auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<StorageResourceDescription> getStorageResourceList(Map<String, String> filters) throws AppCatalogException { try { if (filters.containsKey(DBConstants.StorageResource.HOST_NAME)) { Map<String,Object> queryParameters = new HashMap<>(); queryParameters.put(DBConstants.ComputeResource.HOST_NAME, filters.get(DBConstants.StorageResource.HOST_NAME)); List<StorageResourceDescription> storageResourceDescriptionList = select(QueryConstants.FIND_STORAGE_RESOURCE, -1, 0, queryParameters); return storageResourceDescriptionList; } else { logger.error("Unsupported field name for compute resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported field name for compute resource."); } } catch (Exception e) { logger.error("Error while retrieving storage resource list", e); throw new AppCatalogException(e); } }

Target:
public List<StorageResourceDescription> getStorageResourceList(Map<String, String> filters) throws AppCatalogException { try { if (filters.containsKey(DBConstants.StorageResource.HOST_NAME)) { Map<String,Object> queryParameters = new HashMap<>(); queryParameters.put(DBConstants.ComputeResource.HOST_NAME, filters.get(DBConstants.StorageResource.HOST_NAME)); List<StorageResourceDescription> storageResourceDescriptionList = select(QueryConstants.FIND_STORAGE_RESOURCE, -1, 0, queryParameters); return storageResourceDescriptionList; } else { logger.error("Unsupported field name for compute resource. " + filters.get(DBConstants.StorageResource.HOST_NAME)); throw new IllegalArgumentException("Unsupported field name for compute resource. " + filters.get(DBConstants.StorageResource.HOST_NAME)); } } catch (Exception e) { logger.error("Error while retrieving storage resource list", e); throw new AppCatalogException("Error while retrieving storage resource list", e); } }
Source:
private void prepareFiles() { int fileType = getIntent().getIntExtra(Intents.Extras.FILE_TYPE, FileManager.SERVER_FILE); if (fileType == FileManager.RECENT_FILE) { RecentFileRepository repository = new RecentFileRepository(this); RecentFile recentFile = repository.getRecentFile(getIntent().getStringExtra(Intents.Extras.UNIQUE_KEY)); ServerFile serverFile = new ServerFile(recentFile.getName(), recentFile.getModificationTime(), recentFile.getMime()); serverFile.setSize(recentFile.getSize()); serverFile.setMime(recentFile.getMime()); getIntent().putExtra(Intents.Extras.SERVER_FILE, serverFile); List<ServerFile> serverFiles = new ArrayList<>(); serverFiles.add(serverFile); getIntent().putExtra(Intents.Extras.SERVER_FILES, new ArrayList<Parcelable>(serverFiles)); } NetworkUtils networkUtils = new NetworkUtils(this); if (!networkUtils.isNetworkAvailable()) { Toast.makeText(this, R.string.message_connect_and_try_again, Toast.LENGTH_SHORT).show(); finish(); } }

Target:
private void prepareFiles() { int fileType = getIntent().getIntExtra(Intents.Extras.FILE_TYPE, FileManager.SERVER_FILE); if (fileType == FileManager.RECENT_FILE) { RecentFileRepository repository = new RecentFileRepository(this); RecentFile recentFile = repository.getRecentFile(getIntent().getStringExtra(Intents.Extras.UNIQUE_KEY)); ServerFile serverFile = new ServerFile(recentFile.getName(), recentFile.getModificationTime(), recentFile.getMime()); serverFile.setSize(recentFile.getSize()); serverFile.setMime(recentFile.getMime()); getIntent().putExtra(Intents.Extras.SERVER_FILE, serverFile); List<ServerFile> serverFiles = new ArrayList<>(); serverFiles.add(serverFile); getIntent().putExtra(Intents.Extras.SERVER_FILES, new ArrayList<Parcelable>(serverFiles)); } }
Source:
public Set<String> retrieveSameURIs(String uri) { Set<String> result = null; boolean uriIsCached = false; try { cacheReadMutex.acquire(); } catch (InterruptedException e) { LOGGER.error("Exception while waiting for read mutex. Returning null.", e); return null; } try { uriIsCached = uriSetIdMapping.containsKey(uri); if (uriIsCached) { int setId = uriSetIdMapping.get(uri); if (setId != ENTITY_NOT_FOUND) { result = sets.get(setId); } } } finally { cacheReadMutex.release(); } if (!uriIsCached || (uriIsCached && (result == null) && requestEntitiesNotFound)) { requestUri(uri); } return result; }

Target:
public Set<String> retrieveSameURIs(String uri) { Set<String> result = null; boolean uriIsCached = false; try { cacheReadMutex.acquire(); } catch (InterruptedException e) { LOGGER.error("Exception while waiting for read mutex. Returning null.", e); return null; } try { uriIsCached = uriSetIdMapping.containsKey(uri); if (uriIsCached) { int setId = uriSetIdMapping.get(uri); if (setId != ENTITY_NOT_FOUND) { result = sets.get(setId); } } } finally { cacheReadMutex.release(); } if (!uriIsCached || (uriIsCached && (result == null) && requestEntitiesNotFound)) { result = requestUri(uri); } return result; }
Source:
public boolean registerBlockUpdateListener(final BlockUpdateListener listener) { throw new UnsupportedOperationException("This class doesn't support " + this.getClass().getEnclosingMethod().getName()); }

Target:
public boolean registerBlockUpdateListener(final BlockUpdateListener listener) { throw new NotImplementedException(); }
Source:
public static RowMapperFactory of(Type type, RowMapper<?> mapper) { return (t, ctx) -> t == type ? Optional.of(mapper) : Optional.empty(); }

Target:
public static RowMapperFactory of(Type type, RowMapper<?> mapper) { return (t, ctx) -> t.equals(type) ? Optional.of(mapper) : Optional.empty(); }
Source:
public void applyConfig(Message m, boolean reindex) { XMLDecoder d = new XMLDecoder(new ByteArrayInputStream(m.getText().getBytes())); Configuration config = (Configuration) d.readObject(); d.close(); setConfiguration(config); LOGGER.log(Level.INFO, "Configuration updated: {0}", configuration.getSourceRoot()); if (reindex) { refreshSearcherManagerMap(); maybeRefreshIndexSearchers(); config.refreshDateForLastIndexRun(); } }

