auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String templateAuswahlAuswerten() throws DAOException { Process tempProzess = serviceManager.getProcessService().getById(this.auswahl); if (serviceManager.getProcessService().getWorkpiecesSize(tempProzess) > 0) { for (Property workpieceProperty : tempProzess.getWorkpieces()) { for (AdditionalField field : this.additionalFields) { if (field.getTitle().equals(workpieceProperty.getTitle())) { field.setValue(workpieceProperty.getValue()); } } } } if (serviceManager.getProcessService().getTemplatesSize(tempProzess) > 0) { for (Property templateProperty : tempProzess.getTemplates()) { for (AdditionalField field : this.additionalFields) { if (field.getTitle().equals(templateProperty.getTitle())) { field.setValue(templateProperty.getValue()); } } } } try { this.myRdf = serviceManager.getProcessService().readMetadataAsTemplateFile(tempProzess); } catch (Exception e) { logger.error("Fehler beim Einlesen der Template-Metadaten ", e); Helper.setFehlerMeldung("Fehler beim Einlesen der Template-Metadaten ", e); } try { DocStructInterface colStruct = this.myRdf.getDigitalDocument().getLogicalDocStruct(); removeCollections(colStruct); colStruct = colStruct.getAllChildren().get(0); removeCollections(colStruct); } catch (PreferencesException e) { Helper.setFehlerMeldung("Fehler beim Anlegen des Vorgangs", e); logger.error("Fehler beim Anlegen des Vorgangs", e); } catch (RuntimeException e) { } return ""; }

Target:
public String templateAuswahlAuswerten() throws DAOException { Process tempProzess = serviceManager.getProcessService().getById(this.auswahl); if (serviceManager.getProcessService().getWorkpiecesSize(tempProzess) > 0) { for (Property workpieceProperty : tempProzess.getWorkpieces()) { for (AdditionalField field : this.additionalFields) { if (field.getTitle().equals(workpieceProperty.getTitle())) { field.setValue(workpieceProperty.getValue()); } } } } if (serviceManager.getProcessService().getTemplatesSize(tempProzess) > 0) { for (Property templateProperty : tempProzess.getTemplates()) { for (AdditionalField field : this.additionalFields) { if (field.getTitle().equals(templateProperty.getTitle())) { field.setValue(templateProperty.getValue()); } } } } try { this.myRdf = serviceManager.getProcessService().readMetadataAsTemplateFile(tempProzess); } catch (ReadException | PreferencesException | IOException | RuntimeException e) { Helper.setErrorMessage("Fehler beim Einlesen der Template-Metadaten ", logger, e); } try { DocStructInterface colStruct = this.myRdf.getDigitalDocument().getLogicalDocStruct(); removeCollections(colStruct, this.prozessKopie); colStruct = colStruct.getAllChildren().get(0); removeCollections(colStruct, this.prozessKopie); } catch (PreferencesException e) { Helper.setErrorMessage("Fehler beim Anlegen des Vorgangs", logger, e); } catch (RuntimeException e) { } return ""; }
Source:
private StateManager() { this.initialzedSenderIdList = new ArrayList<>(); this.receiverNum = shuffleDescription.getReceiverIdList().size(); this.receiverStateMachineMap = new HashMap<>(receiverNum); for (final String receiverId : shuffleDescription.getReceiverIdList()) { receiverStateMachineMap.put(receiverId, PushShuffleReceiverImpl.createStateMachine()); } this.stateMachine = StateMachine.newBuilder() .addState("INIT", "Wait for all receivers are initialized") .addState("CAN_SEND", "Prepared senders can send data to receivers") .addState("RECEIVERS_COMPLETED", "All receivers were completed to receive data from senders in an iteration") .addState("FINISHED", "All senders and receivers were finished") .setInitialState("INIT") .addTransition("INIT", "CAN_SEND", "When RECEIVER_INITIALIZED messages arrived from all receivers." + " It sends SENDER_CAN_SEND messages to all initialized senders.") .addTransition("CAN_SEND", "RECEIVERS_COMPLETED", "When RECEIVER_COMPLETED messages arrived from all receivers." + " It broadcasts ALL_RECEIVERS_COMPLETED messages to all receivers.") .addTransition("RECEIVERS_COMPLETED", "CAN_SEND", "When RECEIVER_READY messages arrived from all receivers" + " It broadcasts ALL_RECEIVERS_READY messages to all senders.") .addTransition("CAN_SEND", "FINISHED", "When RECEIVER_FINISHED messages arrived from all receivers") .build(); }

Target:
private StateManager() { this.initializedSenderIdList = new ArrayList<>(); this.totalNumReceivers = shuffleDescription.getReceiverIdList().size(); this.receiverStateMachineMap = new HashMap<>(totalNumReceivers); for (final String receiverId : shuffleDescription.getReceiverIdList()) { receiverStateMachineMap.put(receiverId, PushShuffleReceiverState.createStateMachine()); } this.stateMachine = StateMachine.newBuilder() .addState(INIT, "Wait for all receivers are initialized") .addState(CAN_SEND, "Prepared senders can send data to receivers") .addState(RECEIVERS_COMPLETED, "All receivers were completed to receive data from senders in an iteration") .addState(FINISHED, "All senders and receivers were finished") .setInitialState(INIT) .addTransition(INIT, CAN_SEND, "When RECEIVER_INITIALIZED messages arrived from all receivers." + " It sends SENDER_CAN_SEND messages to all initialized senders.") .addTransition(CAN_SEND, RECEIVERS_COMPLETED, "When RECEIVER_COMPLETED messages arrived from all receivers." + " It broadcasts ALL_RECEIVERS_COMPLETED messages to all receivers.") .addTransition(RECEIVERS_COMPLETED, CAN_SEND, "When RECEIVER_READY messages arrived from all receivers" + " It broadcasts SENDER_CAN_SEND messages to all senders.") .addTransition(RECEIVERS_COMPLETED, FINISHED, "If shutdown() method was called before.") .build(); }
Source:
private Client createClientFrom(final Sid accountSid, final MultivaluedMap<String, String> data) { final Client.Builder builder = Client.builder(); final Sid sid = Sid.generate(Sid.Type.CLIENT); String password = data.getFirst("Password"); builder.setSid(sid); builder.setApiVersion(getApiVersion(data)); builder.setFriendlyName(data.getFirst("FriendlyName")); builder.setAccountSid(accountSid); builder.setLogin(data.getFirst("Login")); builder.setPassword(password); builder.setStatus(Client.ENABLED); builder.setVoiceUrl(getUrl("VoiceUrl", data)); builder.setVoiceMethod(getMethod("VoiceMethod", data)); builder.setVoiceFallbackUrl(getUrl("VoiceFallbackUrl", data)); builder.setVoiceFallbackMethod(getMethod("VoiceFallbackMethod", data)); builder.setVoiceApplicationSid(getSid("VoiceApplicationSid", data)); String rootUri = configuration.getString("root-uri"); rootUri = StringUtils.addSuffixIfNotPresent(rootUri, "/"); final StringBuilder buffer = new StringBuilder(); buffer.append(rootUri).append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Clients/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); }

