auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testShrinkStatus() throws IOException { Configuration conf = getConfiguration(); MockFileSystem mockFs = (MockFileSystem) new Path("test:/ Path dir1 = new Path("test:/a1"); RemoteIterator<LocatedFileStatus> statuses = mockFs.listLocatedStatus(dir1); while (statuses.hasNext()) { LocatedFileStatus orig = statuses.next(); LocatedFileStatus shrink = (LocatedFileStatus)FileInputFormat.shrinkStatus(orig); Assert.assertTrue(orig.equals(shrink)); if (shrink.getBlockLocations() != null) { BlockLocation location = shrink.getBlockLocations()[0]; BlockLocation actual = orig.getBlockLocations()[0]; Assert.assertArrayEquals(actual.getHosts(), location.getHosts()); Assert.assertArrayEquals( actual.getCachedHosts(), location.getCachedHosts() ); Assert.assertArrayEquals( actual.getStorageIds(), location.getStorageIds() ); Assert.assertArrayEquals( actual.getStorageTypes(), location.getStorageTypes() ); Assert.assertArrayEquals( actual.getTopologyPaths(), location.getTopologyPaths() ); Assert.assertArrayEquals(actual.getNames(), location.getNames()); Assert.assertEquals(actual.getLength(), location.getLength()); Assert.assertEquals(actual.getOffset(), location.getOffset()); Assert.assertEquals(actual.isCorrupt(), location.isCorrupt()); } else { Assert.assertTrue(orig.getBlockLocations() == null); } } }

Target:
public void testShrinkStatus() throws IOException { Configuration conf = getConfiguration(); MockFileSystem mockFs = (MockFileSystem) new Path("test:/ Path dir1 = new Path("test:/a1"); RemoteIterator<LocatedFileStatus> statuses = mockFs.listLocatedStatus(dir1); boolean verified = false; while (statuses.hasNext()) { LocatedFileStatus orig = statuses.next(); LocatedFileStatus shrink = (LocatedFileStatus)FileInputFormat.shrinkStatus(orig); Assert.assertTrue(orig.equals(shrink)); if (shrink.getBlockLocations() != null) { Assert.assertEquals(orig.getBlockLocations().length, shrink.getBlockLocations().length); for (int i = 0; i < shrink.getBlockLocations().length; i++) { verified = true; BlockLocation location = shrink.getBlockLocations()[i]; BlockLocation actual = orig.getBlockLocations()[i]; Assert.assertNotNull(((HdfsBlockLocation)actual).getLocatedBlock()); Assert.assertEquals(BlockLocation.class.getName(), location.getClass().getName()); Assert.assertArrayEquals(actual.getHosts(), location.getHosts()); Assert.assertArrayEquals(actual.getCachedHosts(), location.getCachedHosts()); Assert.assertArrayEquals(actual.getStorageIds(), location.getStorageIds()); Assert.assertArrayEquals(actual.getStorageTypes(), location.getStorageTypes()); Assert.assertArrayEquals(actual.getTopologyPaths(), location.getTopologyPaths()); Assert.assertArrayEquals(actual.getNames(), location.getNames()); Assert.assertEquals(actual.getLength(), location.getLength()); Assert.assertEquals(actual.getOffset(), location.getOffset()); Assert.assertEquals(actual.isCorrupt(), location.isCorrupt()); } } else { Assert.assertTrue(orig.getBlockLocations() == null); } } Assert.assertTrue(verified); }
Source:
public void testLoadTarget() throws CoreException { IApiBaseline baseline = ApiModelFactory.newApiBaselineFromTarget(getClass().getName(), definition, null); assertTrue("This baseline should be appear to be from a target definition", ApiModelFactory.isDerivedFromTarget(baseline)); assertTrue("This baseline should be from this particular target definition", ApiModelFactory.isDerivedFromTarget(baseline, definition)); assertTrue(baseline.getApiComponents().length >= 3); }

Target:
public void testLoadTarget() throws CoreException { IApiBaseline baseline = ApiModelFactory.newApiBaselineFromTarget(getClass().getName(), definition, null); assertTrue("This baseline should appear to be from a target definition", ApiModelFactory.isDerivedFromTarget(baseline)); assertTrue("This baseline should be from this particular target definition", ApiModelFactory.isDerivedFromTarget(baseline, definition)); assertTrue(baseline.getApiComponents().length >= 3); }
Source:
private <T extends FlagAffectedCommand & TopologyAffectedCommand> LocalizedCacheTopology checkTopology(T command) { LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology(); if (cacheTopology == null) { return null; } if (!command.hasAnyFlag(FlagBitSets.SKIP_OWNERSHIP_CHECK) && command.getTopologyId() >= 0 && command.getTopologyId() != cacheTopology.getTopologyId()) { throw new OutdatedTopologyException("Command topology: " + command.getTopologyId() + ", cache topology: " + cacheTopology.getTopologyId()); } else if (trace) { log.tracef("%s has topology %d (current is %d)", command, command.getTopologyId(), cacheTopology.getTopologyId()); } return cacheTopology; }

Target:
private <T extends FlagAffectedCommand & TopologyAffectedCommand> LocalizedCacheTopology checkTopology(T command) { LocalizedCacheTopology cacheTopology = distributionManager.getCacheTopology(); if (!command.hasAnyFlag(FlagBitSets.SKIP_OWNERSHIP_CHECK) && command.getTopologyId() >= 0 && command.getTopologyId() != cacheTopology.getTopologyId()) { throw new OutdatedTopologyException(command.getTopologyId()); } else if (trace) { log.tracef("%s has topology %d (current is %d)", command, command.getTopologyId(), cacheTopology.getTopologyId()); } return cacheTopology; }
Source:
private void init() { try (InputStream serviceAccount = new ClassPathResource( yonaProperties.getSecurity().getFirebaseAdminServiceAccountKeyFile()).getInputStream()) { FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(serviceAccount)) .setDatabaseUrl(yonaProperties.getFirebaseDatabaseUrl()).build(); FirebaseApp.initializeApp(options); } catch (IOException e) { logger.error("Error initializing Firebase client", e); } }

Target:
private void init() { if (!yonaProperties.getFirebase().isEnabled()) { logger.info("Firebase is disabled"); return; } try (InputStream serviceAccount = new ClassPathResource(yonaProperties.getFirebase().getAdminServiceAccountKeyFile()) .getInputStream()) { FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(GoogleCredentials.fromStream(serviceAccount)) .setDatabaseUrl(yonaProperties.getFirebase().getDatabaseUrl()).build(); FirebaseApp.initializeApp(options); } catch (IOException e) { throw YonaException.unexpected(e); } }
Source:
private void monitor(ClientEndpoint clientEndpoint) { if (clientEndpoint.isOwnerConnection() && ClientType.CPP.equals(clientEndpoint.getClientType())) { return; } Connection connection = clientEndpoint.getConnection(); long lastTimePacketReceived = connection.lastReadTimeMillis(); long timeoutInMillis = SECONDS.toMillis(heartbeatTimeoutSeconds); long currentTimeMillis = Clock.currentTimeMillis(); if (lastTimePacketReceived + timeoutInMillis < currentTimeMillis) { String message = "Client heartbeat is timed out, closing connection to " + connection + ". Now: " + timeToString(currentTimeMillis) + ". LastTimePacketReceived: " + timeToString(lastTimePacketReceived); connection.close(message, null); } }

Target:
private void monitor(ClientEndpoint clientEndpoint) { if (clientEndpoint.isOwnerConnection() && ClientType.CPP.equals(clientEndpoint.getClientType()) && clientEndpoint.getClientVersion() < BuildInfo.calculateVersion("3.10")) { return; } Connection connection = clientEndpoint.getConnection(); long lastTimePacketReceived = connection.lastReadTimeMillis(); long timeoutInMillis = SECONDS.toMillis(heartbeatTimeoutSeconds); long currentTimeMillis = Clock.currentTimeMillis(); if (lastTimePacketReceived + timeoutInMillis < currentTimeMillis) { String message = "Client heartbeat is timed out, closing connection to " + connection + ". Now: " + timeToString(currentTimeMillis) + ". LastTimePacketReceived: " + timeToString(lastTimePacketReceived); connection.close(message, null); } }
Source:
private void createToken(JCas aJCas, StringBuilder text, Map<Integer, String> tokens, Map<Integer, String> pos, Map<Integer, String> lemma, Map<String, Token> tokensStored) { int tokenBeginPosition = 0; int tokenEndPosition; for (int i = 1; i <= tokens.size(); i++) { tokenBeginPosition = text.indexOf(tokens.get(i), tokenBeginPosition); Token outToken = new Token(aJCas, tokenBeginPosition, text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length()); tokenEndPosition = text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length(); tokenBeginPosition = tokenEndPosition; outToken.addToIndexes(); if (!pos.get(i).equals("_")) { POS outPos = new POS(aJCas, outToken.getBegin(), outToken.getEnd()); outPos.setPosValue(pos.get(i)); outPos.addToIndexes(); outToken.setPos(outPos); } if (!lemma.get(i).equals("_")) { Lemma outLemma = new Lemma(aJCas, outToken.getBegin(), outToken.getEnd()); outLemma.setValue(lemma.get(i)); outLemma.addToIndexes(); outToken.setLemma(outLemma); } tokensStored.put("t_" + i, outToken); } }

Target:
private void createToken(JCas aJCas, StringBuilder text, Map<Integer, String> tokens, Map<Integer, String> pos, Map<Integer, String> lemma, Map<String, Token> tokensStored) { int tokenBeginPosition = 0; int tokenEndPosition = 0; for (int i = 1; i <= tokens.size(); i++) { tokenBeginPosition = text.indexOf(tokens.get(i), tokenBeginPosition); Token outToken = new Token(aJCas, tokenBeginPosition, text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length()); tokenEndPosition = text.indexOf(tokens.get(i), tokenBeginPosition) + tokens.get(i).length(); tokenBeginPosition = tokenEndPosition; outToken.addToIndexes(); if (!pos.get(i).equals("_")) { POS outPos = new POS(aJCas, outToken.getBegin(), outToken.getEnd()); outPos.setPosValue(pos.get(i)); outPos.addToIndexes(); outToken.setPos(outPos); } if (!lemma.get(i).equals("_")) { Lemma outLemma = new Lemma(aJCas, outToken.getBegin(), outToken.getEnd()); outLemma.setValue(lemma.get(i)); outLemma.addToIndexes(); outToken.setLemma(outLemma); } tokensStored.put("t_" + i, outToken); } }
Source:
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { this.configuration = configuration; this.http = http; this.webhookManager = webhookManager; this.taskHistoryHelper = taskHistoryHelper; this.objectMapper = objectMapper; this.webhookSemaphore = AsyncSemaphore.newBuilder(configuration::getMaxConcurrentWebhooks).build(); this.webhookExecutorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("webhooks-%d").build()); }

Target:
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { this.configuration = configuration; this.http = http; this.webhookManager = webhookManager; this.taskHistoryHelper = taskHistoryHelper; this.objectMapper = objectMapper; this.webhookSemaphore = AsyncSemaphore.newBuilder(configuration::getMaxConcurrentWebhooks).build(); }
Source:
public Mono<AccessToken> getToken() throws InterruptedException, ExecutionException { if (isClosed) { throw logger.logExceptionAsError( new RuntimeException("getToken called on closed CommunicationTokenCredential object")); } synchronized (this) { if ((accessToken == null || accessToken.isExpired()) && refresher != null) { return fetchFreshToken() .map(token -> { accessToken = tokenParser.parseJWTToken(token); return accessToken; }); } return Mono.just(accessToken); } }

Target:
public Mono<AccessToken> getToken() throws InterruptedException, ExecutionException { if (isClosed) { return FluxUtil.monoError(logger, new RuntimeException("getToken called on closed CommunicationTokenCredential object")); } if ((accessToken == null || accessToken.isExpired()) && refresher != null) { synchronized (this) { if ((accessToken == null || accessToken.isExpired()) && refresher != null) { return fetchFreshToken() .map(token -> { accessToken = tokenParser.parseJWTToken(token); return accessToken; }); } } } return Mono.just(accessToken); }
Source:
public NoteMap merge(NoteMap base, NoteMap ours, NoteMap theirs) throws IOException { InMemoryNoteBucket mergedBucket = merge(0, base.getRoot(), ours.getRoot(), theirs.getRoot()); return NoteMap.newMap(mergedBucket, reader); }

Target:
public NoteMap merge(NoteMap base, NoteMap ours, NoteMap theirs) throws IOException { try { InMemoryNoteBucket mergedBucket = merge(0, base.getRoot(), ours.getRoot(), theirs.getRoot()); inserter.flush(); return NoteMap.newMap(mergedBucket, reader); } finally { reader.release(); inserter.release(); } }
Source:
String getOffsetMapString() { StringBuilder sb = new StringBuilder(); sb.append("Current offsets map: "); for (TopicPartition tp : offsets.keySet()) { sb.append("p").append(tp.partition()).append("-") .append(offsets.get(tp).offset()).append(" "); } return sb.toString(); }

Target:
private String getOffsetMapString() { StringBuilder sb = new StringBuilder(); sb.append(getName()).append(" current offsets map: "); for (TopicPartition tp : offsets.keySet()) { sb.append("p").append(tp.partition()).append("-") .append(offsets.get(tp).offset()).append(" "); } return sb.toString(); }
Source:
public final void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Failure { initOptionList(); parseCommandLine(); if (abandonChange) { if (restoreChange) { throw error("abandon and restore actions are mutually exclusive"); } if (submitChange) { throw error("abandon and submit actions are mutually exclusive"); } if (publishPatchSet) { throw error("abandon and publish actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("abandon and delete actions are mutually exclusive"); } } if (publishPatchSet) { if (restoreChange) { throw error("publish and restore actions are mutually exclusive"); } if (submitChange) { throw error("publish and submit actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("publish and delete actions are mutually exclusive"); } } boolean ok = true; for (final PatchSet.Id patchSetId : patchSetIds) { try { ok = ok && approveOne(patchSetId); } catch (UnloggedFailure e) { ok = false; writeError("error: " + e.getMessage() + "\n"); } catch (Exception e) { ok = false; writeError("fatal: internal server error while approving " + patchSetId + "\n"); log.error("internal error while approving " + patchSetId, e); } } if (!ok) { throw new UnloggedFailure(1, "one or more approvals failed;" + " review output above"); } } }); }