Target:
public void applyConfig(Message m, boolean reindex) { Configuration config; try { config = makeXMLStringAsConfiguration(m.getText()); } catch (IOException ex) { LOGGER.log(Level.WARNING, "Configuration decoding failed" + ex); return; } setConfiguration(config); LOGGER.log(Level.INFO, "Configuration updated: {0}", configuration.getSourceRoot()); if (reindex) { refreshSearcherManagerMap(); maybeRefreshIndexSearchers(); config.refreshDateForLastIndexRun(); } }
Source:
@Override public void run() { try { Integer exitStatus = controller.exitStatus(workspace, listener); long lastLocation = 0; FilePath lastLocationFile = controller.getLastLocationFile(workspace); if (lastLocationFile.exists()) { lastLocation = Long.parseLong(lastLocationFile.readToString()); } FilePath logFile = controller.getLogFile(workspace); long len = logFile.length(); if (len > lastLocation) { assert !logFile.isRemote(); try (FileChannel ch = FileChannel.open(Paths.get(logFile.getRemote()), StandardOpenOption.READ)) { CountingInputStream cis = new CountingInputStream(Channels.newInputStream(ch.position(lastLocation))); handler.output(cis); lastLocationFile.write(Long.toString(lastLocation + cis.getByteCount()), null); } } if (exitStatus != null) { byte[] output; if (controller.getOutputFile(workspace).exists()) { output = controller.getOutput(workspace); } else { output = null; } handler.exited(exitStatus, output); controller.cleanup(workspace); } else { watchService().schedule(this, 100, TimeUnit.MILLISECONDS); } } catch (Exception x) { LOGGER.log(Level.WARNING, "giving up on watching " + controller.controlDir, x); } }

Target:
@Override public void run() { try { Integer exitStatus = controller.exitStatus(workspace, listener); long lastLocation = 0; FilePath lastLocationFile = controller.getLastLocationFile(workspace); if (lastLocationFile.exists()) { lastLocation = Long.parseLong(lastLocationFile.readToString()); } FilePath logFile = controller.getLogFile(workspace); long len = logFile.length(); if (len > lastLocation) { assert !logFile.isRemote(); try (FileChannel ch = FileChannel.open(Paths.get(logFile.getRemote()), StandardOpenOption.READ)) { InputStream locallyEncodedStream = Channels.newInputStream(ch.position(lastLocation)); InputStream utf8EncodedStream = cs == null ? locallyEncodedStream : new ReaderInputStream(new InputStreamReader(locallyEncodedStream, cs), StandardCharsets.UTF_8); handler.output(utf8EncodedStream); lastLocationFile.write(Long.toString(ch.position()), null); } } if (exitStatus != null) { byte[] output; if (controller.getOutputFile(workspace).exists()) { output = controller.getOutput(workspace); } else { output = null; } handler.exited(exitStatus, output); controller.cleanup(workspace); } else { if (!controller.controlDir(workspace).isDirectory()) { LOGGER.log(Level.WARNING, "giving up on watching nonexistent {0}", controller.controlDir); return; } watchService().schedule(this, 100, TimeUnit.MILLISECONDS); } } catch (Exception x) { LOGGER.log(Level.WARNING, "giving up on watching " + controller.controlDir, x); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AllelicCount)) { return false; } final AllelicCount count = (AllelicCount) o; return interval.equals(count.interval) && refReadCount == count.refReadCount && altReadCount == count.altReadCount && (!((refNucleotide != null) && (count.refNucleotide != null)) || (refNucleotide == count.refNucleotide)) && (!((altNucleotide != null) && (count.altNucleotide != null)) || (altNucleotide == count.altNucleotide)); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AllelicCount)) { return false; } final AllelicCount count = (AllelicCount) o; return interval.equals(count.interval) && refReadCount == count.refReadCount && altReadCount == count.altReadCount && (((refNucleotide == null) || (count.refNucleotide == null)) || (refNucleotide == count.refNucleotide)) && (((altNucleotide == null) || (count.altNucleotide == null)) || (altNucleotide == count.altNucleotide)); }
Source:
protected QueryResponse addProcessingDetails(Set<ProcessingDetails> exceptions, QueryResponse response) { if (!exceptions.isEmpty()) { if (response == null) { logger.error("Could not add Query exceptions to a QueryResponse because the list of ProcessingDetails was null -- according to the API this should not happen"); } else { Set<ProcessingDetails> sourceDetails = response.getProcessingDetails(); sourceDetails.addAll(exceptions); } } return response; }

Target:
protected QueryResponse addProcessingDetails(Set<ProcessingDetails> exceptions, QueryResponse response) { if (!exceptions.isEmpty()) { if (response == null) { logger.error("Could not add exceptions to response because the response was null"); } else { Set<ProcessingDetails> sourceDetails = response.getProcessingDetails(); if (null != sourceDetails) { sourceDetails.addAll(exceptions); } else { logger.error("Could not add exceptions to response because the response's processing details was null"); } } } return response; }
Source:
public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); this.mCommentLinks = new Vector<CommentLinkInfo>(); CommentLinkInfo http = new CommentLinkInfo("StandardHtmlLinks", httpUrl, "", ""); mCommentLinks.add(http); Set<String> subSections = config.getSubsections(COMMENTLINK); for (String subSection : subSections) { String match = config.getString("commentlink", subSection, "match"); String link = config.getString("commentlink", subSection, "link"); String html = config.getString("commentlink", subSection, "link"); mCommentLinks.add(new CommentLinkInfo(subSection, match, link, html)); } }