Target:
private Client createClientFrom(final Sid accountSid, final MultivaluedMap<String, String> data) { final Client.Builder builder = Client.builder(); final Sid sid = Sid.generate(Sid.Type.CLIENT); String password = data.getFirst("Password"); builder.setSid(sid); builder.setAccountSid(accountSid); builder.setApiVersion(getApiVersion(data)); builder.setLogin(data.getFirst("Login")); builder.setPassword(password); builder.setFriendlyName(data.getFirst("FriendlyName")); builder.setStatus(Client.ENABLED); String rootUri = configuration.getString("root-uri"); rootUri = StringUtils.addSuffixIfNotPresent(rootUri, "/"); final StringBuilder buffer = new StringBuilder(); buffer.append(rootUri).append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Clients/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); }
Source:
private void setDiskImageActiveBySnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if (diskImage == null) { return; } if (snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW) { diskImage.setActive(true); } else if (snapshot.getType() == SnapshotType.REGULAR) { diskImage.setActive(false); } }

Target:
private void setDiskImageActiveBySnapshotType(Map<Guid, DiskImage> diskImageMap, Snapshot snapshot) { DiskImage diskImage = diskImageMap.get(snapshot.getId()); if (diskImage == null) { return; } diskImage.setActive(false); if (snapshot.getType() == SnapshotType.ACTIVE || snapshot.getType() == SnapshotType.PREVIEW) { diskImage.setActive(true); } }
Source:
public void startNode(String name) { if (nodeDepth == 1) { currentKey = name; } nodeDepth++; }

Target:
public void startNode(String name) { currentKey.push(name); if (currentKey.size() == 2) { fields.put(name, ""); } }
Source:
private void email() { if (message == null) { return; } workQueue.getDefaultQueue() .submit(requestScopePropagator.wrap(new Runnable() { @Override public void run() { PatchSetInfo patchSetInfo; try { ReviewDb reviewDb = schemaFactory.open(); try { patchSetInfo = patchSetInfoFactory.get(reviewDb, patchSetId); } finally { reviewDb.close(); } } catch (PatchSetInfoNotAvailableException e) { log.error( "Failed to obtain PatchSetInfo for patch set " + patchSetId, e); return; } catch (OrmException e) { log.error( "Cannot send comments by email for patch set " + patchSetId, e); return; } try { final CommentSender cm = commentSenderFactory.create(change); cm.setFrom(user.getAccountId()); cm.setPatchSet(patchSet, patchSetInfo); cm.setChangeMessage(message); cm.setPatchLineComments(drafts); cm.send(); } catch (EmailException e) { log.error( "Cannot send comments by email for patch set " + patchSetId, e); } } @Override public String toString() { return "send email for patch set comments"; } })); }

Target:
private void email() { if (message == null) { return; } workQueue.getDefaultQueue() .submit(requestScopePropagator.wrap(new Runnable() { @Override public void run() { PatchSetInfo patchSetInfo; try { ReviewDb reviewDb = schemaFactory.open(); try { patchSetInfo = patchSetInfoFactory.get(reviewDb, patchSetId); } finally { reviewDb.close(); } } catch (PatchSetInfoNotAvailableException e) { log.error("Cannot read PatchSetInfo of " + patchSetId, e); return; } catch (OrmException e) { log.error("Cannot email comments for " + patchSetId, e); return; } try { final CommentSender cm = commentSenderFactory.create(change); cm.setFrom(user.getAccountId()); cm.setPatchSet(patchSet, patchSetInfo); cm.setChangeMessage(message); cm.setPatchLineComments(drafts); cm.send(); } catch (EmailException e) { log.error("Cannot email comments for " + patchSetId, e); } } @Override public String toString() { return "send-email comments"; } })); }
Source:
@Test public void stepExecutionWithCredentials() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { assumeNotWindows(); IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate"); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" + " sh 'echo would be connecting to $DOCKER_HOST'\n" + " }\n" + "}", true)); WorkflowRun b = story.j.buildAndAssertSuccess(p); story.j.assertLogContains("would be connecting to tcp://host:1234", b); } }); }

Target:
@Test public void stepExecutionWithCredentials() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { assumeNotWindows(); IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate"); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" + " sh 'echo would be connecting to $DOCKER_HOST'\n" + " sh 'echo DOCKER_TLS_VERIFY=$DOCKER_TLS_VERIFY'\n" + " sh 'echo DOCKER_CERT_PATH=$DOCKER_CERT_PATH is not empty'\n" + " }\n" + "}", true)); WorkflowRun b = story.j.buildAndAssertSuccess(p); story.j.assertLogContains("would be connecting to tcp://host:1234", b); story.j.assertLogContains("DOCKER_TLS_VERIFY=1", b); story.j.assertLogNotContains("DOCKER_CERT_PATH= is not empty", b); } }); }
Source:
public String getValue(HttpContext httpContext) { List<String> headers = httpContext.getRequest().getRequestHeader(correlatorHeader); if (headers == null || headers.size() == 0) { LOGGER.error("Correlator Header not present", correlatorHeader); throw new WebApplicationException(Response.Status.BAD_REQUEST); } else if (headers.size() > 1) { LOGGER.error("Too many Correlator Headers {}:", correlatorHeader, headers); throw new WebApplicationException(Response.Status.BAD_REQUEST); } else { LOGGER.debug("correlator found {}:", headers.get(0)); MDC.put("client", headers.get(0)); return headers.get(0); } }