Target:
public final void start(final Environment env) { startThread(new CommandRunnable() { @Override public void run() throws Failure { initOptionList(); parseCommandLine(); if (abandonChange) { if (restoreChange) { throw error("abandon and restore actions are mutually exclusive"); } if (submitChange) { throw error("abandon and submit actions are mutually exclusive"); } if (publishPatchSet) { throw error("abandon and publish actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("abandon and delete actions are mutually exclusive"); } } if (publishPatchSet) { if (restoreChange) { throw error("publish and restore actions are mutually exclusive"); } if (submitChange) { throw error("publish and submit actions are mutually exclusive"); } if (deleteDraftPatchSet) { throw error("publish and delete actions are mutually exclusive"); } } boolean ok = true; for (final PatchSet.Id patchSetId : patchSetIds) { try { boolean oneOk = approveOne(patchSetId); ok = ok && oneOk; } catch (UnloggedFailure e) { ok = false; writeError("error: " + e.getMessage() + "\n"); } catch (Exception e) { ok = false; writeError("fatal: internal server error while approving " + patchSetId + "\n"); log.error("internal error while approving " + patchSetId, e); } } if (!ok) { throw new UnloggedFailure(1, "one or more approvals failed;" + " review output above"); } } }); }
Source:
public void dumpMemory() { for (Map.Entry<Double, Double> entry : new TreeMap<>(memory).entrySet()) { log.info(entry.getKey() + "\t" + entry.getValue()); } }

Target:
public void dumpMemory() { Double[] keys = memory.keySet().toArray(new Double[memory.keySet().size()]); Arrays.sort(keys); for (Double key : keys) { log.info(key + "\t" + memory.get(key)); } }
Source:
List<Transaction> sortTxnsByDependency(Set<Transaction> inputSet) { List<Transaction> result = new ArrayList<Transaction>(inputSet); for (int i = 0; i < result.size()-1; i++) { boolean txAtISpendsOtherTxInTheList; do { txAtISpendsOtherTxInTheList = false; for (int j = i+1; j < result.size(); j++) { if (spends(result.get(i), result.get(j))) { Transaction transactionAtI = result.remove(i); result.add(j, transactionAtI); txAtISpendsOtherTxInTheList = true; break; } } } while (txAtISpendsOtherTxInTheList); } return result; }

Target:
List<Transaction> sortTxnsByDependency(Set<Transaction> inputSet) { ArrayList<Transaction> result = new ArrayList<Transaction>(inputSet); for (int i = 0; i < result.size()-1; i++) { boolean txAtISpendsOtherTxInTheList; do { txAtISpendsOtherTxInTheList = false; for (int j = i+1; j < result.size(); j++) { if (spends(result.get(i), result.get(j))) { Transaction transactionAtI = result.remove(i); result.add(j, transactionAtI); txAtISpendsOtherTxInTheList = true; break; } } } while (txAtISpendsOtherTxInTheList); } return result; }
Source:
public CompletableFuture<Registration> register(String procedure, IInvocationHandler endpoint, RegisterOptions options) { if (!isAttached()) { throw new IllegalStateException("The transport must be connected first"); } CompletableFuture<Registration> future = new CompletableFuture<>(); long requestID = mIDGenerator.next(); mRegisterRequest.put(requestID, new RegisterRequest(requestID, future, procedure, endpoint)); if (options != null) { mTransport.send(new Register(requestID, procedure, options.match, options.invoke)); } else { mTransport.send(new Register(requestID, procedure, null, null)); } return future; }

Target:
public CompletableFuture<Registration> register(String procedure, IInvocationHandler endpoint, RegisterOptions options) { if (!isConnected()) { throw new IllegalStateException("The transport must be connected first"); } CompletableFuture<Registration> future = new CompletableFuture<>(); long requestID = mIDGenerator.next(); mRegisterRequest.put(requestID, new RegisterRequest(requestID, future, procedure, endpoint)); if (options != null) { mTransport.send(new Register(requestID, procedure, options.match, options.invoke)); } else { mTransport.send(new Register(requestID, procedure, null, null)); } return future; }
Source:
public void setAttributeMap(List<String> attributeMapEntries) { this.attributeMap = new HashMap<>(); for (String entry : attributeMapEntries) { String[] keyValuePair = entry.split("(?<!\\\\)(?:\\\\\\\\)*=", 2); if (keyValuePair.length == 2) { this.attributeMap.put( StringEscapeUtils.unescapeJava(keyValuePair[0]), StringEscapeUtils.unescapeJava(keyValuePair[1])); } else { LOGGER.error("Invalid attribute map entry: {}", entry); } } }

Target:
public void setAttributeMap(List<String> attributeMapEntries) { this.attributeMap = new HashMap<>(); for (String entry : attributeMapEntries) { String[] keyValuePair = entry.split("(?<!\\\\)(?:\\\\\\\\)*=", 2); if (keyValuePair.length == 2) { this.attributeMap.put( StringEscapeUtils.unescapeJava(keyValuePair[0]), StringEscapeUtils.unescapeJava(keyValuePair[1])); } else { LOGGER.error( "Invalid attribute map entry: \"{}\". Entries must be of the form \"claim=attribute\"", entry); } } setSupportedClaims(this.attributeMap.keySet()); }
Source:
public static Slice serialize(OGCGeometry input) { int wkid = input.SRID(); Geometry geometry = input.getEsriGeometry(); if (geometry == null) { return EMPTY_SLICE; } byte[] shape = GeometryEngine.geometryToEsriShape(geometry); if (shape == null) { return EMPTY_SLICE; } Slice result = Slices.allocate(shape.length + SIZE_WKID); result.setInt(0, wkid); result.setBytes(SIZE_WKID, shape); return result; }

Target:
public static Slice serialize(OGCGeometry input) { int spatialReferenceId = input.SRID(); DynamicSliceOutput sliceOutput = new DynamicSliceOutput(100); sliceOutput.appendInt(spatialReferenceId); GeometryCursor cursor = input.getEsriGeometryCursor(); while (true) { Geometry geometry = cursor.next(); if (geometry == null) { break; } byte[] shape = geometryToEsriShape(geometry); sliceOutput.appendInt(shape.length); sliceOutput.appendBytes(shape); } return sliceOutput.slice(); }
Source:
public WebElement getToolbarLoggedInUser() { return toolbarLoggedInUser; }

Target:
public String getToolbarLoggedInUser() { return getTextFromElement(toolbarLoggedInUser); }
Source:
public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, Joiner.on(",").join(indices)); } else { conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, ""); } }

Target:
public static void setRequiredFieldConf(Configuration conf, RequiredFieldList requiredFieldList) { String value = ""; if (requiredFieldList != null) { List<Integer> indices = Lists.newArrayList(); for(RequiredField f : requiredFieldList.getFields()) { indices.add(f.getIndex()); } value = Joiner.on(",").join(indices); } conf.set(RCFileUtil.REQUIRED_FIELD_INDICES_CONF, value); }
Source:
protected EntityManagerFactory newEntityManagerFactory() { logger.debug("Creating EntityManagerFactory..."); Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.url", JpaConfiguration.dbConnectionUrl); properties.put("javax.persistence.jdbc.driver", JpaConfiguration.dbDriverClass); if(JpaConfiguration.dbUserName != null) { properties.put("javax.persistence.jdbc.user", JpaConfiguration.dbUserName); } if(JpaConfiguration.dbPassword != null) { properties.put("javax.persistence.jdbc.password", JpaConfiguration.dbPassword); } EntityManagerFactory fac = Persistence.createEntityManagerFactory(getPersistenceUnitName(), properties); logger.debug("Creating EntityManagerFactory...done"); return fac; }

Target:
protected EntityManagerFactory newEntityManagerFactory() { logger.debug("Creating EntityManagerFactory..."); Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.url", JpaConfiguration.dbConnectionUrl); properties.put("javax.persistence.jdbc.driver", JpaConfiguration.dbDriverClass); if(JpaConfiguration.dbUserName != null) { properties.put("javax.persistence.jdbc.user", JpaConfiguration.dbUserName); } if(JpaConfiguration.dbPassword != null) { properties.put("javax.persistence.jdbc.password", JpaConfiguration.dbPassword); } if(JpaConfiguration.dbUserName != null && JpaConfiguration.dbPassword == null) { logger.warn("JPA persistence - it is recommended to use a password to protect data store"); } EntityManagerFactory fac = Persistence.createEntityManagerFactory(getPersistenceUnitName(), properties); logger.debug("Creating EntityManagerFactory...done"); return fac; }
Source:
public void testCtor() throws UnsupportedEncodingException { final LocalizedMessage addExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "DefaultLogger.addException", new String[] {"myfile"}, null, LocalizedMessage.class, null); final OutputStream infoStream = new ByteArrayOutputStream(); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); final DefaultLogger dl = new DefaultLogger(infoStream, true, errorStream, true); dl.addException(new AuditEvent(5000, "myfile"), new IllegalStateException("upsss")); dl.auditFinished(new AuditEvent(6000, "myfile")); final String output = errorStream.toString("UTF-8"); assertTrue(output.contains(addExceptionMessage.getMessage())); assertTrue(output.contains("java.lang.IllegalStateException: upsss")); }

Target:
public void testCtor() throws UnsupportedEncodingException { final OutputStream infoStream = new ByteArrayOutputStream(); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); final DefaultLogger dl = new DefaultLogger(infoStream, true, errorStream, true); dl.addException(new AuditEvent(5000, "myfile"), new IllegalStateException("upsss")); dl.auditFinished(new AuditEvent(6000, "myfile")); final String output = errorStream.toString("UTF-8"); final LocalizedMessage addExceptionMessage = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, "DefaultLogger.addException", new String[] {"myfile"}, null, getClass(), null); assertTrue(output.contains(addExceptionMessage.getMessage())); assertTrue(output.contains("java.lang.IllegalStateException: upsss")); }
Source:
private static Geometry readPolyline(SliceInput input) { requireNonNull(input, "input is null"); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { return GEOMETRY_FACTORY.createLineString(); } int pointCount = input.readInt(); LineString[] lineStrings = new LineString[partCount]; int[] numnParts = new int[partCount]; input.readInt(); if (partCount > 1) { numnParts[0] = input.readInt(); for (int i = 1; i < partCount - 1; i++) { numnParts[i] = input.readInt() - numnParts[i - 1]; } numnParts[partCount - 1] = pointCount - numnParts[partCount - 2]; } else { numnParts[0] = pointCount; } for (int i = 0; i < partCount; i++) { lineStrings[i] = GEOMETRY_FACTORY.createLineString(readCoordinates(input, numnParts[i])); } if (lineStrings.length == 1) { return lineStrings[0]; } return GEOMETRY_FACTORY.createMultiLineString(lineStrings); }

Target:
private static Geometry readPolyline(SliceInput input) { requireNonNull(input, "input is null"); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { return GEOMETRY_FACTORY.createLineString(); } int pointCount = input.readInt(); LineString[] lineStrings = new LineString[partCount]; int[] partLengths = new int[partCount]; input.readInt(); if (partCount > 1) { partLengths[0] = input.readInt(); for (int i = 1; i < partCount - 1; i++) { partLengths[i] = input.readInt() - partLengths[i - 1]; } partLengths[partCount - 1] = pointCount - partLengths[partCount - 2]; } else { partLengths[0] = pointCount; } for (int i = 0; i < partCount; i++) { lineStrings[i] = GEOMETRY_FACTORY.createLineString(readCoordinates(input, partLengths[i])); } if (lineStrings.length == 1) { return lineStrings[0]; } return GEOMETRY_FACTORY.createMultiLineString(lineStrings); }
Source:
protected void verifyOutput(NestedOwnerDTO source, Owner dest, boolean childrenGenerated) { if (source != null) { assertNotNull(dest.getId()); assertEquals(source.getKey(), dest.getKey()); assertNotNull(dest.getDisplayName()); } else { assertNull(dest); } }

Target:
protected void verifyOutput(NestedOwnerDTO source, Owner dest, boolean childrenGenerated) { if (source != null) { assertEquals(source.getId(), dest.getId()); assertEquals(source.getKey(), dest.getKey()); assertEquals(source.getDisplayName(), dest.getDisplayName()); } else { assertNull(dest); } }
Source:
public void start() { try { String location = configuration.location(); if (location == null || location.trim().length() == 0) location = "Infinispan-SingleFileStore"; File f = new File(location + File.separator + ctx.getCache().getName() + ".dat"); if (!f.exists()) { File dir = f.getParentFile(); synchronized (SingleFileStore.class) { if (!dir.exists() && !dir.mkdirs()) { throw log.directoryCannotBeCreated(dir.getAbsolutePath()); } } } file = new RandomAccessFile(f, "rw").getChannel(); entries = newEntryMap(); freeList = Collections.synchronizedSortedSet(new TreeSet<FileEntry>()); byte[] header = new byte[MAGIC.length]; if (file.read(ByteBuffer.wrap(header), 0) == MAGIC.length && Arrays.equals(MAGIC, header)) rebuildIndex(); else clear(); } catch (Exception e) { throw new CacheLoaderException(e); } }

Target:
public void start() { try { String location = configuration.location(); if (location == null || location.trim().length() == 0) location = "Infinispan-SingleFileStore"; File f = new File(location + File.separator + ctx.getCache().getName() + ".dat"); if (!f.exists()) { File dir = f.getParentFile(); if (!dir.mkdirs() && !dir.exists()) { throw log.directoryCannotBeCreated(dir.getAbsolutePath()); } } file = new RandomAccessFile(f, "rw").getChannel(); entries = newEntryMap(); freeList = Collections.synchronizedSortedSet(new TreeSet<FileEntry>()); byte[] header = new byte[MAGIC.length]; if (file.read(ByteBuffer.wrap(header), 0) == MAGIC.length && Arrays.equals(MAGIC, header)) rebuildIndex(); else clear(); } catch (Exception e) { throw new CacheLoaderException(e); } }
Source:
snapshotIOStatistics(IOStatistics statistics) { IOStatisticsSnapshot stats = new IOStatisticsSnapshot(statistics); stats.snapshot(statistics); return stats; }

Target:
snapshotIOStatistics(IOStatistics statistics) { return new IOStatisticsSnapshot(statistics); }
Source:
private long countMapWithBackupReadEnabled(Node node) { return maps.stream().filter(distributedObject -> node.getConfig(). getMapConfig(distributedObject.getName()).isReadBackupData()).count(); }

Target:
private long countMapWithBackupReadEnabled(Node node) { return maps.stream().filter(distributedObject -> { MapConfig config = node.getConfig().getMapConfig(distributedObject.getName()); if (config != null) { return config.isReadBackupData(); } return false; }).count(); }
Source:
public long hash(int value) { ByteBuffer plain = ByteBuffer.allocate(Integer.SIZE/Byte.SIZE); plain.order(ByteOrder.LITTLE_ENDIAN).putInt(value); return hashFunction.hashByteBuffer(plain); }

Target:
public long hash(int value) { cacheBuffer.putInt(value); return doHash(); }
Source:
public void newEvent(long bucketKey, T event) { int bucketIdx = (int) (bucketKey % noOfBuckets); AbstractBucket<T> bucket = buckets[bucketIdx]; logger.debug("Adding event to bucket index {}", event, bucketIdx); if(bucket != null){ logger.debug("Old Bucket Key {}, Requested {}", bucket.bucketKey, bucketKey); } if (bucket == null || bucket.bucketKey != bucketKey) { bucket = createBucket(bucketKey); buckets[bucketIdx] = bucket; dirtyBuckets.put(bucketIdx, bucket); } else if (dirtyBuckets.get(bucketIdx) == null) { dirtyBuckets.put(bucketIdx, bucket); } bucket.addNewEvent(bucket.getEventKey(event), writeEventKeysOnly ? null : event); bucketCounters.getCounter(BucketManager.CounterKeys.EVENTS_IN_MEMORY).increment(); Long max = maxExpiryPerBucket[bucketIdx]; long eventTime = getExpiryKey(event); if (max == null || eventTime > max) { maxExpiryPerBucket[bucketIdx] = eventTime; } }

Target:
public void newEvent(long bucketKey, T event) { super.newEvent(bucketKey, event); int bucketIdx = (int) (bucketKey % noOfBuckets); Long max = maxExpiryPerBucket[bucketIdx]; long expiryKey = getExpiryKey(event); if (max == 0 || expiryKey > max) { maxExpiryPerBucket[bucketIdx] = expiryKey; } }
Source:
private static String setupDatabase() { List<String> statements = STATEMENT_SPLITTER.splitToList(scriptContents); for (int i = 1; i < statements.size(); i++) { String statement = statements.get(i); try { SESSION_RULE.session().execute(statement); } catch (Exception e) { fail("Error executing statement %s (%s)", statement, e); } } return scriptContents; }

Target:
private static void setupDatabase() { List<String> statements = STATEMENT_SPLITTER.splitToList(scriptContents); for (int i = 1; i < statements.size(); i++) { String statement = statements.get(i); try { SESSION_RULE.session().execute(statement); } catch (Exception e) { fail("Error executing statement %s (%s)", statement, e); } } }
Source:
private static Instance initializeOpenSourceSoftwareInstanceBuilder(String url) { Instance instance = new Instance(); instance.setInstancetype(INSTANCE_TYPE_SOFTWARE); instance.setAccessright(ACCESS_RIGHT_OPEN_SOURCE); instance.setUrl(Arrays.asList(url)); return instance; }

Target:
private static Instance initializeOpenSourceSoftwareInstanceBuilder(String url) { Instance instance = new Instance(); instance.setInstancetype(INSTANCE_TYPE_SOFTWARE); instance.setAccessright(ACCESS_RIGHT_OPEN_SOURCE); instance.setUrl(Collections.singletonList(url)); return instance; }
Source:
public static void waitForIndexState(Connection conn, String fullIndexName, PIndexState expectedIndexState) throws InterruptedException, SQLException { int maxTries = 60; RetryCounter retrier = new RetryCounter(maxTries, 1, TimeUnit.SECONDS); while (retrier.shouldRetry()) { String schema = SchemaUtil.getSchemaNameFromFullName(fullIndexName); String index = SchemaUtil.getTableNameFromFullName(fullIndexName); String query = "SELECT " + PhoenixDatabaseMetaData.INDEX_STATE + " FROM " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME + " WHERE (" + PhoenixDatabaseMetaData.TABLE_SCHEM + "," + PhoenixDatabaseMetaData.TABLE_NAME + ") = (" + "'" + schema + "','" + index + "') " + "AND " + PhoenixDatabaseMetaData.COLUMN_FAMILY + " IS NULL AND " + PhoenixDatabaseMetaData.COLUMN_NAME + " IS NULL"; ResultSet rs = conn.createStatement().executeQuery(query); PIndexState actualIndexState = null; if (rs.next()) { actualIndexState = PIndexState.fromSerializedValue(rs.getString(1)); boolean matchesExpected = (actualIndexState == expectedIndexState); if (matchesExpected) { return; } } retrier.sleepUntilNextRetry(); } fail("Ran out of time waiting for index state to become " + expectedIndexState); }

Target:
public static void waitForIndexState(Connection conn, String fullIndexName, PIndexState expectedIndexState) throws InterruptedException, SQLException { int maxTries = 60, nTries = 0; do { String schema = SchemaUtil.getSchemaNameFromFullName(fullIndexName); String index = SchemaUtil.getTableNameFromFullName(fullIndexName); Thread.sleep(1000); String query = "SELECT " + PhoenixDatabaseMetaData.INDEX_STATE + " FROM " + PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME + " WHERE (" + PhoenixDatabaseMetaData.TABLE_SCHEM + "," + PhoenixDatabaseMetaData.TABLE_NAME + ") = (" + "'" + schema + "','" + index + "') " + "AND " + PhoenixDatabaseMetaData.COLUMN_FAMILY + " IS NULL AND " + PhoenixDatabaseMetaData.COLUMN_NAME + " IS NULL"; ResultSet rs = conn.createStatement().executeQuery(query); PIndexState actualIndexState = null; if (rs.next()) { actualIndexState = PIndexState.fromSerializedValue(rs.getString(1)); boolean matchesExpected = (actualIndexState == expectedIndexState); if (matchesExpected) { return; } } } while (++nTries < maxTries); fail("Ran out of time waiting for index state to become " + expectedIndexState); }
Source:
public void release() { if (referenceCount.decrementAndGet() == 0) { Futures.addCallback(pagesFuture, new FutureCallback<NestedLoopJoinPages>() { @Override public void onSuccess(NestedLoopJoinPages result) { result.freeMemory(); } @Override public void onFailure(Throwable t) { } }, directExecutor()); } }

Target:
public void release() { if (referenceCount.decrementAndGet() == 0) { addSuccessCallback(pagesFuture, result -> result.freeMemory()); } }
Source:
public String resolveElasticServerDir() { final String value = configuration.esServerDir(); if ( !nullToEmpty( value ).isBlank() ) { return value; } return HomeDir.get().toString() + "/../elasticsearch"; }

Target:
public String resolveElasticServerDir() { final String value = configuration.esServerDir(); return getPathOfDirAsString( value, "../elasticsearch" ); }
Source:
public static void updateLRAContext(ClientRequestContext context) { URL lraId = Current.peek(); if (lraId != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraId); } else { Object lraContext = getState("suspendedLRA"); if (lraContext == null) lraContext = context.getProperty(LRA_HTTP_HEADER); if (lraContext != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraContext); } else { context.getHeaders().remove(LRA_HTTP_HEADER); } } }