Target:
public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); String regexp = REGEXP_HTTP_CHANGE_ID; List<CommentLinkInfo> list = new ArrayList<CommentLinkInfo>(); list.add(new CommentLinkInfo("StandardHtmlLinks", HTTP_URL_PATTERN, "", "")); Set<String> subsections = config.getSubsections(COMMENTLINK); for (String subsection : subsections) { String match = config.getString("commentlink", subsection, "match"); String link = config.getString("commentlink", subsection, "link"); String html = config.getString("commentlink", subsection, "html"); checkArgument(!Strings.isNullOrEmpty(match), "invalid commentlink.%s.match", subsection); try { Pattern compiledPattern = Pattern.compile(match); list.add(new CommentLinkInfo(subsection, compiledPattern, link, html)); regexp += "|(" + match + ")"; } catch (RuntimeException err) { System.err.println("Ommiting commentlink " + subsection); } } this.commentLinks = Collections.unmodifiableList(list); try { allPattern = Pattern.compile(regexp); } catch (RuntimeException err) { System.err.println("Could not compile all commentlinks as a whole"); } }
Source:
public ILocation getLocation() { LineRange selectedRange = getSelectedRange(); ILineLocation location = ReviewsFactory.eINSTANCE.createLineLocation(); ILineRange range = ReviewsFactory.eINSTANCE.createLineRange(); range.setStart(selectedRange.getStartLine()); range.setEnd(selectedRange.getStartLine() + selectedRange.getNumberOfLines()); location.getRanges().add(range); return location; }

Target:
private ILocation getLocation() { LineRange selectedRange = getSelectedRange(); ILineLocation location = ReviewsFactory.eINSTANCE.createLineLocation(); ILineRange range = ReviewsFactory.eINSTANCE.createLineRange(); range.setStart(selectedRange.getStartLine()); range.setEnd(selectedRange.getStartLine() + selectedRange.getNumberOfLines()); location.getRanges().add(range); return location; }
Source:
private void createResourceGroup(EnvironmentDto environmentDto, Environment environment) { if (!azureSingleResourceGroupFeatureSwitch.isActive()) { LOGGER.debug("Azure single resource group feature turned off, not creating resourcegroup."); return; } Optional<AzureResourceGroupDto> azureResourceGroupDtoOptional = getAzureResourceGroupDto(environmentDto); if (!AZURE.name().equals(environmentDto.getCloudPlatform()) || azureResourceGroupDtoOptional.isEmpty()) { LOGGER.debug("Cloudplatform not azure or no azure resource group dto defined, not creating resource group."); return; } AzureResourceGroupDto azureResourceGroupDto = azureResourceGroupDtoOptional.get(); if (!CREATE_NEW.equals(azureResourceGroupDto.getResourceGroupCreation())) { LOGGER.debug("Azure resource group creation not requested, not creating resource group."); return; } CloudCredential cloudCredential = credentialToCloudCredentialConverter.convert(environmentDto.getCredential()); AzureClient azureClient = azureClientService.getClient(cloudCredential); String resourceGroupName = String.format("%s_%d", environmentDto.getName(), clock.getCurrentTimeMillis()); LOGGER.debug("Azure generated resource group name: {}.", resourceGroupName); azureClient.createResourceGroup(resourceGroupName, environmentDto.getLocation().getName(), mergeTags(environmentDto)); parameterService.updateResourceGroupName(environment, resourceGroupName); LOGGER.debug("Azure resource group created successfully."); }

Target:
private void createResourceGroup(EnvironmentDto environmentDto, Environment environment) { if (!azureSingleResourceGroupFeatureSwitch.isActive()) { LOGGER.debug("Azure single resource group feature turned off, not creating resourcegroup."); return; } Optional<AzureResourceGroupDto> azureResourceGroupDtoOptional = getAzureResourceGroupDto(environmentDto); if (azureResourceGroupDtoOptional.isEmpty()) { LOGGER.debug("No azure resource group dto defined, not creating resource group."); return; } AzureResourceGroupDto azureResourceGroupDto = azureResourceGroupDtoOptional.get(); if (!CREATE_NEW.equals(azureResourceGroupDto.getResourceGroupCreation())) { LOGGER.debug("New single azure resource group creation not requested, not creating resource group."); return; } String resourceGroupName = String.format("%s_%d", environmentDto.getName(), clock.getCurrentTimeMillis()); LOGGER.debug("Azure generated resource group name: {}.", resourceGroupName); createResourceGroup(environmentDto, resourceGroupName); parameterService.updateResourceGroupName(environment, resourceGroupName); LOGGER.debug("Azure resource group created successfully."); }
Source:
@Override protected boolean isApplicable(MultiBranchProjectDescriptor projectDescriptor) { for (BranchProjectFactoryDescriptor d : projectDescriptor.getProjectFactoryDescriptors()) { Type factoryType = Types.getBaseClass(d.clazz, BranchProjectFactory.class); Type jobType = Types.getTypeArgument(factoryType, 0, Project.class); if (Project.class.isAssignableFrom(Types.erasure(jobType))) { return true; } } return false; }

Target:
protected boolean isApplicable(MultiBranchProjectDescriptor projectDescriptor) { for (BranchProjectFactoryDescriptor d : projectDescriptor.getProjectFactoryDescriptors()) { Type factoryType = Types.getBaseClass(d.clazz, BranchProjectFactory.class); Type jobType = Types.getTypeArgument(factoryType, 0, Project.class); if (Project.class.isAssignableFrom(Types.erasure(jobType))) { return true; } } return false; }
Source:
@Test public void peekMaxCanBeSmallerThanQueueDepth() { List<String> peek = queue.peek(2); assertThat(peek).hasSize(2); assertThat(peek).containsSequence("one", "two"); }