Target:
public String getValue(HttpContext httpContext) { List<String> headers = httpContext.getRequest().getRequestHeader(correlatorHeader); if ( (headers != null) && (headers.size() > 0) ) { if (headers.size() == 1) { LOGGER.debug("correlator found {}:", headers.get(0)); MDC.put("client", headers.get(0)); return headers.get(0); } else { LOGGER.error("Too many Correlator Headers {}:", correlatorHeader, headers); throw new WebApplicationException(Response.Status.BAD_REQUEST); } } else { LOGGER.debug("correlator not found"); return null; } }
Source:
public NeuralNetworkRule(ResourceBundle messages, Language language, ScoredConfusionSet confusionSet, Word2VecModel word2VecModel) { super(messages); super.setCategory(Categories.TYPOS.getCategory(messages)); this.subjects = confusionSet.getConfusionTokens(); this.descriptions = confusionSet.getTokenDescriptions(); this.minScore = confusionSet.getScore(); try { final InputStream W1Stream = streamFor(word2VecModel.getPath(), "W_fc1.txt"); final InputStream b1Stream = streamFor(word2VecModel.getPath(), "b_fc1.txt"); try { final InputStream W2Stream = streamFor(word2VecModel.getPath(), "W_fc2.txt"); final InputStream b2Stream = streamFor(word2VecModel.getPath(), "b_fc2.txt"); System.out.println("deep rule for" + confusionSet.toString()); classifier = new TwoLayerClassifier(word2VecModel.getEmbedding(), W1Stream, b1Stream, W2Stream, b2Stream); } catch (FileNotFoundException e) { classifier = new SingleLayerClassifier(word2VecModel.getEmbedding(), W1Stream, b1Stream); } } catch (FileNotFoundException e) { throw new IllegalStateException("weights for confusion set " + confusionSet.toString() + " are missing"); } this.id = createId(language); }

Target:
public NeuralNetworkRule(ResourceBundle messages, Language language, ScoredConfusionSet confusionSet, Word2VecModel word2VecModel) throws IOException { super(messages); super.setCategory(Categories.TYPOS.getCategory(messages)); this.subjects = confusionSet.getConfusionTokens(); this.descriptions = confusionSet.getTokenDescriptions(); this.minScore = confusionSet.getScore(); try { final InputStream W1Stream = streamFor(word2VecModel.getPath(), "W_fc1.txt"); final InputStream b1Stream = streamFor(word2VecModel.getPath(), "b_fc1.txt"); try { final InputStream W2Stream = streamFor(word2VecModel.getPath(), "W_fc2.txt"); final InputStream b2Stream = streamFor(word2VecModel.getPath(), "b_fc2.txt"); System.out.println("deep rule for" + confusionSet.toString()); classifier = new TwoLayerClassifier(word2VecModel.getEmbedding(), W1Stream, b1Stream, W2Stream, b2Stream); } catch (FileNotFoundException e) { classifier = new SingleLayerClassifier(word2VecModel.getEmbedding(), W1Stream, b1Stream); } } catch (FileNotFoundException e) { throw new IOException("weights for confusion set " + confusionSet.toString() + " are missing", e); } this.id = createId(language); }
Source:
public void testUnknownInstallSourceIsParsedCorrectly() { final InstallSource installSource = InstallSource.fromInstallerPackageName(null); assertTrue(installSource instanceof UnknownInstallSource); assertEquals("Unknown", installSource.toString()); }

Target:
public void testUnknownInstallSourceIsParsedCorrectly() { final InstallSource installSource = InstallSource.fromInstallerPackageName(null); assertTrue( "null package name is correctly identified as an unknown install source", installSource instanceof UnknownInstallSource); assertEquals( "Unknown install source has correct description", "Unknown", installSource.toString()); }
Source:
public static short computeDuplicateScore(final SAMRecord record, final ScoringStrategy scoringStrategy, final boolean assumeMateCigar) { Short storedScore = (Short) record.getTransientAttribute(Attr.DuplicateScore); if (storedScore == null) { short score=0; switch (scoringStrategy) { case SUM_OF_BASE_QUALITIES: score += (short) Math.min(getSumOfBaseQualities(record), Short.MAX_VALUE / 2); break; case TOTAL_MAPPED_REFERENCE_LENGTH: if (!record.getReadUnmappedFlag()) { score += record.getCigar().getReferenceLength(); } if (assumeMateCigar && record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { score += SAMUtils.getMateCigar(record).getReferenceLength(); } break; case RANDOM: score += (short) (hasher.hashUnencodedChars(record.getReadName()) & 0b11_1111_1111_1111); score -= Short.MIN_VALUE/4; } score = (short) Math.max(Short.MIN_VALUE, score); score += record.getReadFailsVendorQualityCheckFlag() ? (short) (Short.MIN_VALUE / 2) : 0; storedScore = score; record.setTransientAttribute(Attr.DuplicateScore, storedScore); } return storedScore; }

Target:
public static short computeDuplicateScore(final SAMRecord record, final ScoringStrategy scoringStrategy, final boolean assumeMateCigar) { Short storedScore = (Short) record.getTransientAttribute(Attr.DuplicateScore); if (storedScore == null) { short score=0; switch (scoringStrategy) { case SUM_OF_BASE_QUALITIES: score += (short) Math.min(getSumOfBaseQualities(record), Short.MAX_VALUE / 2); break; case TOTAL_MAPPED_REFERENCE_LENGTH: if (!record.getReadUnmappedFlag()) { score = (short) Math.min(record.getCigar().getReferenceLength(), Short.MAX_VALUE / 2); } if (assumeMateCigar && record.getReadPairedFlag() && !record.getMateUnmappedFlag()) { score += (short) Math.min(SAMUtils.getMateCigar(record).getReferenceLength(), Short.MAX_VALUE / 2); } break; case RANDOM: score += (short) (hasher.hashUnencodedChars(record.getReadName()) & 0b11_1111_1111_1111); score -= Short.MIN_VALUE / 4; } score += record.getReadFailsVendorQualityCheckFlag() ? (short) (Short.MIN_VALUE / 2) : 0; storedScore = score; record.setTransientAttribute(Attr.DuplicateScore, storedScore); } return storedScore; }
Source:
public void testSendNonExistingFile() throws Exception { server.requestHandler(req -> { req.response().sendFile("/not/existing/path", event -> { if (event.failed()) { req.response().end("failed"); } }); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals("failed", buff.toString()); testComplete(); }); }).end(); })); await(); }