Target:
public static void updateLRAContext(ClientRequestContext context) { URL lraId = Current.peek(); if (lraId != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraId); } else { Object lraContext = context.getProperty(LRA_HTTP_HEADER); if (lraContext != null) { context.getHeaders().putSingle(LRA_HTTP_HEADER, lraContext); } else { context.getHeaders().remove(LRA_HTTP_HEADER); } } }
Source:
public static void setupEventTypeWithEvents() throws JsonProcessingException, InterruptedException { eventType = createEventType(); final CountDownLatch finished = new CountDownLatch(1); final AtomicReference<String[]> inTimeCursors = new AtomicReference<>(); createParallelConsumer(eventType.getName(), 8, finished, inTimeCursors::set); final long start = System.currentTimeMillis(); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); finished.await(); cursorsDuringPublish = inTimeCursors.get(); System.out.println("Total took: " + (System.currentTimeMillis() - start)/1000); }

Target:
public static void setupEventTypeWithEvents() throws JsonProcessingException, InterruptedException { eventType = createEventType(); final CountDownLatch finished = new CountDownLatch(1); final AtomicReference<String[]> inTimeCursors = new AtomicReference<>(); createParallelConsumer(eventType.getName(), 8, finished, inTimeCursors::set); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); createTimeline(eventType.getName()); publishEvents(eventType.getName(), 2, i -> "{\"foo\":\"bar\"}"); finished.await(); cursorsDuringPublish = inTimeCursors.get(); }
Source:
public void append(Entry entry) throws IOException { transactionEntries.add(entry); }