Target:
@Test public void peekMaxCanBeSmallerThanQueueDepth() { List<String> peek = queue.peek(2); assertThat(peek).containsExactly("one", "two"); }
Source:
private static int getHttpServicePortProperty(final BundleContext bc, final String propertyName) { Object value; int port = -1; ServiceReference<?>[] refs = new ServiceReference[0]; try { refs = bc.getAllServiceReferences("org.osgi.service.http.HttpService", null); } catch (final InvalidSyntaxException ex) { final Logger logger = LoggerFactory.getLogger(HttpServiceUtil.class); logger.warn("This error should only be thrown if a filter could not be parsed. We don't use a filter..."); } int candidate = Integer.MIN_VALUE; for (final ServiceReference<?> ref : refs) { value = ref.getProperty(propertyName); if (value == null) { continue; } final int servicePort; try { servicePort = Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { continue; } value = ref.getProperty(Constants.SERVICE_RANKING); final int serviceRanking; if (value == null || !(value instanceof Integer)) { serviceRanking = 0; } else { serviceRanking = (Integer) value; } if (serviceRanking >= candidate) { candidate = serviceRanking; port = servicePort; } } if (port > 0) { return port; } value = bc.getProperty(propertyName); if (value != null) { if (value instanceof String) { try { return Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { } } else if (value instanceof Integer) { return (Integer) value; } } return -1; }

Target:
private static int getHttpServicePortProperty(final BundleContext bc, final String propertyName) { Object value; int port = -1; final ServiceReference<?>[] refs; try { refs = bc.getAllServiceReferences("org.osgi.service.http.HttpService", null); } catch (final InvalidSyntaxException ex) { final Logger logger = LoggerFactory.getLogger(HttpServiceUtil.class); logger.warn("This error should only be thrown if a filter could not be parsed. We don't use a filter..."); return -1; } int candidate = Integer.MIN_VALUE; for (final ServiceReference<?> ref : refs) { value = ref.getProperty(propertyName); if (value == null) { continue; } final int servicePort; try { servicePort = Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { continue; } value = ref.getProperty(Constants.SERVICE_RANKING); final int serviceRanking; if (value == null || !(value instanceof Integer)) { serviceRanking = 0; } else { serviceRanking = (Integer) value; } if (serviceRanking >= candidate) { candidate = serviceRanking; port = servicePort; } } if (port > 0) { return port; } value = bc.getProperty(propertyName); if (value != null) { if (value instanceof String) { try { return Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { } } else if (value instanceof Integer) { return (Integer) value; } } return -1; }
Source:
public void onPost(final GitLabMergeRequest req) { final ParameterizedJobMixIn scheduledJob = new ParameterizedJobMixIn() { @Override protected Job asJob() { return job; } }; if (triggerOnMergeRequest && this.isBranchAllowed(req.getObjectAttribute().getTargetBranch())) { LOGGER.log(Level.INFO, "{0} triggered for merge request.", job.getFullName()); GitLabMergeCause cause = createGitLabMergeCause(req); Action action = createAction(req, job); int projectbuildDelay = 0; if (job instanceof ParameterizedJobMixIn.ParameterizedJob) { ParameterizedJobMixIn.ParameterizedJob abstractProject = (ParameterizedJobMixIn.ParameterizedJob)job; if (abstractProject.getQuietPeriod() > projectbuildDelay) { projectbuildDelay = abstractProject.getQuietPeriod(); } } if(addCiMessage) { req.createCommitStatus(getDescriptor().getGitlab().instance(), "pending", Jenkins.getInstance().getRootUrl() + job.getUrl()); } scheduledJob.scheduleBuild2(projectbuildDelay, action, new CauseAction(cause)); } else { if (triggerOnMergeRequest ) { LOGGER.log(Level.INFO, "trigger on merge request not set"); } else if ( this.isBranchAllowed(req.getObjectAttribute().getTargetBranch())) { LOGGER.log(Level.INFO, "branch {0} is not allowed", req.getObjectAttribute().getTargetBranch()); } } }

Target:
public void onPost(final GitLabMergeRequest req) { final ParameterizedJobMixIn scheduledJob = new ParameterizedJobMixIn() { @Override protected Job asJob() { return job; } }; if (triggerOnMergeRequest && this.isBranchAllowed(req.getObjectAttribute().getTargetBranch())) { LOGGER.log(Level.INFO, "{0} triggered for merge request.", job.getFullName()); GitLabMergeCause cause = createGitLabMergeCause(req); Action action = createAction(req, job); int projectbuildDelay = 0; if (job instanceof ParameterizedJobMixIn.ParameterizedJob) { ParameterizedJobMixIn.ParameterizedJob abstractProject = (ParameterizedJobMixIn.ParameterizedJob)job; if (abstractProject.getQuietPeriod() > projectbuildDelay) { projectbuildDelay = abstractProject.getQuietPeriod(); } } if(addCiMessage) { req.createCommitStatus(getDescriptor().getGitlab().instance(), "pending", Jenkins.getInstance().getRootUrl() + job.getUrl()); } scheduledJob.scheduleBuild2(projectbuildDelay, action, new CauseAction(cause)); } else if ( ! triggerOnMergeRequest ) { LOGGER.log(Level.INFO, "trigger on merge request not set"); } else { LOGGER.log(Level.INFO, "branch {0} is not allowed", req.getObjectAttribute().getTargetBranch()); } }
Source:
public void validateAccessToken(String accessToken, boolean atHashRequired) { if (!Strings.isNullOrEmpty(accessToken)) { String atHash = idToken.getClaims().getClaimAsString("at_hash"); if (Strings.isNullOrEmpty(atHash)) { if(atHashRequired) { LOG.error("`at_hash` is missing in `ID_TOKEN`."); throw new HttpException(ErrorResponseCode.AT_HASH_NOT_FOUND); } else { LOG.warn("Skip access_token validation because corresponding id_token does not have at_hash claim. access_token: " + accessToken + ", id_token: " + idToken); return; } } if (!jwsSigner.validateAccessToken(accessToken, idToken)) { LOG.error("Hash from id_token does not match hash of the access_token (at_hash). access_token:" + accessToken + ", idToken: " + idToken + ", at_hash:" + atHash); throw new HttpException(ErrorResponseCode.INVALID_ACCESS_TOKEN_BAD_HASH); } } }

Target:
public void validateAccessToken(String accessToken, boolean atHashRequired) { if (!configuration.getIdTokenValidationAtHashRequired()) { return; } if (Strings.isNullOrEmpty(accessToken)) { return; } String atHash = idToken.getClaims().getClaimAsString("at_hash"); if (Strings.isNullOrEmpty(atHash)) { if (atHashRequired) { LOG.error("`at_hash` is missing in `ID_TOKEN`."); throw new HttpException(ErrorResponseCode.AT_HASH_NOT_FOUND); } else { LOG.warn("Skip access_token validation because corresponding id_token does not have at_hash claim. access_token: " + accessToken + ", id_token: " + idToken); return; } } if (!jwsSigner.validateAccessToken(accessToken, idToken)) { LOG.error("Hash from id_token does not match hash of the access_token (at_hash). access_token:" + accessToken + ", idToken: " + idToken + ", at_hash:" + atHash); throw new HttpException(ErrorResponseCode.INVALID_ACCESS_TOKEN_BAD_HASH); } }
Source:
public void testCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerFrameDeflateDecoder(false, NEVER_SKIP)); byte[] payload = new byte[300]; random.nextBytes(payload); encoderChannel.writeOutbound(Unpooled.wrappedBuffer(payload)); ByteBuf compressedPayload = encoderChannel.readOutbound(); BinaryWebSocketFrame compressedFrame = new BinaryWebSocketFrame(true, RSV1 | RSV3, compressedPayload.slice(0, compressedPayload.readableBytes() - 4)); decoderChannel.writeInbound(compressedFrame); BinaryWebSocketFrame uncompressedFrame = decoderChannel.readInbound(); assertNotNull(uncompressedFrame); assertNotNull(uncompressedFrame.content()); assertEquals(RSV3, uncompressedFrame.rsv()); assertEquals(300, uncompressedFrame.content().readableBytes()); byte[] finalPayload = new byte[300]; uncompressedFrame.content().readBytes(finalPayload); assertArrayEquals(finalPayload, payload); uncompressedFrame.release(); }

Target:
public void testCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel( ZlibCodecFactory.newZlibEncoder(ZlibWrapper.NONE, 9, 15, 8)); EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerFrameDeflateDecoder(false)); byte[] payload = new byte[300]; random.nextBytes(payload); assertTrue(encoderChannel.writeOutbound(Unpooled.wrappedBuffer(payload))); ByteBuf compressedPayload = encoderChannel.readOutbound(); BinaryWebSocketFrame compressedFrame = new BinaryWebSocketFrame(true, RSV1 | RSV3, compressedPayload.slice(0, compressedPayload.readableBytes() - 4)); assertTrue(decoderChannel.writeInbound(compressedFrame)); BinaryWebSocketFrame uncompressedFrame = decoderChannel.readInbound(); assertNotNull(uncompressedFrame); assertNotNull(uncompressedFrame.content()); assertEquals(RSV3, uncompressedFrame.rsv()); assertEquals(300, uncompressedFrame.content().readableBytes()); byte[] finalPayload = new byte[300]; uncompressedFrame.content().readBytes(finalPayload); assertArrayEquals(finalPayload, payload); uncompressedFrame.release(); }
Source:
public static NotificationConfig<DownloadBatchStatus> createDownloadNotificationConfig(Context context, String channelId, String channelDescription, final int iconDrawable) { NotificationCustomizer<DownloadBatchStatus> notificationCustomizer = new NotificationCustomizer<DownloadBatchStatus>() { @Override public Notification customNotificationFrom(NotificationCompat.Builder builder, DownloadBatchStatus downloadBatchStatus) { DownloadBatchTitle downloadBatchTitle = downloadBatchStatus.getDownloadBatchTitle(); int percentageDownloaded = downloadBatchStatus.percentageDownloaded(); int bytesFileSize = (int) downloadBatchStatus.bytesTotalSize(); int bytesDownloaded = (int) downloadBatchStatus.bytesDownloaded(); String title = downloadBatchTitle.asString(); String content = percentageDownloaded + "% downloaded"; Log.v("Create notification for " + title + ", " + content); return builder .setProgress(bytesFileSize, bytesDownloaded, NOT_INDETERMINATE) .setSmallIcon(iconDrawable) .setContentTitle(title) .setContentText(content) .build(); } }; return new NotificationConfig<>( context, channelId, channelDescription, notificationCustomizer, NotificationManagerCompat.IMPORTANCE_LOW ); }