Target:
public void testSendNonExistingFile() throws Exception { server.requestHandler(req -> { final Context ctx = vertx.getOrCreateContext(); req.response().sendFile("/not/existing/path", event -> { assertEquals(ctx, vertx.getOrCreateContext()); if (event.failed()) { req.response().end("failed"); } }); }); server.listen(onSuccess(s -> { client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> { resp.bodyHandler(buff -> { assertEquals("failed", buff.toString()); testComplete(); }); }).end(); })); await(); }
Source:
public void load() throws FailToParseHooksException, FieldNotFoundException { BotUI.getInstance().getJMenuBar().remove(2); Core.verbose(TranslationHelper.translate("PARSING_SERVER_JAR")); serverProvider.init(); serverProvider.parseJar(); Core.verbose(TranslationHelper.translate("DONE")); Core.verbose(TranslationHelper.translate("INJECTING_HOOKS")); serverProvider.injectHooks(); Core.verbose(TranslationHelper.translate("DONE")); Core.verbose(TranslationHelper.translate("FETCHING_GAME_APPLET")); if(Core.shouldDump()) { Core.verbose(TranslationHelper.translate("DUMPING_INJECTED_CLIENT")); classPath.dump(new File(Directories.getWorkspace(), "dump.jar")); Core.verbose(TranslationHelper.translate("DONE")); } Applet applet = serverProvider.fetchApplet(); if(applet != null) { setApplet(applet); } }

Target:
public void load() throws FailToParseHooksException, FieldNotFoundException { Core.verbose(TranslationHelper.translate("PARSING_SERVER_JAR")); serverProvider.init(); serverProvider.parseJar(); Core.verbose(TranslationHelper.translate("DONE")); Core.verbose(TranslationHelper.translate("INJECTING_HOOKS")); serverProvider.injectHooks(); Core.verbose(TranslationHelper.translate("DONE")); Core.verbose(TranslationHelper.translate("FETCHING_GAME_APPLET")); if (Core.shouldDump()) { Core.verbose(TranslationHelper.translate("DUMPING_INJECTED_CLIENT")); classPath.dump(new File(Directories.getWorkspace(), "dump.jar")); Core.verbose(TranslationHelper.translate("DONE")); } Applet applet = serverProvider.fetchApplet(); if (applet != null) { setApplet(applet); } }
Source:
private static String getPermissionsTableName(Class<?> owner, Class<?> property) { String ownerName = owner.getSimpleName(); String propertyName = property.getSimpleName(); if (propertyName.equals("ManagedUser")) { propertyName = "User"; } return ownerName.substring(0, 1).toLowerCase() + ownerName.substring(1) + "_" + propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); }

Target:
private static String getPermissionsTableName(Class<?> owner, Class<?> property) { String propertyName = property.getSimpleName(); if (propertyName.equals("ManagedUser")) { propertyName = "User"; } return Introspector.decapitalize(owner.getSimpleName()) + "_" + Introspector.decapitalize(propertyName); }
Source:
private void checkPlaylist() { if (isCheckingWhatsPlaying) return; isCheckingWhatsPlaying = true; connection.execute(new GetPlaylist(connection), new ApiCallback<ArrayList<GetPlaylist.GetPlaylistResult>>() { @Override public void onSuccess(ArrayList<GetPlaylist.GetPlaylistResult> result) { isCheckingWhatsPlaying = false; if (result.isEmpty()) return; for (PlaylistEventsObserver observer : playlistEventsObservers) { observer.playlistsAvailable(result); } } @Override public void onError(int errorCode, String description) { isCheckingWhatsPlaying = false; for (PlaylistEventsObserver observer : playlistEventsObservers) { observer.playlistOnError(errorCode, description); } } }, new Handler()); }

Target:
private void checkPlaylist() { if (isCheckingPlaylist) return; isCheckingPlaylist = true; connection.execute(new GetPlaylist(connection), new ApiCallback<ArrayList<GetPlaylist.GetPlaylistResult>>() { @Override public void onSuccess(ArrayList<GetPlaylist.GetPlaylistResult> result) { isCheckingPlaylist = false; if (result.isEmpty()) { callPlaylistsOnClear(prevGetPlaylistResults); return; } for (PlaylistEventsObserver observer : playlistEventsObservers) { observer.playlistsAvailable(result); } for (GetPlaylist.GetPlaylistResult getPlaylistResult : result) { for (int i = 0; i < prevGetPlaylistResults.size(); i++) { if (getPlaylistResult.id == prevGetPlaylistResults.get(i).id) { prevGetPlaylistResults.remove(i); break; } } } callPlaylistsOnClear(prevGetPlaylistResults); prevGetPlaylistResults = result; } @Override public void onError(int errorCode, String description) { isCheckingPlaylist = false; for (PlaylistEventsObserver observer : playlistEventsObservers) { observer.playlistOnError(errorCode, description); } } }, new Handler()); }
Source:
private TopologyResources getResourcesForTopology(String topoId, StormBase base) throws NotAliveException, AuthorizationException, InvalidTopologyException, IOException { TopologyResources ret = idToResources.get().get(topoId); if (ret == null) { try { IStormClusterState state = stormClusterState; TopologyDetails details = readTopologyDetails(topoId, base); Assignment assignment = getAssignmentInfo(state, topoId); ret = new TopologyResources(details, assignment); } catch(KeyNotFoundException e) { LOG.error("Failed to get topology details", e); ret = new TopologyResources(); } } return ret; }

Target:
private TopologyResources getResourcesForTopology(String topoId, StormBase base) throws NotAliveException, AuthorizationException, InvalidTopologyException, IOException { TopologyResources ret = idToResources.get().get(topoId); if (ret == null) { try { TopologyDetails details = readTopologyDetails(topoId, base); Assignment assignment = getAssignmentInfo(topoId); ret = new TopologyResources(details, assignment); } catch(KeyNotFoundException e) { LOG.error("Failed to get topology details", e); ret = new TopologyResources(); } } return ret; }
Source:
public String getUsage(ICommandSender commandSender) { return new TextComponentTranslation("commands.bloodmagic.bind.usage").getFormattedText() + "\n" + help; }