Target:
public void append(Entry entry) throws IOException { internalWriter.append(entry.getKey(), entry.getEdit()); }
Source:
public void testReadPipePosixCommandStartFailure() throws CommandFailedException { FS fs = FS.DETECTED.newInstance(); assumeTrue(fs instanceof FS_POSIX); FS.readPipe(fs.userHome(), new String[] { "this-command-does-not-exist" }, Charset.defaultCharset().name()); }

Target:
public void testReadPipePosixCommandStartFailure() throws CommandFailedException { FS fs = FS.DETECTED.newInstance(); FS.readPipe(fs.userHome(), new String[] { "this-command-does-not-exist" }, Charset.defaultCharset().name()); }
Source:
private boolean release0(int decrement) { int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { maxCapacity(-rawMaxCapacity()); deallocate(); return true; } return retryRelease0(decrement); } return releaseNonFinal0(decrement, rawCnt, realCnt); }

Target:
private boolean release0(int decrement) { int rawCnt = nonVolatileRawCnt(), realCnt = toLiveRealCnt(rawCnt, decrement); if (decrement == realCnt) { if (refCntUpdater.compareAndSet(this, rawCnt, 1)) { maxCapacity(-maxCapacity()); deallocate(); return true; } return retryRelease0(decrement); } return releaseNonFinal0(decrement, rawCnt, realCnt); }
Source:
public static EchoTagStatementTree newEchoTagStatement(ExpressionTree expression, InternalSyntaxToken eosToken) { SeparatedList<ExpressionTree> expressionList = new SeparatedListImpl(Collections.singletonList(expression), Collections.emptyList()); return newEchoTagStatement(expressionList, eosToken); }