Target:
public static NotificationConfig<DownloadBatchStatus> createDownloadNotificationConfig(Context context, String channelId, String channelDescription, final int iconDrawable) { NotificationCustomizer<DownloadBatchStatus> notificationCustomizer = new DownloadNotificationCustomizer(iconDrawable); return new NotificationConfig<>( context, channelId, channelDescription, notificationCustomizer, NotificationManagerCompat.IMPORTANCE_LOW ); }
Source:
public LongRunningOperationStatus getOperationStatus() { switch (this.pollingType) { case AZURE_ASYNC_OPERATION_POLL: return toLongRunningOperationStatus(this.azureAsyncOperationData.getProvisioningState()); case LOCATION_POLL: return toLongRunningOperationStatus(this.locationData.getProvisioningState()); case PROVISIONING_STATE_POLL: return toLongRunningOperationStatus(this.provisioningStateData.getProvisioningState()); case SYNCHRONOUSLY_SUCCEEDED_LRO_NO_POLL: return LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; case SYNCHRONOUSLY_FAILED_LRO_NO_POLL: return LongRunningOperationStatus.FAILED; default: throw LOGGER.logExceptionAsError(new IllegalStateException("Unknown pollingType:" + this.pollingType)); } }

Target:
LongRunningOperationStatus getOperationStatus() { switch (this.pollingType) { case AZURE_ASYNC_OPERATION_POLL: return toLongRunningOperationStatus(this.azureAsyncOperationData.getProvisioningState()); case LOCATION_POLL: return toLongRunningOperationStatus(this.locationData.getProvisioningState()); case PROVISIONING_STATE_POLL: return toLongRunningOperationStatus(this.provisioningStateData.getProvisioningState()); case SYNCHRONOUSLY_SUCCEEDED_LRO_NO_POLL: return LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; case SYNCHRONOUSLY_FAILED_LRO_NO_POLL: return LongRunningOperationStatus.FAILED; default: throw LOGGER.logExceptionAsError(new IllegalStateException("Unknown pollingType:" + this.pollingType)); } }
Source:
public void clearAsyncTask(boolean forceDelete) { VDSReturnValue vdsReturnValue = null; try { log.info("SPMAsyncTask::ClearAsyncTask: Attempting to clear task '{}'", getVdsmTaskId()); vdsReturnValue = coco.clearTask(getStoragePoolID(), getVdsmTaskId()); } catch (RuntimeException e) { log.error("SPMAsyncTask::ClearAsyncTask: Clearing task '{}' threw an exception: {}", getVdsmTaskId(), e.getMessage()); log.error("Exception", e); } boolean shouldGracefullyDeleteTask = false; if (!isTaskStateError(vdsReturnValue)) { if (vdsReturnValue == null || !vdsReturnValue.getSucceeded()) { setState(AsyncTaskState.ClearFailed); onTaskCleanFailure(); } else { setState(AsyncTaskState.Cleared); shouldGracefullyDeleteTask = true; } } if (shouldGracefullyDeleteTask || forceDelete) { removeTaskFromDB(); } }