Target:
public String getUsage(ICommandSender commandSender) { return "commands.bloodmagic.bind.usage"; }
Source:
protected void onPostExecute(Void aVoid) { LinearLayout multireddits_area = headerMain.findViewById(R.id.multireddits_area); for (MultiReddit multiReddit : UserSubscriptions.multireddits) { final View t = getLayoutInflater().inflate(R.layout.multireddit_textview_white, multireddits_area, false); ((TextView) t.findViewById(R.id.name)).setText(multiReddit.getDisplayName()); t.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, MultiredditOverview.class); intent.putExtra(MultiredditOverview.EXTRA_MULTI, multiReddit.getFullName()); startActivity(intent); }); multireddits_area.addView(t); } }

Target:
protected void onPostExecute(Void aVoid) { LinearLayout multiredditsArea = headerMain.findViewById(R.id.expand_multireddits); for (MultiReddit multiReddit : UserSubscriptions.multireddits) { final View t = getLayoutInflater().inflate(R.layout.multireddit_textview_white, multiredditsArea, false); ((TextView) t.findViewById(R.id.name)).setText(multiReddit.getDisplayName()); t.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, MultiredditOverview.class); intent.putExtra(MultiredditOverview.EXTRA_MULTI, multiReddit.getFullName()); startActivity(intent); }); multiredditsArea.addView(t); } }
Source:
protected void beforeSave() { if (Strings.isEmpty(blobKey)) { blobKey = keyGen.generateId(); } updateFilenameFields(); if (isNew() || isChanged(FILENAME, NORMALIZED_FILENAME, FILE_EXTENSION)) { changed = true; } if (deleted) { changed = false; } }

Target:
protected void beforeSave() { if (Strings.isEmpty(blobKey)) { blobKey = keyGen.generateId(); } updateFilenameFields(); if (isNew() || isChanged(FILENAME, NORMALIZED_FILENAME, FILE_EXTENSION)) { createdOrRenamed = true; } if (deleted) { createdOrRenamed = false; } }
Source:
public AnsibleCommandBuilder hosts(VdsStatic... hosts) { this.hostnames = Arrays.stream(hosts) .map(h -> String.format("[%1$s]:%2$s", h.getHostName(), h.getSshPort())) .collect(Collectors.toList()); return this; }

Target:
public AnsibleCommandBuilder hosts(VdsStatic... hosts) { this.hostnames = Arrays.stream(hosts) .map(h -> formatHostPort(h.getHostName(), h.getSshPort())) .collect(Collectors.toList()); return this; }
Source:
public static void openFolderAndSelectFile(Path fileLink) throws IOException { if (Objects.isNull(fileLink)) { return; } boolean usingDefault = Globals.prefs.getBoolean(JabRefPreferences.USE_DEFAULT_FILE_BROWSER_APPLICATION); if(usingDefault) { NATIVE_DESKTOP.openFolderAndSelectFile(fileLink); }else{ String absolutePath = fileLink.toAbsolutePath().getParent().toString(); String command = Globals.prefs.get(JabRefPreferences.FILE_BROWSER_COMMAND); if (!command.isEmpty()) { command = command.replaceAll("\\s+", " "); command = command.replace("%DIR", absolutePath); String[] subcommands = command.split(" "); JabRefGUI.getMainFrame().output(Localization.lang("Executing command \"%0\"...", command)); LOGGER.info("Executing command \"" + command + "\"..."); try { new ProcessBuilder(subcommands).start(); } catch (IOException exception) { LOGGER.error("Open File Browser", exception); JOptionPane.showMessageDialog(null, Localization.lang("Error occured while executing the command \"%0\".", command), Localization.lang("Open File Browser") + " - " + Localization.lang("Error"), JOptionPane.ERROR_MESSAGE); } } } }

Target:
public static void openFolderAndSelectFile(Path fileLink) throws IOException { if (fileLink == null) { return; } boolean usingDefault = Globals.prefs.getBoolean(JabRefPreferences.USE_DEFAULT_FILE_BROWSER_APPLICATION); if (usingDefault) { NATIVE_DESKTOP.openFolderAndSelectFile(fileLink); } else { String absolutePath = fileLink.toAbsolutePath().getParent().toString(); String command = Globals.prefs.get(JabRefPreferences.FILE_BROWSER_COMMAND); if (!command.isEmpty()) { command = command.replaceAll("\\s+", " "); command = command.replace("%DIR", absolutePath); String[] subcommands = command.split(" "); LOGGER.info("Executing command \"" + command + "\"..."); try { new ProcessBuilder(subcommands).start(); } catch (IOException exception) { LOGGER.error("Open File Browser", exception); JabRefGUI.getMainFrame().getDialogService().notify(Localization.lang("Error occured while executing the command \"%0\".", command)); } } } }
Source:
private void validate(short version) { if (version == 0) { final boolean unsupported = acls().stream() .anyMatch(acl -> acl.patternType() != PatternType.LITERAL.code()); if (unsupported) { throw new UnsupportedVersionException("Version 0 only supports literal resource pattern types"); } } final boolean unknown = acls().stream() .map(DescribeAclsResponse::aclBindings) .anyMatch(bindings -> bindings.stream().anyMatch(AclBinding::isUnknown)); if (unknown) { throw new IllegalArgumentException("Contain UNKNOWN elements"); } }

Target:
private void validate(short version) { if (version == 0) { final boolean unsupported = acls().stream() .anyMatch(acl -> acl.patternType() != PatternType.LITERAL.code()); if (unsupported) { throw new UnsupportedVersionException("Version 0 only supports literal resource pattern types"); } } for (DescribeAclsResource resource : acls()) { if (resource.patternType() == PatternType.UNKNOWN.code() || resource.type() == ResourceType.UNKNOWN.code()) throw new IllegalArgumentException("Contain UNKNOWN elements"); for (AclDescription acl : resource.acls()) { if (acl.operation() == AclOperation.UNKNOWN.code() || acl.permissionType() == AclPermissionType.UNKNOWN.code()) { throw new IllegalArgumentException("Contain UNKNOWN elements"); } } } }
Source:
public static void update(IProject project, Optional<List<OmniEclipseBuildCommand>> buildCommands, PersistentModelBuilder persistentModel, IProgressMonitor monitor) throws CoreException { IProjectDescription description = project.getDescription(); Set<ICommand> current = Sets.newLinkedHashSet(Arrays.asList(description.getBuildSpec())); Set<ICommand> model = toCommands(buildCommands, description); PersistentModel previousModel = persistentModel.getPrevious(); Set<ICommand> managed = previousModel.isPresent() ? Sets.newLinkedHashSet(previousModel.getManagedBuilders()) : Sets.<ICommand>newLinkedHashSet(); Result<ICommand> result = GradleBuilderAndNatureMergingStrategy.calculate(current, model, managed); description.setBuildSpec(result.getNextElements().toArray(new ICommand[0])); project.setDescription(description, monitor); persistentModel.managedBuilders(result.getNextManaged()); }