Target:
private static EchoTagStatementTree newEchoTagStatement(ExpressionTree expression, InternalSyntaxToken eosToken) { SeparatedList<ExpressionTree> expressionList = new SeparatedListImpl<>(Collections.singletonList(expression), Collections.emptyList()); return newEchoTagStatement(expressionList, eosToken); }
Source:
boolean wouldPushProject(Project.NameKey project) { if (projects.length < 1) { return true; } for (final String projectMatch : projects) { if (isRE(projectMatch)) { if ((new RegExp(projectMatch, RegExp.NONE)). toAutomaton().run(project.get())) return true; } else if (projectMatch.endsWith("/*")) { if (project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1))) return true; } else if (project.get().equals(projectMatch)) { return true; } } return false; }

Target:
boolean wouldPushProject(Project.NameKey project) { if (projects.length < 1) { return true; } for (final String projectMatch : projects) { if (isRE(projectMatch)) { if (new RegExp(projectMatch, RegExp.NONE). toAutomaton().run(project.get())) return true; } else if (projectMatch.endsWith("/*")) { if (project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1))) return true; } else if (project.get().equals(projectMatch)) { return true; } } return false; }
Source:
public Map<String, String> getQuota() { return quota; }

Target:
public EmailQuota getQuota() { return quota; }
Source:
public int execute() { try { AtlasReplInfo atlasReplInfo = createAtlasReplInfo(); LOG.info("Dumping Atlas metadata of srcDb: {}, for TgtDb: to staging location:", atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir()); atlasRestClient = new AtlasRestClientBuilder(atlasReplInfo.getAtlasEndpoint()) .getClient(atlasReplInfo.getConf()); AtlasRequestBuilder atlasRequestBuilder = new AtlasRequestBuilder(); String entityGuid = checkHiveEntityGuid(atlasRequestBuilder, atlasReplInfo.getSrcCluster(), atlasReplInfo.getSrcDB()); long currentModifiedTime = getCurrentTimestamp(atlasReplInfo, entityGuid); AtlasDumpLogger replLogger = new AtlasDumpLogger(atlasReplInfo.getSrcDB(), atlasReplInfo.getStagingDir().toString()); replLogger.startLog(); long numBytesWritten = dumpAtlasMetaData(atlasRequestBuilder, atlasReplInfo); LOG.debug("Finished dumping atlas metadata, total:{} bytes written", numBytesWritten); replLogger.endLog(0L); createDumpMetadata(atlasReplInfo, currentModifiedTime); return 0; } catch (Exception e) { LOG.error("Exception while dumping atlas metadata", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }

Target:
public int execute() { try { AtlasReplInfo atlasReplInfo = createAtlasReplInfo(); LOG.info("Dumping Atlas metadata of srcDb: {}, for TgtDb: to staging location:", atlasReplInfo.getSrcDB(), atlasReplInfo.getTgtDB(), atlasReplInfo.getStagingDir()); AtlasDumpLogger replLogger = new AtlasDumpLogger(atlasReplInfo.getSrcDB(), atlasReplInfo.getStagingDir().toString()); replLogger.startLog(); atlasRestClient = new AtlasRestClientBuilder(atlasReplInfo.getAtlasEndpoint()) .getClient(atlasReplInfo.getConf()); AtlasRequestBuilder atlasRequestBuilder = new AtlasRequestBuilder(); String entityGuid = checkHiveEntityGuid(atlasRequestBuilder, atlasReplInfo.getSrcCluster(), atlasReplInfo.getSrcDB()); long currentModifiedTime = getCurrentTimestamp(atlasReplInfo, entityGuid); long numBytesWritten = dumpAtlasMetaData(atlasRequestBuilder, atlasReplInfo); LOG.debug("Finished dumping atlas metadata, total:{} bytes written", numBytesWritten); createDumpMetadata(atlasReplInfo, currentModifiedTime); replLogger.endLog(0L); return 0; } catch (Exception e) { LOG.error("Exception while dumping atlas metadata", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } }
Source:
public static Map<String, Integer> getDRTableNamePartitionColumnMapping(Database db) { Map<String, Integer> res = new HashMap<String, Integer>(); for (Table tb : db.getTables()) { if (tb.getIsdred()) { res.put(tb.getTypeName(), tb.getPartitioncolumn().getIndex()); } } return res; }

Target:
public static Map<String, Integer> getDRTableNamePartitionColumnMapping(Database db) { Map<String, Integer> res = new HashMap<String, Integer>(); for (Table tb : db.getTables()) { if (!tb.getIsreplicated() && tb.getIsdred()) { res.put(tb.getTypeName(), tb.getPartitioncolumn().getIndex()); } } return res; }
Source:
LockFactory pickLockFactory(RuntimeEnvironment env) { String luceneLocking = env.getLuceneLocking(); switch (luceneLocking) { case LuceneLockName.OFF: return NoLockFactory.INSTANCE; case LuceneLockName.ON: case LuceneLockName.SIMPLE: return SimpleFSLockFactory.INSTANCE; case LuceneLockName.NATIVE: return NativeFSLockFactory.INSTANCE; default: LOGGER.log(Level.WARNING, "Unknown Lucene locking mode: {0}", luceneLocking); return NoLockFactory.INSTANCE; } }

Target:
LockFactory pickLockFactory(RuntimeEnvironment env) { switch (env.getLuceneLocking()) { case ON: case SIMPLE: return SimpleFSLockFactory.INSTANCE; case NATIVE: return NativeFSLockFactory.INSTANCE; case OFF: default: return NoLockFactory.INSTANCE; } }
Source:
public final void create() throws Exception { final String name = "test-repo"; final Github github = RtReposITCase.github(); final Repos repos = github.repos(); final Repo repo = repos.create(request(name)); MatcherAssert.assertThat(repo, Matchers.notNullValue()); }

Target:
public final void create() throws Exception { final String name = RandomStringUtils.randomNumeric(5); final Repos repos = RtReposITCase.github().repos(); try { MatcherAssert.assertThat( repos.create(request(name)), Matchers.notNullValue() ); } finally { final Coordinates.Simple coordinates = new Coordinates.Simple( RtReposITCase.github().users().self().login(), name ); repos.remove(coordinates); } }
Source:
public String getReleaseNotesForFixVersion(String projectKey, String versionName, String filter) throws IOException { JiraSession session = getSession(); if (session == null) { return ""; } List<Issue> issues = session.getIssuesWithFixVersion(projectKey, versionName, filter); if (issues == null) { return ""; } Map<String, Set<String>> releaseNotes = new HashMap<String, Set<String>>(); for (Issue issue : issues) { String key = issue.getKey(); String summary = issue.getSummary(); String status = issue.getStatus().getName(); String type = issue.getIssueType().getName(); Set<String> issueSet; if (!releaseNotes.containsKey(type)) { issueSet = new HashSet<String>(); releaseNotes.put(type, issueSet); } else { issueSet = releaseNotes.get(type); } issueSet.add(String.format(" - [%s] %s (%s)", key, summary, status)); } StringBuilder sb = new StringBuilder(); for (String type : releaseNotes.keySet()) { sb.append(String.format("# %s\n", type)); for (String issue : releaseNotes.get(type)) { sb.append(issue); sb.append("\n"); } } return sb.toString(); }

Target:
public String getReleaseNotesForFixVersion(String projectKey, String versionName, String filter) throws IOException { JiraSession session = getSession(); if (session == null) { return ""; } List<Issue> issues = session.getIssuesWithFixVersion(projectKey, versionName, filter); if (issues == null) { return ""; } Map<String, Set<String>> releaseNotes = new HashMap<String, Set<String>>(); for (Issue issue : issues) { String key = issue.getKey(); String summary = issue.getSummary(); String status = issue.getStatus().getName(); String type = "UNKNOWN"; if (issue.getIssueType() != null && issue.getIssueType().getName() != null) { type = issue.getIssueType().getName(); } Set<String> issueSet; if (!releaseNotes.containsKey(type)) { issueSet = new HashSet<String>(); releaseNotes.put(type, issueSet); } else { issueSet = releaseNotes.get(type); } issueSet.add(String.format(" - [%s] %s (%s)", key, summary, status)); } StringBuilder sb = new StringBuilder(); for (String type : releaseNotes.keySet()) { sb.append(String.format("# %s\n", type)); for (String issue : releaseNotes.get(type)) { sb.append(issue); sb.append("\n"); } } return sb.toString(); }
Source:
public void gotoExternalComponentSettings() { activeSection = 3; editorStatus.saveSelectedOption(displayerSettings.getUUID(), activeSection); initComponentEditor(); view.gotoExternalComponentSettings(externalComponentPropertiesEditor); }

Target:
public void gotoExternalComponentSettings() { activeSection = EXTERNAL_COMPONENT_SECTION; editorStatus.saveSelectedOption(displayerSettings.getUUID(), activeSection); initComponentEditor(); view.gotoExternalComponentSettings(externalComponentPropertiesEditor); }