Target:
public void clearAsyncTask(boolean forceDelete) { VDSReturnValue vdsReturnValue = null; try { log.info("SPMAsyncTask::ClearAsyncTask: Attempting to clear task '{}'", getVdsmTaskId()); vdsReturnValue = coco.clearTask(getStoragePoolID(), getVdsmTaskId()); } catch (RuntimeException e) { log.error("SPMAsyncTask::ClearAsyncTask: Error during clearing task '{}': {}", getVdsmTaskId(), e.getMessage()); log.error("Exception", e); } boolean shouldGracefullyDeleteTask = false; if (!isTaskStateError(vdsReturnValue)) { if (vdsReturnValue == null || !vdsReturnValue.getSucceeded()) { setState(AsyncTaskState.ClearFailed); onTaskCleanFailure(); } else { setState(AsyncTaskState.Cleared); shouldGracefullyDeleteTask = true; } } if (shouldGracefullyDeleteTask || forceDelete) { removeTaskFromDB(); } }
Source:
private static Intent getFeedbackEmailIntent(Context context) { String email; try { email = context.getString(R.string.amp_feedback_email); } catch (Resources.NotFoundException e) { throw new IllegalArgumentException("R.string.amp_feedback_email resource not found, you must set this in your strings file for the" + " feedback util to function", e); } final String feedbackMailTo = "mailto:" + email; final String feedbackEmailSubject = Uri.encode("Android App Feedback", "UTF-8"); final String appInfo = getAppInfo(context); final String uriString = feedbackMailTo + "?subject=" + feedbackEmailSubject + "&body=" + Uri.encode(appInfo); final Uri uri = Uri.parse(uriString); final Intent emailIntent = new Intent(Intent.ACTION_SENDTO); emailIntent.setData(uri); return emailIntent; }