Target:
public static void update(IProject project, Optional<List<OmniEclipseBuildCommand>> buildCommands, PersistentModelBuilder persistentModel, IProgressMonitor monitor) throws CoreException { IProjectDescription description = project.getDescription(); Set<ICommand> current = ImmutableSet.copyOf(description.getBuildSpec()); Set<ICommand> model = toCommands(buildCommands, description); PersistentModel previousModel = persistentModel.getPrevious(); Set<ICommand> managed = previousModel.isPresent() ? Sets.newLinkedHashSet(previousModel.getManagedBuilders()) : Sets.<ICommand>newLinkedHashSet(); Result<ICommand> result = ManagedModelMergingStrategy.calculate(current, model, managed); description.setBuildSpec(result.getNextElements().toArray(new ICommand[0])); project.setDescription(description, monitor); persistentModel.managedBuilders(result.getNextManaged()); }
Source:
public static Change translateAttributesToOtherUnits( final Unit unitGivingAttributes, final Collection<Unit> unitsThatWillGetAttributes, final Territory territory) { final CompositeChange changes = unitsThatWillGetAttributes.stream() .findFirst() .map( receivingUnit -> { final CompositeChange unitChange = new CompositeChange(); final List<Unit> unloaded = unitGivingAttributes.getUnloaded(); if (!unloaded.isEmpty()) { unitChange.add( ChangeFactory.unitPropertyChange(receivingUnit, unloaded, Unit.UNLOADED)); } final List<Unit> transporting = unitGivingAttributes.getTransporting(); return transporting.stream() .map( transported -> new CompositeChange( ChangeFactory.unitPropertyChange( transported, receivingUnit, Unit.TRANSPORTED_BY))) .reduce(unitChange, CompositeChange::new); }) .orElse(new CompositeChange()); return unitsThatWillGetAttributes.stream() .map( receivingUnit -> { final CompositeChange unitChange = new CompositeChange(); final int transferHits = Math.min( unitGivingAttributes.getHits(), receivingUnit.getUnitAttachment().getHitPoints() - 1); if (transferHits > 0) { unitChange.add( ChangeFactory.unitsHit( IntegerMap.of(Map.of(receivingUnit, transferHits)), List.of(territory))); } final int transferDamage = Math.min( unitGivingAttributes.getUnitDamage(), receivingUnit.getHowMuchDamageCanThisUnitTakeTotal(territory)); if (transferDamage > 0) { unitChange.add( ChangeFactory.bombingUnitDamage( IntegerMap.of(Map.of(receivingUnit, transferDamage)), List.of(territory))); } return unitChange; }) .reduce(changes, CompositeChange::new); }

Target:
public static Change translateAttributesToOtherUnits( final Unit unitGivingAttributes, final Collection<Unit> unitsThatWillGetAttributes, final Territory territory) { final CompositeChange changes = unitsThatWillGetAttributes.stream() .findFirst() .map( receivingUnit -> translateDependentUnitsToOtherUnit(unitGivingAttributes, receivingUnit)) .orElse(new CompositeChange()); return unitsThatWillGetAttributes.stream() .map( receivingUnit -> translateHitPointsAndDamageToOtherUnit( unitGivingAttributes, territory, receivingUnit)) .reduce(changes, CompositeChange::new); }
Source:
public void handleData(final ITmfEvent event) { super.handleData(event); if (isCancelled()) { return; } try { if (fFilter == null || fFilter.matches(event)) { if (fTable != null) { String[] entries = fTable.getCurrentItemStrings(event); boolean needTab = false; for (String entry : entries) { if (needTab) { fWriter.write('\t'); } printValue(entry); needTab = true; } } else { fWriter.write(event.getTimestamp().toString()); fWriter.write('\t'); fWriter.write(event.getSource()); fWriter.write('\t'); fWriter.write(event.getType().getName()); fWriter.write('\t'); fWriter.write(event.getReference()); fWriter.write('\t'); ITmfEventField content = event.getContent(); printValue(content.getValue()); } fWriter.write('\n'); } } catch (IOException ex) { fIOException = ex; fail(); } }

Target:
public void handleData(final ITmfEvent event) { super.handleData(event); if (isCancelled()) { return; } try { if (fFilter == null || fFilter.matches(event)) { if (fTable != null) { String[] entries = fTable.getItemStrings(event); boolean needTab = false; for (String entry : entries) { if (needTab) { fWriter.write('\t'); } printValue(entry); needTab = true; } } else { fWriter.write(event.getTimestamp().toString()); fWriter.write('\t'); fWriter.write(event.getSource()); fWriter.write('\t'); fWriter.write(event.getType().getName()); fWriter.write('\t'); fWriter.write(event.getReference()); fWriter.write('\t'); ITmfEventField content = event.getContent(); printValue(content.getValue()); } fWriter.write('\n'); } } catch (IOException ex) { fIOException = ex; fail(); } }
Source:
protected Quip doTargetableComplimentRequest(VoiceInput voiceInput, ServiceOutput serviceOutput) throws DerpwizardException { QuipMetadata outputMetadata = (QuipMetadata) serviceOutput.getMetadata(); Map<String,String> messageMap = voiceInput.getMessageAsMap(); if(!messageMap.containsKey("target") || StringUtils.isEmpty(messageMap.get("target"))){ return doComplimentRequest(voiceInput, serviceOutput); } String target = messageMap.get("target"); if(target.toLowerCase().equals("me")){ return doComplimentRequest(voiceInput, serviceOutput); } target = target.substring(0,1).toUpperCase()+target.substring(1); Queue<String> complimentsUsed = outputMetadata.getComplimentsUsed(); Quip quip = getRandomTargetableQuip(QuipType.COMPLIMENT, complimentsUsed, target); String plaintext = quip.getText(); String ssml = quip.getSsml(); if(quip.isTargetable()){ plaintext = quip.getTargetableText(); ssml = quip.getTargetableSsml(); } serviceOutput.getVisualOutput().setTitle("CompliBot compliment"); serviceOutput.getVisualOutput().setText(plaintext); serviceOutput.getVoiceOutput().setPlaintext(plaintext); serviceOutput.getVoiceOutput().setSsmltext(ssml); if(handholdMode){ serviceOutput.getDelayedVoiceOutput().setPlaintext(COMPLIBOT_QUIP_FOLLOW_UP); serviceOutput.getDelayedVoiceOutput().setSsmltext("<p> " + COMPLIBOT_QUIP_FOLLOW_UP + " </p>"); } return quip; }

Target:
protected Quip doTargetableComplimentRequest(VoiceInput voiceInput, ServiceOutput serviceOutput) throws DerpwizardException { QuipMetadata outputMetadata = (QuipMetadata) serviceOutput.getMetadata(); Map<String,String> messageMap = voiceInput.getMessageAsMap(); if(!messageMap.containsKey("target") || StringUtils.isEmpty(messageMap.get("target"))){ return doComplimentRequest(voiceInput, serviceOutput); } String target = messageMap.get("target"); if(target.toLowerCase().equals("me")){ return doComplimentRequest(voiceInput, serviceOutput); } target = target.substring(0,1).toUpperCase()+target.substring(1); Queue<String> complimentsUsed = outputMetadata.getComplimentsUsed(); Quip quip = getRandomTargetableQuip(QuipType.COMPLIMENT, complimentsUsed, target); String plaintext = quip.getText(); String ssml = quip.getSsml(); if(quip.isTargetable()){ plaintext = quip.getTargetableText(); ssml = quip.getTargetableSsml(); } serviceOutput.getVisualOutput().setTitle("CompliBot compliment"); serviceOutput.getVisualOutput().setText(plaintext); serviceOutput.getVoiceOutput().setPlaintext(plaintext); serviceOutput.getVoiceOutput().setSsmltext(ssml); if(handholdMode){ serviceOutput.getDelayedVoiceOutput().setPlaintext(COMPLIBOT_QUIP_FOLLOW_UP); serviceOutput.getDelayedVoiceOutput().setSsmltext(COMPLIBOT_QUIP_FOLLOW_UP); } return quip; }
Source:
protected Object handleRequestMessage(Message<?> requestMessage) { MessageHeaders requestMessageHeaders = requestMessage.getHeaders(); PollableChannel gatherResultChannel = new QueueChannel(); Message<?> scatterMessage = getMessageBuilderFactory() .fromMessage(requestMessage) .setHeader(GATHER_RESULT_CHANNEL, gatherResultChannel) .setHeader(ORIGINAL_REPLY_CHANNEL, requestMessageHeaders.getReplyChannel()) .setHeader(ORIGINAL_ERROR_CHANNEL, requestMessageHeaders.getErrorChannel()) .setReplyChannel(this.gatherChannel) .setErrorChannelName(this.errorChannelName) .build(); this.messagingTemplate.send(this.scatterChannel, scatterMessage); Message<?> gatherResult = gatherResultChannel.receive(this.gatherTimeout); if (gatherResult != null && (requestMessageHeaders.containsKey(ORIGINAL_REPLY_CHANNEL) || requestMessageHeaders.containsKey(ORIGINAL_ERROR_CHANNEL) || requestMessageHeaders.containsKey(GATHER_RESULT_CHANNEL))) { return getMessageBuilderFactory() .fromMessage(gatherResult) .removeHeader(GATHER_RESULT_CHANNEL) .setHeader(GATHER_RESULT_CHANNEL, requestMessageHeaders.get(GATHER_RESULT_CHANNEL)) .setHeader(ORIGINAL_REPLY_CHANNEL, requestMessageHeaders.get(ORIGINAL_REPLY_CHANNEL)) .setHeader(ORIGINAL_ERROR_CHANNEL, requestMessageHeaders.get(ORIGINAL_ERROR_CHANNEL)) .setHeader(MessageHeaders.REPLY_CHANNEL, requestMessage.getHeaders().getReplyChannel()) .build(); } return gatherResult; }

Target:
protected Object handleRequestMessage(Message<?> requestMessage) { MessageHeaders requestMessageHeaders = requestMessage.getHeaders(); PollableChannel gatherResultChannel = new QueueChannel(); Message<?> scatterMessage = getMessageBuilderFactory() .fromMessage(requestMessage) .setHeader(GATHER_RESULT_CHANNEL, gatherResultChannel) .setHeader(ORIGINAL_ERROR_CHANNEL, requestMessageHeaders.getErrorChannel()) .setReplyChannel(this.gatherChannel) .setErrorChannelName(this.errorChannelName) .build(); this.messagingTemplate.send(this.scatterChannel, scatterMessage); Message<?> gatherResult = gatherResultChannel.receive(this.gatherTimeout); if (gatherResult != null) { return getMessageBuilderFactory() .fromMessage(gatherResult) .setHeader(GATHER_RESULT_CHANNEL, requestMessageHeaders.get(GATHER_RESULT_CHANNEL)) .setHeader(ORIGINAL_ERROR_CHANNEL, requestMessageHeaders.get(ORIGINAL_ERROR_CHANNEL)) .setHeader(MessageHeaders.REPLY_CHANNEL, requestMessage.getHeaders().getReplyChannel()) .setHeader(MessageHeaders.ERROR_CHANNEL, requestMessage.getHeaders().getErrorChannel()) .build(); } return gatherResult; }
Source:
public TemplateBundle(Bundle bundle, List<ServiceReference<Object>> services) { this.bundle = bundle; this.initServices = services; init(); }

Target:
public TemplateBundle(Bundle bundle, List<ServiceReference<Object>> services) { if(bundle == null){ throw new NullArgumentException("bundle"); } this.bundle = bundle; init(services); }
Source:
public void setUp() { manager = new TaskRepositoryManager(); manager.addRepository(actualFixture.repository()); connector = new BugzillaRestConnector(); }

Target:
public void setUp() { connector = new BugzillaRestConnector(); }
Source:
public CompositeDescriptorProvider(List<DescriptorProvider> delegates) { this.delegates = delegates; serverChecker = new ServerChecker(); serverCheckerThread = new Thread(serverChecker); serverCheckerThread.start(); }