Target:
private static Intent getFeedbackEmailIntent(Context context) { final String feedbackEmailSubject = Uri.encode("Android App Feedback", "UTF-8"); final String appInfo = getAppInfo(context); final StringBuilder uriStringBuilder = new StringBuilder("mailto:"); try { uriStringBuilder.append(context.getString(R.string.amp_feedback_email)); } catch (Resources.NotFoundException e) { IllegalArgumentException illegalArgumentException = new IllegalArgumentException("R.string.amp_feedback_email" + "resource not found, you must set this in your strings file for the feedback util to function", e); Log.d(TAG, "ResourceNotFound", illegalArgumentException); } uriStringBuilder.append("?subject=") .append(feedbackEmailSubject) .append("&body=") .append(appInfo); final Uri uri = Uri.parse(uriStringBuilder.toString()); return new Intent(Intent.ACTION_SENDTO, uri); }
Source:
public void cancelTransactionShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.cancelTransaction("foo", "bar", new RetrofitPromise<Transaction>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards/%s/transactions/%s/cancel", MOCK_URL, "foo", "bar")); Assert.assertEquals(bodyRef.get().getMethod(), "POST"); }

Target:
public void cancelTransactionShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.cancelTransaction("foo", "bar", new RetrofitPromise<Transaction>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "POST"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards/%s/transactions/%s/cancel", MOCK_URL, "foo", "bar")); }
Source:
public void validateDetailCount(ConcurStandardAccountingExtractFile concurStandardAccountingExtractFile) throws ValidationException { Integer numberOfDetailsInHeader = concurStandardAccountingExtractFile.getRecordCount(); int actualNumberOfDetails = concurStandardAccountingExtractFile.getConcurStandardAccountingExtractDetailLines().size(); if (numberOfDetailsInHeader.intValue() != actualNumberOfDetails) { String message = "The header said there were " + numberOfDetailsInHeader + " the but the actual number of details was " + actualNumberOfDetails; LOG.debug("validateDetailCount, " + message); throw new ValidationException(message); } else { if (LOG.isDebugEnabled()) { LOG.debug("validateDetailCount, Number of detail lines is what we expected."); } } }

Target:
public boolean validateDetailCount(ConcurStandardAccountingExtractFile concurStandardAccountingExtractFile) { Integer numberOfDetailsInHeader = concurStandardAccountingExtractFile.getRecordCount(); int actualNumberOfDetails = concurStandardAccountingExtractFile.getConcurStandardAccountingExtractDetailLines().size(); boolean valid = numberOfDetailsInHeader.intValue() == actualNumberOfDetails; if (valid) { LOG.debug("validateDetailCount, Number of detail lines is what we expected: " + actualNumberOfDetails); } else { LOG.error("validateDetailCount, The header said there were (" + numberOfDetailsInHeader + ") detail lines expected, but the actual number of details were (" + actualNumberOfDetails + ")"); } return valid; }
Source:
public AnalyzerProvider() { factTypes.add( new FactTypes.FactType( "Applicant", new HashSet<FactTypes.Field>() {{ add( new FactTypes.Field( "age", DataType.TYPE_NUMERIC_INTEGER ) ); }} ) ); factTypes.add( new FactTypes.FactType( "Account", new HashSet<FactTypes.Field>() {{ add( new FactTypes.Field( "deposit", DataType.TYPE_NUMERIC_DOUBLE ) ); }} ) ); factTypes.add( new FactTypes.FactType( "Person", new HashSet<FactTypes.Field>() {{ add( new FactTypes.Field( "age", DataType.TYPE_NUMERIC_INTEGER ) ); add( new FactTypes.Field( "name", DataType.TYPE_STRING ) ); add( new FactTypes.Field( "lastName", DataType.TYPE_STRING ) ); add( new FactTypes.Field( "description", DataType.TYPE_STRING ) ); add( new FactTypes.Field( "approved", DataType.TYPE_BOOLEAN ) ); add( new FactTypes.Field( "salary", DataType.TYPE_NUMERIC_INTEGER ) ); }} ) ); }

Target:
public AnalyzerProvider() { factTypes.add(new FactTypes.FactType("Applicant", Collections.singleton(new FactTypes.Field("age", DataType.TYPE_NUMERIC_INTEGER)))); factTypes.add(new FactTypes.FactType("Account", new HashSet<FactTypes.Field>() {{ add(new FactTypes.Field("deposit", DataType.TYPE_NUMERIC_DOUBLE)); }})); factTypes.add(new FactTypes.FactType("Person", new HashSet<FactTypes.Field>() {{ add(new FactTypes.Field("age", DataType.TYPE_NUMERIC_INTEGER)); add(new FactTypes.Field("name", DataType.TYPE_STRING)); add(new FactTypes.Field("lastName", DataType.TYPE_STRING)); add(new FactTypes.Field("description", DataType.TYPE_STRING)); add(new FactTypes.Field("approved", DataType.TYPE_BOOLEAN)); add(new FactTypes.Field("salary", DataType.TYPE_NUMERIC_INTEGER)); }})); }
Source:
void deleteIfManaged() throws InfrastructureException { KubernetesClient client = clientFactory.create(workspaceId); if (!isNamespaceManaged(client)) { LOG.debug( "Namespace for workspace is not marked as managed. Ignoring the delete request.", name, workspaceId); return; } try { delete(name, client); } catch (KubernetesClientException e) { if (e.getCode() == 403) { throw new InfrastructureException( format( "Could not access the namespace %s when deleting it for workspace %s", name, workspaceId), e); } throw new KubernetesInfrastructureException(e); } }

Target:
void deleteIfManaged() throws InfrastructureException { KubernetesClient client = clientFactory.create(workspaceId); if (!isNamespaceManaged(client)) { LOG.info( "Namespace for workspace is not marked as managed. Ignoring the delete request.", name, workspaceId); return; } try { delete(name, client); } catch (KubernetesClientException e) { if (e.getCode() == 403) { throw new InfrastructureException( format( "Could not access the namespace %s when deleting it for workspace %s", name, workspaceId), e); } throw new KubernetesInfrastructureException(e); } }
Source:
public IdentityProvider[] getAllIdPs() throws IdentityProviderManagementException { try { String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); List<IdentityProvider> identityProviders = IdentityProviderManager.getInstance().getIdPs(tenantDomain); for (int i = 0; i < identityProviders.size(); i++) { String providerName = identityProviders.get(i).getIdentityProviderName(); if (providerName != null && providerName.startsWith(IdPManagementConstants.SHARED_IDP_PREFIX)) { identityProviders.remove(i); i--; } } return identityProviders.toArray(new IdentityProvider[identityProviders.size()]); } catch (IdentityProviderManagementException idpException) { log.error("Error while getting IdPs", idpException); throw idpException; } }

Target:
public IdentityProvider[] getAllIdPs() throws IdentityProviderManagementException { String tenantDomain = ""; try { tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); List<IdentityProvider> identityProviders = IdentityProviderManager.getInstance().getIdPs(tenantDomain); for (int i = 0; i < identityProviders.size(); i++) { String providerName = identityProviders.get(i).getIdentityProviderName(); if (providerName != null && providerName.startsWith(IdPManagementConstants.SHARED_IDP_PREFIX)) { identityProviders.remove(i); i--; } } return identityProviders.toArray(new IdentityProvider[identityProviders.size()]); } catch (IdentityProviderManagementException idpException) { log.error("Error while getting IdPs in tenantDomain : " + tenantDomain, idpException); throw idpException; } }
Source:
public Optional<KiePMMLModel> getModel(String modelName) { logger.trace("getModel {}", modelName); return KnowledgeBaseUtils.getModel(knowledgeBase, modelName); }

Target:
public Optional<KiePMMLModel> getModel(String modelName) { return KnowledgeBaseUtils.getModel(knowledgeBase, modelName); }
Source:
public boolean validate() { getName().validateEntity(new IValidation[] { new NotEmptyValidation(), new LengthValidation(40), new LengthValidation(getMaxNameLength()), new AsciiNameValidation() }); getStorageTypeList().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); getVersion().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); getDescription().validateEntity(new IValidation[] { new AsciiOrNoneValidation() }); getComment().validateEntity(new IValidation[] { new AsciiOrNoneValidation() }); return getName().getIsValid() && getDescription().getIsValid() && getComment().getIsValid() && getStorageTypeList().getIsValid() && getVersion().getIsValid(); }

Target:
public boolean validate() { getName().validateEntity(new IValidation[] { new NotEmptyValidation(), new LengthValidation(40), new LengthValidation(getMaxNameLength()), new AsciiNameValidation() }); getStorageTypeList().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); getVersion().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); getDescription().validateEntity(new IValidation[] { new AsciiOrNoneValidation() }); getComment().validateEntity(new IValidation[] { new SpecialAsciiI18NOrNoneValidation() }); return getName().getIsValid() && getDescription().getIsValid() && getComment().getIsValid() && getStorageTypeList().getIsValid() && getVersion().getIsValid(); }
Source:
public void prepare(Object o) { executor = MoreExecutors.listeningDecorator(newFixedThreadPoolWithQueueSize(5, 20)); Preconditions.checkNotNull(providerQueue); Preconditions.checkNotNull(this.klass); Preconditions.checkNotNull(config.getOauth().getConsumerKey()); Preconditions.checkNotNull(config.getOauth().getConsumerSecret()); Preconditions.checkNotNull(config.getOauth().getAccessToken()); Preconditions.checkNotNull(config.getOauth().getAccessTokenSecret()); Preconditions.checkNotNull(config.getFollow()); idsCount = config.getFollow().size(); ids = config.getFollow().iterator(); jsonStoreEnabled = Optional.fromNullable(new Boolean(Boolean.parseBoolean(config.getJsonStoreEnabled()))).or(true); includeEntitiesEnabled = Optional.fromNullable(new Boolean(Boolean.parseBoolean(config.getIncludeEntities()))).or(true); client = getTwitterClient(); providerQueue = constructQueue(); }