Target:
public CompositeDescriptorProvider(List<DescriptorProvider> delegates) { this.delegates = delegates; serverChecker = new ServerChecker(); serverCheckerThread = new Thread(serverChecker); serverCheckerThread.setDaemon(true); serverCheckerThread.setName("ServerChecker"); serverCheckerThread.start(); }
Source:
private static void addSecondaryLocations(PreciseIssue issue, Expression expression) { Expression unwrappedExpression = Expressions.removeParentheses(expression); if (unwrappedExpression.is(Tree.Kind.CONDITIONAL_EXPR)) { ConditionalExpression conditionalExpression = (ConditionalExpression) unwrappedExpression; ignoreList.add(conditionalExpression); addSecondaryLocations(issue, (conditionalExpression).trueExpression()); addSecondaryLocations(issue, (conditionalExpression).falseExpression()); } else { issue.secondary(unwrappedExpression, null); } }

Target:
private static void addSecondaryLocations(PreciseIssue issue, Expression expression) { Expression unwrappedExpression = Expressions.removeParentheses(expression); if (unwrappedExpression.is(Tree.Kind.CONDITIONAL_EXPR)) { ConditionalExpression conditionalExpression = (ConditionalExpression) unwrappedExpression; ignoreList.add(conditionalExpression); addSecondaryLocations(issue, conditionalExpression.trueExpression()); addSecondaryLocations(issue, conditionalExpression.falseExpression()); } else { issue.secondary(unwrappedExpression, null); } }
Source:
public Object getResult() throws Exception { try { final Unmarshaller unmarshaller = MethodInvocationResponseHandler.this.prepareForUnMarshalling(MethodInvocationResponseHandler.this.marshallerFactory, this.input); final Object result = unmarshaller.readObject(); final Map<String, Object> attachments = MethodInvocationResponseHandler.this.readAttachments(unmarshaller); for(Map.Entry<String,Object> entry : attachments.entrySet()) this.clientInvocationContext.getContextData().put(entry.getKey(), entry.getValue()); unmarshaller.finish(); if (this.clientInvocationContext != null && attachments != null && attachments.containsKey(Affinity.WEAK_AFFINITY_CONTEXT_KEY)) { final Affinity weakAffinity = (Affinity) attachments.get(Affinity.WEAK_AFFINITY_CONTEXT_KEY); this.clientInvocationContext.putAttachment(AttachmentKeys.WEAK_AFFINITY, weakAffinity); } return result; } finally { this.input.close(); } }

Target:
public Object getResult() throws Exception { try { final Unmarshaller unmarshaller = MethodInvocationResponseHandler.this.prepareForUnMarshalling(MethodInvocationResponseHandler.this.marshallerFactory, this.input); final Object result = unmarshaller.readObject(); final Map<String, Object> attachments = MethodInvocationResponseHandler.this.readAttachments(unmarshaller); if(attachments != null) { for(Map.Entry<String,Object> entry : attachments.entrySet()) this.clientInvocationContext.getContextData().put(entry.getKey(), entry.getValue()); } unmarshaller.finish(); if (this.clientInvocationContext != null && attachments != null && attachments.containsKey(Affinity.WEAK_AFFINITY_CONTEXT_KEY)) { final Affinity weakAffinity = (Affinity) attachments.get(Affinity.WEAK_AFFINITY_CONTEXT_KEY); this.clientInvocationContext.putAttachment(AttachmentKeys.WEAK_AFFINITY, weakAffinity); } return result; } finally { this.input.close(); } }
Source:
public void onError(Throwable t) { Status s = Status.fromThrowable(t); String statusDesc = s == null ? "" : s.getDescription(); if (t.getClass() == StatusException.class || t.getClass() == StatusRuntimeException.class) { Code code = t.getClass() == StatusException.class ? ((StatusException) t).getStatus().getCode() : ((StatusRuntimeException) t).getStatus().getCode(); if (code == Code.DEADLINE_EXCEEDED || code == Code.RESOURCE_EXHAUSTED || code == Code.INTERNAL || code == Code.UNAVAILABLE) { transientError = t; } } if (transientError == null) { nonTransientError = new Throwable( String.format( "Caught exception for '%s', while uploading to uploadId %s at writeOffset %d." + " Status: %s", resourceId, uploadId, writeOffset, statusDesc), t); } done.countDown(); }

Target:
public void onError(Throwable t) { Status s = Status.fromThrowable(t); String statusDesc = s == null ? "" : s.getDescription(); if (t.getClass() == StatusException.class || t.getClass() == StatusRuntimeException.class) { Code code = t.getClass() == StatusException.class ? ((StatusException) t).getStatus().getCode() : ((StatusRuntimeException) t).getStatus().getCode(); if (TRANSIENT_ERRORS.contains(code)) { transientError = t; objectFinalized = false; } } if (transientError == null) { nonTransientError = new IOException( String.format( "Caught exception for '%s', while uploading to uploadId %s at writeOffset %d." + " Status: %s", resourceId, uploadId, writeOffset, statusDesc), t); objectFinalized = true; } done.countDown(); }
Source:
public void testExistingIncorrectChildrenInConfigFile() throws Exception { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final LocalizedMessage errorCounterMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, ERROR_COUNTER_MESSAGE, new String[] {String.valueOf(1)}, null, getClass(), null); final String output = String.format(Locale.ROOT, errorCounterMessage.getMessage() + "%n"); assertEquals(output, systemOut.getLog()); final String errorOutput = "com.puppycrawl.tools.checkstyle.api." + "CheckstyleException: cannot initialize module RegexpSingleline" + " - RegexpSingleline is not allowed as a child in RegexpSingleline"; assertTrue(systemErr.getLog().startsWith(errorOutput)); }); Main.main("-c", getPath("config-incorrectChildren.xml"), getPath("InputMain.java")); }

Target:
public void testExistingIncorrectChildrenInConfigFile() throws Exception { exit.expectSystemExitWithStatus(-2); exit.checkAssertionAfterwards(() -> { final String output = errorCounterOneMessage.getMessage() + EOL; assertEquals(output, systemOut.getLog()); final String errorOutput = "com.puppycrawl.tools.checkstyle.api." + "CheckstyleException: cannot initialize module RegexpSingleline" + " - RegexpSingleline is not allowed as a child in RegexpSingleline"; assertTrue(systemErr.getLog().startsWith(errorOutput)); }); Main.main("-c", getPath("config-incorrectChildren.xml"), getPath("InputMain.java")); }