Target:
public void prepare(Object o) { executor = MoreExecutors.listeningDecorator(newFixedThreadPoolWithQueueSize(5, 20)); try { lock.writeLock().lock(); providerQueue = constructQueue(); } finally { lock.writeLock().unlock(); } Preconditions.checkNotNull(providerQueue); Preconditions.checkNotNull(this.klass); Preconditions.checkNotNull(config.getOauth().getConsumerKey()); Preconditions.checkNotNull(config.getOauth().getConsumerSecret()); Preconditions.checkNotNull(config.getOauth().getAccessToken()); Preconditions.checkNotNull(config.getOauth().getAccessTokenSecret()); Preconditions.checkNotNull(config.getFollow()); idsCount = config.getFollow().size(); ids = config.getFollow().iterator(); jsonStoreEnabled = Optional.fromNullable(new Boolean(Boolean.parseBoolean(config.getJsonStoreEnabled()))).or(true); includeEntitiesEnabled = Optional.fromNullable(new Boolean(Boolean.parseBoolean(config.getIncludeEntities()))).or(true); client = getTwitterClient(); }
Source:
public Map<String, Object> aggregate(long windowId, Collection<AutoMetric.PhysicalMetricsContext> physicalMetrics) { return null; }

Target:
public Map<String, Object> aggregate(long windowId, Collection<AutoMetric.PhysicalMetricsContext> physicalMetrics) { result.put("progress", physicalMetrics.iterator().next().getMetrics().get("progress")); latch.countDown(); return result; }
Source:
void closeAllWriters() { if (m_hasClosed) return; for (Entry<FileHandle, CSVWriter> entry : m_writers.entrySet()) { CSVWriter writer = entry.getValue(); if (writer == null) { m_logger.info("Null writer found for: " + entry.getKey().toString()); continue; } try { writer.flush(); writer.close(); } catch (IOException e) { m_logger.error("Failed to flush or close file, " + entry.getKey().getActivePath() + ". Export file may be unavailable/unwritable, or not enough space.", e); } finally { if (writer.checkError()) { m_logger.error("Failed to flush or close file, " + entry.getKey().getActivePath() + ". Export file may be unavailable/unwritable, or not enough space."); } } } if (m_batched) { closeBatch(); } else { closeFiles(); } m_writers.clear(); m_hasClosed = true; }

Target:
void closeAllWriters() { if (m_hasClosed) return; for (Entry<FileHandle, CSVWriter> entry : m_writers.entrySet()) { CSVWriter writer = entry.getValue(); if (writer == null) { m_logger.info("Null writer found for: " + entry.getKey().toString()); continue; } try { writer.flush(); writer.close(); } catch (IOException e) { m_logger.error("Failed to flush or close file '" + entry.getKey().getActivePath() + "'. Export file may be unavailable/unwritable, or not enough space.", e); } finally { if (writer.checkError()) { m_logger.error("Failed to flush or close file '" + entry.getKey().getActivePath() + "'. Export file may be unavailable/unwritable, or not enough space."); } } } if (m_batched) { closeBatch(); } else { closeFiles(); } m_writers.clear(); m_hasClosed = true; }
Source:
public ReadMapContextJob(MapElement editableMap) { this.editableMap = editableMap; Services.registerService(MapElement.class, I18N.tr("Access to the MapElement"), editableMap); }

Target:
public ReadMapContextJob(MapElement editableMap) { this.editableMap = editableMap; }
Source:
protected ExecutorService getDeferredCloseExecutor() { if (null != getExecutorService()) { return getExecutorService(); } synchronized (this.connectionMonitor) { if (null == this.deferredCloseExecutor) { this.deferredCloseExecutor = Executors.newCachedThreadPool(new AmqpNamedThreadPoolFactory()); } } return this.deferredCloseExecutor; }

Target:
protected ExecutorService getDeferredCloseExecutor() { if (null != getExecutorService()) { return getExecutorService(); } synchronized (this.connectionMonitor) { if (null == this.deferredCloseExecutor) { final String threadPrefix = (null == getBeanName()) ? DEFAULT_DEFERRED_POOL_PREFIX + threadPoolId.incrementAndGet() : getBeanName(); ThreadFactory threadPoolFactory = new CustomizableThreadFactory(threadPrefix); this.deferredCloseExecutor = Executors.newCachedThreadPool(threadPoolFactory); } } return this.deferredCloseExecutor; }
Source:
public SAMRecord next() { if (!hasNext()) { return null; } return nextUnalignment(); }

Target:
public SAMRecord next() { if (!hasNext()) { throw new NoSuchElementException("No more alignments are available"); } return nextUnalignment(); }
Source:
protected NuxeoPrincipal getAuthor(DocumentModel docModel) { String author = null; if (docModel.hasSchema(COMMENT_SCHEMA)) { author = (String) docModel.getPropertyValue(COMMENT_AUTHOR); } if (StringUtils.isBlank(author)) { String[] contributors = (String[]) docModel.getPropertyValue("dc:contributors"); author = contributors[0]; } NuxeoPrincipal principal = Framework.getService(UserManager.class).getPrincipal(author); if (principal == null) { log.debug("Principal not found: " + principal); } return principal; }

Target:
protected NuxeoPrincipal getAuthor(DocumentModel docModel) { String author = null; if (docModel.hasSchema(COMMENT_SCHEMA)) { author = (String) docModel.getPropertyValue(COMMENT_AUTHOR); } if (StringUtils.isBlank(author)) { String[] contributors = (String[]) docModel.getPropertyValue("dc:contributors"); author = contributors[0]; } NuxeoPrincipal principal = Framework.getService(UserManager.class).getPrincipal(author); if (principal == null) { log.debug("Principal not found: " + author); } return principal; }