auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { ColumnExpression columnExp = (ColumnExpression)exps.get(0); LiteralExpression isAscendingExpression = (LiteralExpression)exps.get(1); boolean isAscending = (Boolean)isAscendingExpression.getValue(); LiteralExpression percentileExp = (LiteralExpression)exps.get(2); float p = ((Number)percentileExp.getValue()).floatValue(); NavigableMap<ImmutableBytesPtr, Integer> sortedMap = new TreeMap<ImmutableBytesPtr, Integer>(valueVsCount); if (!isAscending) { sortedMap = sortedMap.descendingMap(); } float i = (p * this.totalCount) + 0.5F; long k = (long)i; float f = i - k; ImmutableBytesPtr pi1 = null; ImmutableBytesPtr pi2 = null; long distinctCountsSum = 0; for (Entry<ImmutableBytesPtr, Integer> entry : sortedMap.entrySet()) { if (pi1 != null) { pi2 = entry.getKey(); break; } distinctCountsSum += entry.getValue(); if (distinctCountsSum == k) { pi1 = entry.getKey(); } else if (distinctCountsSum > k) { pi1 = pi2 = entry.getKey(); break; } } float result = 0F; Number n1 = (Number)columnExp.getDataType().toObject(pi1); if (pi2 == null || pi1 == pi2) { result = n1.floatValue(); } else { Number n2 = (Number)columnExp.getDataType().toObject(pi2); result = (n1.floatValue() * (1.0F - f)) + (n2.floatValue() * f); } this.cachedResult = new BigDecimal(result); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(this.cachedResult); ptr.set(buffer); return true; }

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { if (cachedResult == null) { ColumnExpression columnExp = (ColumnExpression)exps.get(0); LiteralExpression isAscendingExpression = (LiteralExpression)exps.get(1); boolean isAscending = (Boolean)isAscendingExpression.getValue(); LiteralExpression percentileExp = (LiteralExpression)exps.get(2); float p = ((Number)percentileExp.getValue()).floatValue(); Entry<ImmutableBytesPtr, Integer>[] entries = getSortedValueVsCount(isAscending); float i = (p * this.totalCount) + 0.5F; long k = (long)i; float f = i - k; ImmutableBytesPtr pi1 = null; ImmutableBytesPtr pi2 = null; long distinctCountsSum = 0; for (Entry<ImmutableBytesPtr, Integer> entry : entries) { if (pi1 != null) { pi2 = entry.getKey(); break; } distinctCountsSum += entry.getValue(); if (distinctCountsSum == k) { pi1 = entry.getKey(); } else if (distinctCountsSum > k) { pi1 = pi2 = entry.getKey(); break; } } double result = 0.0; Number n1 = (Number)columnExp.getDataType().toObject(pi1); if (pi2 == null || pi1 == pi2) { result = n1.doubleValue(); } else { Number n2 = (Number)columnExp.getDataType().toObject(pi2); result = (n1.doubleValue() * (1.0F - f)) + (n2.doubleValue() * f); } this.cachedResult = new BigDecimal(result); } if (buffer == null) { initBuffer(); } buffer = PDataType.DECIMAL.toBytes(this.cachedResult); ptr.set(buffer); return true; }
Source:
public static Optional<Long> findLedgerByName(BookKeeper bk, String name) throws Exception { Map<Long, LedgerMetadata> ledgers = new HashMap<Long, LedgerMetadata>(); final AtomicInteger returnCode = new AtomicInteger(BKException.Code.OK); final CountDownLatch processDone = new CountDownLatch(1); bk.getLedgerManager() .asyncProcessLedgers((ledgerId, cb) -> collectLedgers(bk, ledgerId, cb, ledgers), (rc, s, obj) -> { returnCode.set(rc); processDone.countDown(); }, null, BKException.Code.OK, BKException.Code.ReadException); processDone.await(5, TimeUnit.MINUTES); log.info("Ledgers collected: total found=" + ledgers.size()); byte[] nameBytes = name.getBytes(); Optional<Entry<Long, LedgerMetadata>> entry = ledgers.entrySet() .stream() .filter((e) -> { Map<String, byte[]> meta = e.getValue().getCustomMetadata(); if (meta != null) { log.info("ledger: " + e.getKey() + ", customMeta=" + meta); byte[] data = meta.get("name"); if (data != null && Arrays.equals(data, nameBytes)) { return true; } else { return false; } } else { log.info("ledger: " + e.getKey() + ", no meta"); return false; } }) .findFirst(); if (entry.isPresent()) { return Optional.of(entry.get().getKey()); } else { return Optional.empty(); } }

Target:
public static Optional<Long> findLedgerByName(BookKeeper bk, String name) throws Exception { Map<Long, LedgerMetadata> ledgers = new HashMap<Long, LedgerMetadata>(); final AtomicInteger returnCode = new AtomicInteger(BKException.Code.OK); final CountDownLatch processDone = new CountDownLatch(1); bk.getLedgerManager() .asyncProcessLedgers( (ledgerId, cb) -> collectLedgers(bk, ledgerId, cb, ledgers), (rc, s, obj) -> { returnCode.set(rc); processDone.countDown(); }, null, BKException.Code.OK, BKException.Code.ReadException); processDone.await(5, TimeUnit.MINUTES); LOG.info("Ledgers collected: total found=" + ledgers.size()); byte[] nameBytes = name.getBytes(); Optional<Entry<Long, LedgerMetadata>> entry = ledgers.entrySet() .stream() .filter((e) -> { Map<String, byte[]> meta = e.getValue() .getCustomMetadata(); if (meta != null) { LOG.info("ledger: " + e.getKey() + ", customMeta=" + meta); byte[] data = meta.get("name"); if (data != null && Arrays.equals(data, nameBytes)) { return true; } else { return false; } } else { LOG.info("ledger: " + e.getKey() + ", no meta"); return false; } }) .findFirst(); if (entry.isPresent()) { return Optional.of(entry.get() .getKey()); } else { return Optional.empty(); } }
Source:
private double protectionFull( ResolvedCds cds, CreditDiscountFactors discountFactors, LegalEntitySurvivalProbabilities survivalProbabilities, LocalDate referenceDate, LocalDate effectiveStartDate) { DoubleArray integrationSchedule = DoublesScheduleGenerator.getIntegrationsPoints( discountFactors.relativeYearFraction(effectiveStartDate), discountFactors.relativeYearFraction(cds.getProtectionEndDate()), discountFactors.getParameterKeys(), survivalProbabilities.getParameterKeys()); double pv = 0d; double ht0 = survivalProbabilities.zeroRate(integrationSchedule.get(0)) * integrationSchedule.get(0); double rt0 = discountFactors.zeroRate(integrationSchedule.get(0)) * integrationSchedule.get(0); double b0 = Math.exp(-ht0 - rt0); int n = integrationSchedule.size(); for (int i = 1; i < n; ++i) { double ht1 = survivalProbabilities.zeroRate(integrationSchedule.get(i)) * integrationSchedule.get(i); double rt1 = discountFactors.zeroRate(integrationSchedule.get(i)) * integrationSchedule.get(i); double b1 = Math.exp(-ht1 - rt1); double dht = ht1 - ht0; double drt = rt1 - rt0; double dhrt = dht + drt; double dPV = 0d; if (Math.abs(dhrt) < 1e-5) { dPV = dht * b0 * epsilon(-dhrt); } else { dPV = (b0 - b1) * dht / dhrt; } pv += dPV; ht0 = ht1; rt0 = rt1; b0 = b1; } double df = discountFactors.discountFactor(referenceDate); pv /= df; return pv; }

Target:
private double protectionFull( ResolvedCds cds, CreditDiscountFactors discountFactors, LegalEntitySurvivalProbabilities survivalProbabilities, LocalDate referenceDate, LocalDate effectiveStartDate) { DoubleArray integrationSchedule = DoublesScheduleGenerator.getIntegrationsPoints( discountFactors.relativeYearFraction(effectiveStartDate), discountFactors.relativeYearFraction(cds.getProtectionEndDate()), discountFactors.getParameterKeys(), survivalProbabilities.getParameterKeys()); double pv = 0d; double ht0 = survivalProbabilities.zeroRate(integrationSchedule.get(0)) * integrationSchedule.get(0); double rt0 = discountFactors.zeroRate(integrationSchedule.get(0)) * integrationSchedule.get(0); double b0 = Math.exp(-ht0 - rt0); int n = integrationSchedule.size(); for (int i = 1; i < n; ++i) { double ht1 = survivalProbabilities.zeroRate(integrationSchedule.get(i)) * integrationSchedule.get(i); double rt1 = discountFactors.zeroRate(integrationSchedule.get(i)) * integrationSchedule.get(i); double b1 = Math.exp(-ht1 - rt1); double dht = ht1 - ht0; double drt = rt1 - rt0; double dhrt = dht + drt; double dPV = 0d; if (Math.abs(dhrt) < SMALL) { dPV = dht * b0 * epsilon(-dhrt); } else { dPV = (b0 - b1) * dht / dhrt; } pv += dPV; ht0 = ht1; rt0 = rt1; b0 = b1; } double df = discountFactors.discountFactor(referenceDate); return pv / df; }
Source:
public static HashMap<String, Object> getMetaFieldsAndValues(Externalizable e) throws RecordTooLargeException{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStream out = bos; try { e.writeExternal(new DataOutputStream(out)); out.close(); } catch (IOException e1) { e1.printStackTrace(); throw new RuntimeException("Failed to serialize externalizable for content values"); } byte[] blob = bos.toByteArray(); HashMap<String, Object> values = new HashMap<String, Object>(); if(e instanceof IMetaData) { IMetaData m = (IMetaData)e; for(String key : m.getMetaDataFields()) { Object o = m.getMetaData(key); if(o == null ) { continue;} String value = o.toString(); values.put(TableBuilder.scrubName(key), value); } } if(blob.length > 1000000){ throw new RecordTooLargeException(blob.length / 1000000); } values.put(DATA_COL, blob); return values; }

Target:
public static HashMap<String, Object> getMetaFieldsAndValues(Externalizable e) throws RecordTooLargeException{ byte[] blob = TableBuilder.toBlob(e); HashMap<String, Object> values = new HashMap<String, Object>(); if(e instanceof IMetaData) { IMetaData m = (IMetaData)e; for(String key : m.getMetaDataFields()) { Object o = m.getMetaData(key); if(o == null ) { continue;} String value = o.toString(); values.put(TableBuilder.scrubName(key), value); } } if(blob.length > 1000000){ throw new RecordTooLargeException(blob.length / 1000000); } values.put(DATA_COL, blob); return values; }
Source:
public CharSequence toXML(XmlEnvironment xmlEnvironment) { XmlStringBuilder xml = new XmlStringBuilder(this); parseInfos(xml); parsePointers(xml); closeElement(xml); return xml; }

Target:
public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) { XmlStringBuilder xml = new XmlStringBuilder(this, xmlEnvironment); appendInfoElements(xml); appendPointerElements(xml); closeElement(xml); return xml; }
Source:
public Boolean visitPrimitive_Primitive( AnnotatedPrimitiveType subtype, AnnotatedPrimitiveType supertype, Void p) { boolean superResult = super.visitPrimitive_Primitive(subtype, supertype, p); if (superResult) { return true; } PrimitiveType subPrimitive = subtype.getUnderlyingType(); PrimitiveType superPrimitive = supertype.getUnderlyingType(); if (isNarrowerIntegral(subPrimitive, superPrimitive)) { AnnotationMirror superAnno = supertype.getAnnotationInHierarchy(UNKNOWN_SIGNEDNESS); if (!superAnno.equals(SIGNEDNESS_BOTTOM)) { return true; } } return false; }

Target:
public Boolean visitPrimitive_Primitive( AnnotatedPrimitiveType subtype, AnnotatedPrimitiveType supertype, Void p) { boolean superResult = super.visitPrimitive_Primitive(subtype, supertype, p); if (superResult) { return true; } PrimitiveType subPrimitive = subtype.getUnderlyingType(); PrimitiveType superPrimitive = supertype.getUnderlyingType(); if (isNarrowerIntegral(subPrimitive, superPrimitive)) { AnnotationMirror superAnno = supertype.getAnnotationInHierarchy(UNKNOWN_SIGNEDNESS); if (!AnnotationUtils.areSameByName(superAnno, SIGNEDNESS_BOTTOM)) { return true; } } return false; }
Source:
void someMethod(Root root) { root.getFoo(); }

Target:
void someMethod(Root root) { root.getFoo().getBar(); }
Source:
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { hash = in.readInt(); ncols = in.readInt(); column = new DataValueDescriptor[ncols]; for (int i = 0; i < ncols; i++) { column[i] = (DataValueDescriptor) in.readObject(); } StructType structType = (StructType)in.readObject(); schema = structType.length() > 0 ? Optional.of(structType) : Optional.empty(); }

Target:
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { hash = in.readInt(); ncols = in.readInt(); column = new DataValueDescriptor[ncols]; for (int i = 0; i < ncols; i++) { column[i] = (DataValueDescriptor) in.readObject(); } }
Source:
public int compare(final SAMRecord samRecord1, final SAMRecord samRecord2) { int cmp; if (null == samRecord1.getHeader() || null == samRecord2.getHeader()) { throw new IllegalArgumentException("Record must have non-null SAMFileHeaders to be comapred"); } int samRecord1Value, samRecord2Value; cmp = fileOrderCompare(samRecord1, samRecord2); if (cmp == 0) { cmp = DuplicateScoringStrategy.compare(samRecord1, samRecord2, this.scoringStrategy, true); } if (cmp == 0) { cmp = samRecord1.getReadName().compareTo(samRecord2.getReadName()); } if (cmp == 0) { if (samRecord1.getReadPairedFlag() && samRecord2.getReadPairedFlag()) { samRecord1Value = samRecord1.getFirstOfPairFlag() ? 0 : 1; samRecord2Value = samRecord2.getFirstOfPairFlag() ? 0 : 1; cmp = samRecord1Value - samRecord2Value; } } return cmp; }

Target:
public int compare(final SAMRecord samRecord1, final SAMRecord samRecord2) { populateTransientAttributes(samRecord1, samRecord2); int cmp; int samRecord1Value, samRecord2Value; cmp = fileOrderCompare(samRecord1, samRecord2); if (cmp == 0) { cmp = DuplicateScoringStrategy.compare(samRecord1, samRecord2, this.scoringStrategy, true); } if (cmp == 0) { cmp = samRecord1.getReadName().compareTo(samRecord2.getReadName()); } if (cmp == 0) { if (samRecord1.getReadPairedFlag() && samRecord2.getReadPairedFlag()) { samRecord1Value = samRecord1.getFirstOfPairFlag() ? 0 : 1; samRecord2Value = samRecord2.getFirstOfPairFlag() ? 0 : 1; cmp = samRecord1Value - samRecord2Value; } } return cmp; }
Source:
public void verifyLastEditHistorySummary(String targetText) { Assertion.assertStringContains(targetText, getLastHistorySummary()); PageObjectLogging.log("verifyLastEditHistorySummary", "verifying the last edit summary shows " + targetText, true); }

Target:
public void verifyLastEditHistorySummary(String targetText) { Assertion.assertStringContains(targetText, getLastHistorySummary()); PageObjectLogging.log( "verifyLastEditHistorySummary", "The last edit summary shows " + targetText, true ); }
Source:
public int getBaseTime() { if (campaign.getCampaignOptions().useAeroSystemHits()) { Entity e = unit.getEntity(); if (isSalvaging()) { if (e.hasETypeFlag(Entity.ETYPE_DROPSHIP) || e.hasETypeFlag(Entity.ETYPE_JUMPSHIP)) { if (e.hasNavalC3()) { return 8640; } return 4320; } else { return 1080; } } if (hits == 1) { if (e.hasETypeFlag(Entity.ETYPE_DROPSHIP) || e.hasETypeFlag(Entity.ETYPE_JUMPSHIP)) { if (e.hasNavalC3()) { return 480; } return 240; } else { return 120; } } if (hits == 2) { if (e.hasETypeFlag(Entity.ETYPE_DROPSHIP) || e.hasETypeFlag(Entity.ETYPE_JUMPSHIP)) { if (e.hasNavalC3()) { return 960; } return 480; } else { return 240; } } } if(isSalvaging()) { return 4320; } return 120; }

Target:
public int getBaseTime() { int time = 0; if (campaign.getCampaignOptions().useAeroSystemHits()) { Entity e = unit.getEntity(); if (e.hasETypeFlag(Entity.ETYPE_DROPSHIP) || e.hasETypeFlag(Entity.ETYPE_JUMPSHIP)) { time = 120; if (e.hasNavalC3()) { time *= 2; } } else { time = 60; } if (isSalvaging()) { time *= 10; } if (hits == 1) { time *= 1; } if (hits == 2) { time *= 2; } return time; } if(isSalvaging()) { time = 4320; } else { time = 120; } return time; }
Source:
public void setRow(int row, double... values) { if (values.length != SIZE) { throw new IllegalArgumentException("Call setRow received an array of length " + values.length + ". " + "The dimensions of the matrix is 2 by 2."); } if (row == 0) { m00 = values[0]; m01 = values[1]; } else if (row == 1) { m10 = values[2]; m11 = values[3]; } else { throw new IllegalArgumentException("Specified element is out of bounds: (" + row + " , 0)"); } }

Target:
public void setRow(int row, double... values) { if (values.length != SIZE) { throw new IllegalArgumentException("Call setRow received an array of length " + values.length + ". " + "The dimensions of the matrix is 2 by 2."); } if (row == 0) { m00 = values[0]; m01 = values[1]; } else if (row == 1) { m10 = values[0]; m11 = values[1]; } else { throw new IllegalArgumentException("Specified element is out of bounds: (" + row + " , 0)"); } }
Source:
public static String hmacDigest(String msg, String keyString, String algo) { String digest = null; try { SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo); Mac mac = Mac.getInstance(algo); mac.init(key); byte[] bytes = mac.doFinal(msg.getBytes("ASCII")); StringBuffer hash = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hash.append('0'); } hash.append(hex); } digest = hash.toString(); } catch (UnsupportedEncodingException e) { } catch (InvalidKeyException e) { } catch (NoSuchAlgorithmException e) { } return digest; }

Target:
public static String hmacDigest(String msg, String keyString, String algo) { String digest = null; try { SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo); String algorithm; if (!algo.toLowerCase().startsWith("hmac")) { algorithm = "hmac" + algo.toLowerCase(); } else { algorithm = algo.toLowerCase(); } Mac mac = Mac.getInstance(algorithm); mac.init(key); byte[] bytes = mac.doFinal(msg.getBytes("ASCII")); StringBuffer hash = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hash.append('0'); } hash.append(hex); } digest = hash.toString(); } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException e) { throw new IllegalStateException("HMAC digest could not be obtained correctly.", e); } return digest; }
Source:
default <T> SearchPage<T> queryForPage(Query query, Class<T> clazz, IndexCoordinates index) { return SearchHitSupport.searchPageFor(queryForList(query, clazz, index), query.getPageable()); }

Target:
default <T> AggregatedPage<T> queryForPage(Query query, Class<T> clazz, IndexCoordinates index) { return (AggregatedPage<T>) SearchHitSupport.unwrapSearchHits(searchForPage(query, clazz, index)); }
Source:
public static void trace(String option, String message, Throwable throwable) { String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.println(partial + "\\"); } if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } }

Target:
public static void trace(String option, String message, Throwable throwable) { String systemPrintableMessage = message; while (systemPrintableMessage.length() > 100) { String partial = systemPrintableMessage.substring(0, 100); systemPrintableMessage = systemPrintableMessage.substring(100); System.out.println(partial + "\\"); } System.out.println(systemPrintableMessage); if(fgDebugTrace != null) { fgDebugTrace.trace(option, message, throwable); } }
Source:
public void shouldFailWhenMovingDocumentBlobAlreadyInColdStorage() { DocumentModel documentModel = createDocument(true); documentModel = moveContentToColdStorage(session, documentModel.getRef()); documentModel = session.getDocument(documentModel.getRef()); try { moveContentToColdStorage(session, documentModel.getRef()); fail("Should fail because the content is already in cold storage"); } catch (NuxeoException ne) { assertEquals(SC_CONFLICT, ne.getStatusCode()); assertEquals( String.format("The main content of documentModel: %s is already in cold storage.", documentModel), ne.getMessage()); } }

Target:
public void shouldFailWhenMovingDocumentBlobAlreadyInColdStorage() { DocumentModel documentModel = createDocument(true); documentModel = moveContentToColdStorage(session, documentModel.getRef()); try { moveContentToColdStorage(session, documentModel.getRef()); fail("Should fail because the content is already in cold storage"); } catch (NuxeoException ne) { assertEquals(SC_CONFLICT, ne.getStatusCode()); assertEquals(String.format("The main content for document: %s is already in cold storage.", documentModel), ne.getMessage()); } }
Source:
public void run() { final List<HealthCheckResult> healthChecks = zookeeperClients.stream() .map(this::doHealthCheck) .collect(Collectors.toList()); if (!modeService.isReadOnlyEnabled() && healthChecks.contains(HealthCheckResult.UNHEALTHY)) { modeService.setMode(ModeService.ManagementMode.READ_ONLY); } else if (modeService.isReadOnlyEnabled() && !healthChecks.contains(HealthCheckResult.UNHEALTHY)) { modeService.setMode(ModeService.ManagementMode.READ_WRITE); } }

Target:
public void run() { final List<HealthCheckResult> healthCheckResults = zookeeperClients.stream() .map(this::doHealthCheck) .collect(Collectors.toList()); updateMode(healthCheckResults); }
Source:
private Event createCommandEvent(String topic, String payload, String source) { String itemName = getItemName(topic); ItemEventPayloadBean bean = deserializePayload(payload, ItemEventPayloadBean.class); Command command = null; try { command = (Command) parse(bean.getType() + TYPE_POSTFIX, bean.getValue()); } catch (Exception e) { throw new IllegalArgumentException("Parsing of item command event failed.", e); } return new ItemCommandEvent(topic, payload, itemName, command, source); }

Target:
private Event createCommandEvent(String topic, String payload, String source) { String itemName = getItemName(topic); ItemEventPayloadBean bean = deserializePayload(payload, ItemEventPayloadBean.class); Command command = parseType(bean.getType(), bean.getValue(), Command.class); return new ItemCommandEvent(topic, payload, itemName, command, source); }
Source:
private void encodePropertiesByType( PropertyType parentType, PropertyDescriptor descriptor, List<Property> properties) { List<Feature> chainedFeatures = getChainedFeatures(properties); if (chainedFeatures == null || chainedFeatures.isEmpty() || descriptor.getMaxOccurs() == 1) { List<Map<NameImpl, String>> linkedFeatures = getLinkedFeatures(properties); if (!linkedFeatures.isEmpty()) { encodeLinkedFeatures(descriptor, linkedFeatures); } else { String attributeName = descriptor.getName().getLocalPart(); if (properties.size() > 1 && properties .stream() .allMatch( prop -> Objects.equals( attributeName, prop.getName().getLocalPart()))) { jsonWriter.key(attributeName).array(); properties.forEach( prop -> encodeProperty( INSIDE_ARRAY_ATTRIBUTE, prop, getAttributes(prop))); jsonWriter.endArray(); } else { properties.forEach(this::encodeProperty); } } } else { encodeChainedFeatures(descriptor.getName().getLocalPart(), chainedFeatures); } }

Target:
private void encodePropertiesByType( PropertyType parentType, PropertyDescriptor descriptor, List<Property> properties) { List<Feature> chainedFeatures = getChainedFeatures(properties); if (chainedFeatures == null || chainedFeatures.isEmpty() || descriptor.getMaxOccurs() == 1) { List<Map<NameImpl, String>> linkedFeatures = getLinkedFeatures(properties); if (!linkedFeatures.isEmpty()) { encodeLinkedFeatures(descriptor, linkedFeatures); } else { encodeProperties(descriptor, properties); } } else { encodeChainedFeatures(descriptor.getName().getLocalPart(), chainedFeatures); } }
Source:
public void handleArtifactEvent(ArtifactEvent artifactEvent, Sender sender) { boolean refreshWorkflow = false; if (artifactEvent == null) { return; } for (EventBasicGuidArtifact event : artifactEvent.getArtifacts()) { if (event.is(EventModType.Modified)) { refreshWorkflow = true; break; } } if (refreshWorkflow) { Displays.ensureInDisplayThread(new Runnable() { @Override public void run() { redrawComposite(); } }); } }

Target:
public void handleArtifactEvent(ArtifactEvent artifactEvent, Sender sender) { if (artifactEvent.isModified(getTeamArt())) { Displays.ensureInDisplayThread(new Runnable() { @Override public void run() { loadTable(); } }); } }
Source:
public void initializedWithPopulatedChangeLog() throws Exception { final QueryChangeLog changeLog = new InMemoryQueryChangeLog(); final QueryRepository queries = new InMemoryQueryRepository( changeLog, SCHEDULE ); try { queries.startAndWait(); final Set<StreamsQuery> expected = new HashSet<>(); expected.add( queries.add("query 1", true) ); final UUID deletedMeId = queries.add("query 2", false).getQueryId(); expected.add( queries.add("query 3", true) ); queries.delete( deletedMeId ); final QueryRepository initializedQueries = new InMemoryQueryRepository( changeLog, SCHEDULE ); try { final Set<StreamsQuery> stored = initializedQueries.list(); assertEquals(expected, stored); } finally { queries.stop(); } } finally { queries.stop(); } }

Target:
public void initializedWithPopulatedChangeLog() throws Exception { final QueryChangeLog changeLog = new InMemoryQueryChangeLog(); final QueryRepository queries = new InMemoryQueryRepository( changeLog, SCHEDULE ); try { queries.startAndWait(); final Set<StreamsQuery> expected = new HashSet<>(); expected.add( queries.add("query 1", true) ); final UUID deletedMeId = queries.add("query 2", false).getQueryId(); expected.add( queries.add("query 3", true) ); queries.delete( deletedMeId ); final QueryRepository initializedQueries = new InMemoryQueryRepository( changeLog, SCHEDULE ); final Set<StreamsQuery> stored = initializedQueries.list(); assertEquals(expected, stored); } finally { queries.stop(); } }
Source:
public ManagementResourceRegistration register(ManagementResourceRegistration parent) { ManagementResourceRegistration registration = parent.registerSubModel(this); parent.registerAlias(LEGACY_PATH, new SimpleAliasEntry(registration)); Capability dependentCapability = new BinaryRequirementCapability(InfinispanCacheRequirement.CACHE, BinaryCapabilityNameResolver.GRANDPARENT_PARENT); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(Attribute.class) .addResourceCapabilityReference(new TransactionResourceCapabilityReference(dependentCapability, TransactionRequirement.TRANSACTION_MANAGER, EnumSet.of(TransactionMode.NONE, TransactionMode.BATCH))) .addResourceCapabilityReference(new TransactionResourceCapabilityReference(dependentCapability, TransactionRequirement.XA_RESOURCE_RECOVERY_REGISTRY, EnumSet.complementOf(EnumSet.of(TransactionMode.NON_XA)))); ResourceServiceHandler handler = new SimpleResourceServiceHandler(TransactionServiceConfigurator::new); new SimpleResourceRegistration(descriptor, handler).register(registration); if (registration.isRuntimeOnlyRegistrationValid()) { new MetricHandler<>(new TransactionMetricExecutor(), TransactionMetric.class).register(registration); } return registration; }

Target:
public ManagementResourceRegistration register(ManagementResourceRegistration parent) { ManagementResourceRegistration registration = parent.registerSubModel(this); parent.registerAlias(LEGACY_PATH, new SimpleAliasEntry(registration)); Capability dependentCapability = new BinaryRequirementCapability(InfinispanCacheRequirement.CACHE, BinaryCapabilityNameResolver.GRANDPARENT_PARENT); ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(Attribute.class) .addResourceCapabilityReference(new TransactionResourceCapabilityReference(dependentCapability, TransactionRequirement.LOCAL_TRANSACTION_PROVIDER, EnumSet.of(TransactionMode.NONE, TransactionMode.BATCH))) .addResourceCapabilityReference(new TransactionResourceCapabilityReference(dependentCapability, TransactionRequirement.XA_RESOURCE_RECOVERY_REGISTRY, EnumSet.complementOf(EnumSet.of(TransactionMode.FULL_XA)))); ResourceServiceHandler handler = new SimpleResourceServiceHandler(TransactionServiceConfigurator::new); new SimpleResourceRegistration(descriptor, handler).register(registration); if (registration.isRuntimeOnlyRegistrationValid()) { new MetricHandler<>(new TransactionMetricExecutor(), TransactionMetric.class).register(registration); } return registration; }
Source:
public LogMetadata() { this.globalTail = Address.NON_ADDRESS; this.streamTails = new HashMap(); this.streamsAddressSpaceMap = new HashMap(); }

Target:
public LogMetadata() { this.globalTail = Address.NON_ADDRESS; this.streamTails = new HashMap(); this.streamsAddressSpaceMap = new HashMap<>(); }
Source:
IndexValue findKey(StoreKey key, FileSpan fileSpan) throws StoreException { return findKey(key, fileSpan, null); }

Target:
IndexValue findKey(StoreKey key, FileSpan fileSpan) throws StoreException { return findKey(key, fileSpan, IndexEntryType.ANY); }
Source:
public String run() throws IOException { Process process = new ProcessBuilder(mCommand).redirectErrorStream(true).start(); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); try { StringBuilder output = new StringBuilder(); String line = inReader.readLine(); while (line != null) { output.append(line); output.append("\n"); line = inReader.readLine(); } int exitCode = process.waitFor(); if (exitCode != 0) { throw new ShellUtils.ExitCodeException(exitCode, output.toString()); } return output.toString(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } finally { try { InputStream stdout = process.getInputStream(); synchronized (stdout) { inReader.close(); } } catch (IOException e) { LOG.warn("Error while closing the input stream", e); } process.destroy(); } }

Target:
public String run() throws IOException { Process process = new ProcessBuilder(mCommand).redirectErrorStream(true).start(); BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); try { StringBuilder output = new StringBuilder(); String line = inReader.readLine(); while (line != null) { output.append(line); output.append("\n"); line = inReader.readLine(); } int exitCode = process.waitFor(); if (exitCode != 0) { throw new ShellUtils.ExitCodeException(exitCode, output.toString()); } return output.toString(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } finally { try { InputStream stdout = process.getInputStream(); synchronized (stdout) { inReader.close(); } } catch (IOException e) { LOG.warn(String.format("Error while closing the input stream of process %s: %s", process, e.getMessage())); } process.destroy(); } }
Source:
public void syncSearch(VdcQueryType vdcQueryType, VdcQueryParametersBase vdcQueryParametersBase) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { setItems((Collection<T>) ((VdcQueryReturnValue) ReturnValue).getReturnValue()); } }; vdcQueryParametersBase.setRefresh(getIsQueryFirstTime()); Frontend.getInstance().runQuery(vdcQueryType, vdcQueryParametersBase, _asyncQuery); setIsQueryFirstTime(false); }

Target:
protected void syncSearch(VdcQueryType vdcQueryType, VdcQueryParametersBase vdcQueryParametersBase) { AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { setItems((Collection<T>) ((VdcQueryReturnValue) ReturnValue).getReturnValue()); } }; vdcQueryParametersBase.setRefresh(getIsQueryFirstTime()); Frontend.getInstance().runQuery(vdcQueryType, vdcQueryParametersBase, _asyncQuery); setIsQueryFirstTime(false); }
Source:
private void maybeCheckLocalBitcoinNode(Runnable nextStep) { BaseCurrencyNetwork baseCurrencyNetwork = config.baseCurrencyNetwork; var shouldIgnoreLocalNode = config.ignoreLocalBtcNode || baseCurrencyNetwork.isDaoRegTest() || baseCurrencyNetwork.isDaoTestNet(); if (shouldIgnoreLocalNode) { nextStep.run(); return; } localBitcoinNode.checkUsable(); var detectedButMisconfigured = localBitcoinNode.isDetectedButMisconfigured().get(); if (detectedButMisconfigured) { displayLocalNodeMisconfigurationHandler.accept(nextStep); return; } nextStep.run(); }

Target:
private void maybeCheckLocalBitcoinNode(Runnable nextStep) { if (localBitcoinNode.shouldBeIgnored()) { nextStep.run(); return; } if (localBitcoinNode.isDetectedButMisconfigured()) { if (displayLocalNodeMisconfigurationHandler != null) { displayLocalNodeMisconfigurationHandler.accept(nextStep); return; } else { log.error("displayLocalNodeMisconfigurationHandler undefined", new RuntimeException()); } } nextStep.run(); }
Source:
public void transitionToWaiting() { if (state == State.WAITING) { return; } state = State.WAITING; mainView.setClickable(false); editText.setActive(false); suggestionDropdown.setVisibility(View.GONE); }

Target:
private void transitionToWaiting() { if (state == State.WAITING) { return; } state = State.WAITING; mainView.setClickable(false); editText.setActive(false); suggestionDropdown.setVisibility(View.GONE); }
Source:
protected void findMoreStuff() { IInventoryComposite chests = cache.getAdjacentInventories(); for (IInvSlot slot : InventoryIterator.getVanilla(craftMatrix)) { ItemStack stack = slot.getStack(); if (!InvTools.isEmpty(stack) && stack.isStackable() && sizeOf(stack) == 1) { ItemStack request = InvTools.removeOneItem(chests, StackFilters.of(stack)); if (request != null) { inc(stack); break; } if (sizeOf(stack) > 1) break; } } }

Target:
protected void findMoreStuff() { IInventoryComposite chests = cache.getAdjacentInventories(); for (IInvSlot slot : InventoryIterator.getVanilla(craftMatrix)) { ItemStack stack = slot.getStack(); if (!InvTools.isEmpty(stack) && stack.isStackable() && sizeOf(stack) == 1) { ItemStack request = InvTools.removeOneItem(chests, StackFilters.of(stack)); if (!isEmpty(request)) { inc(stack); break; } if (sizeOf(stack) > 1) break; } } }
Source:
public void cancelDelayedAction(CancelDelayedActionEvent event, EntityRef entity) { DelayedActionComponent delayedComponent = entity.getComponent(DelayedActionComponent.class); delayedOperationsSortedByTime.remove(delayedComponent.getWorldTime(), new DelayedOperation(entity, delayedComponent.getActionId())); entity.removeComponent(DelayedActionComponent.class); }

Target:
public void cancelDelayedAction(CancelDelayedActionEvent event, EntityRef entity) { entity.removeComponent(DelayedActionComponent.class); }
Source:
public void testCatchErrorOnEmbeddedSubprocessWithEmptyErrorCode() { try { testCatchErrorOnEmbeddedSubprocess(); } catch (ActivitiException re) { } }

Target:
public void testCatchErrorOnEmbeddedSubprocessWithEmptyErrorCode() { Throwable throwable = catchThrowable(() -> repositoryService .createDeployment() .addClasspathResource("org/activiti/engine/test/bpmn/event/error/BoundaryErrorEventTest.testCatchErrorOnEmbeddedSubprocessWithEmptyErrorCode.bpmn20.xml") .deploy()); assertThat(throwable).isInstanceOf(ActivitiException.class) .hasMessageContaining("activiti-error-missing-error-code"); }
Source:
private void editPipeline() throws Exception { CvPipeline pipeline = partSettings.getPipeline(); Camera camera = Configuration.get().getMachine().getDefaultHead().getDefaultCamera(); pipeline.setProperty("camera", camera); pipeline.setProperty("part", part); pipeline.setProperty("package", part.getPackage()); pipeline.setProperty("footprint", part.getPackage().getFootprint()); CvPipelineEditor editor = new CvPipelineEditor(pipeline); JDialog dialog = new CvPipelineEditorDialog(MainFrame.get(), "Fiducial Locator Pipeline", editor); dialog.setVisible(true); editor.initializeFocus(); }

Target:
private void editPipeline() throws Exception { CvPipeline pipeline = partSettings.getPipeline(); Camera camera = Configuration.get().getMachine().getDefaultHead().getDefaultCamera(); pipeline.setProperty("camera", camera); pipeline.setProperty("part", part); pipeline.setProperty("package", part.getPackage()); pipeline.setProperty("footprint", part.getPackage().getFootprint()); CvPipelineEditor editor = new CvPipelineEditor(pipeline); JDialog dialog = new CvPipelineEditorDialog(MainFrame.get(), "Fiducial Locator Pipeline", editor); dialog.setVisible(true); }
Source:
public Response<Set<String>> apply(ChangeResource req, Input input) throws AuthException, OrmException, IOException, BadRequestException { if (input == null || Strings.isNullOrEmpty(input.hashtags)) { throw new BadRequestException("Hashtags are required"); } ChangeControl control = req.getControl(); if (!control.canEditHashtags()) { throw new AuthException("Editing hashtags not permitted"); } ChangeUpdate update = updateFactory.create(control); ChangeNotes notes = control.getNotes().load(); Set<String> existingHashtags = notes.getHashtags(); Set<String> updatedHashtags = new HashSet<String>(); Set<String> added = new HashSet<String>(); ArrayList<String> toAdd = Lists.newArrayList(Splitter.on(CharMatcher.anyOf(",;")) .trimResults().split(input.hashtags)); if (existingHashtags != null) { updatedHashtags.addAll(existingHashtags); for (String hashtag: toAdd) { if (!existingHashtags.contains(hashtag)) { added.add(hashtag); } } } if (added.size() > 0) { updatedHashtags.addAll(added); update.setHashtags(updatedHashtags); update.commit(); IdentifiedUser currentUser = ((IdentifiedUser) control.getCurrentUser()); hooks.doHashtagsEditedHook( req.getChange(), currentUser.getAccount(), added, null, updatedHashtags, dbProvider.get()); } return Response.ok(updatedHashtags); }

Target:
public Response<Set<String>> apply(ChangeResource req, Input input) throws AuthException, OrmException, IOException, BadRequestException { if (input == null || Strings.isNullOrEmpty(input.hashtags)) { throw new BadRequestException("Hashtags are required"); } ChangeControl control = req.getControl(); if (!control.canEditHashtags()) { throw new AuthException("Editing hashtags not permitted"); } ChangeUpdate update = updateFactory.create(control); ChangeNotes notes = control.getNotes().load(); Set<String> existingHashtags = notes.getHashtags(); Set<String> updatedHashtags = new HashSet<String>(); Set<String> added = new HashSet<String>(); ArrayList<String> toAdd = Lists.newArrayList(Splitter.on(CharMatcher.anyOf(",;")) .trimResults().split(input.hashtags)); if (existingHashtags != null) { updatedHashtags.addAll(existingHashtags); for (String hashtag: toAdd) { if (!existingHashtags.contains(hashtag)) { added.add(hashtag); } } } if (added.size() > 0) { updatedHashtags.addAll(added); update.setHashtags(updatedHashtags); update.commit(); indexer.index(dbProvider.get(), update.getChange()); IdentifiedUser currentUser = ((IdentifiedUser) control.getCurrentUser()); hooks.doHashtagsEditedHook( req.getChange(), currentUser.getAccount(), added, null, updatedHashtags, dbProvider.get()); } return Response.ok(updatedHashtags); }
Source:
public void actionPerformed(ActionEvent event) { final String METHOD_NAME = "actionPerformed(ActionEvent)"; if(event.getActionCommand().equals(GM_TOOL_DICE)) { performDiceRoll(); } if(event.getActionCommand().equals(RAT_ROLLER_TOOL)) { lastRolledUnit = performRollRat(); } if(event.getActionCommand().equals(RAT_ADDER_TOOL)) { if (lastRolledUnit == null) { lastRolledUnit = performRollRat(); } Entity e; try { e = new MechFileParser(lastRolledUnit.getSourceFile(), lastRolledUnit.getEntryName()).getEntity(); Unit u = gui.getCampaign().addUnit(e, false, 0); if (person != null) { u.addPilotOrSoldier(person); person.setOriginalUnit(u); setVisible(false); } lastRolledUnit = null; } catch (EntityLoadingException e1) { MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.ERROR, "Failed to load entity " + lastRolledUnit.getName() + " from " + lastRolledUnit.getSourceFile().toString()); MekHQ.getLogger().error(getClass(), METHOD_NAME, e1); unitPicked.setText("Failed to load entity " + lastRolledUnit.getName()); } } }

Target:
public void actionPerformed(ActionEvent event) { final String METHOD_NAME = "actionPerformed(ActionEvent)"; if(event.getActionCommand().equals(GM_TOOL_DICE)) { performDiceRoll(); } if(event.getActionCommand().equals(RAT_ROLLER_TOOL)) { lastRolledUnit = performRollRat(); } if(event.getActionCommand().equals(RAT_ADDER_TOOL)) { if (lastRolledUnit == null) { lastRolledUnit = performRollRat(); } if (lastRolledUnit != null) { Entity e; try { e = new MechFileParser(lastRolledUnit.getSourceFile(), lastRolledUnit.getEntryName()).getEntity(); Unit u = gui.getCampaign().addUnit(e, false, 0); if (person != null) { u.addPilotOrSoldier(person); person.setOriginalUnit(u); setVisible(false); } lastRolledUnit = null; } catch (EntityLoadingException e1) { MekHQ.getLogger().log(getClass(), METHOD_NAME, LogLevel.ERROR, "Failed to load entity " + lastRolledUnit.getName() + " from " + lastRolledUnit.getSourceFile().toString()); MekHQ.getLogger().error(getClass(), METHOD_NAME, e1); unitPicked.setText("Failed to load entity " + lastRolledUnit.getName()); } } } }
Source:
public void testAddPartition() throws Exception { String topic = "test"; int partition = 0; TopicPartition topicPart = new TopicPartition(topic, partition); Set<TopicPartition> assignment = new HashSet<>(); assignment.add(topicPart); HdfsWriter hdfsWriter = new HdfsWriter(connectorConfig, assignment); hdfsWriter.recover(topicPart); String key = "key"; org.apache.kafka.copycat.data.Schema schema = createSchema(); Struct record = createRecord(schema); for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(topic, partition, org.apache.kafka.copycat.data.Schema.STRING_SCHEMA, key, schema, record, offset); hdfsWriter.writeRecord(topicPart, sinkRecord); } hdfsWriter.close(); fs.delete(new Path(FileUtils.logFileName(url, topicsDir, topicPart)), false); Schema avroSchema = AvroData.fromCopycatSchema(createSchema()); HiveExec hiveExec = new HiveExec(conf, connectorConfig); runHive(hiveExec, "DROP TABLE " + topic); hiveExec.createAvroTable(topic, avroSchema); hiveExec.addPartition(topic, 0); hiveExec.setPartitionLoc(topic, 0); String[] expectedResult = {"true", "12", "12", "12.2", "12.2", "0"}; String result = runHive(hiveExec, "SELECT * from " + topic); String[] rows = result.split("\n"); assertEquals(7, rows.length); for (String row: rows) { String[] parts = row.replace(" ", "").split("\t"); for (int j = 0; j < expectedResult.length; ++j) { assertEquals(expectedResult[j], parts[j]); } } }

Target:
public void testAddPartition() throws Exception { prepareData(TOPIC, PARTITION); Schema avroSchema = avroData.fromCopycatSchema(createSchema()); HiveExec hiveExec = new HiveExec(conf, connectorConfig); runHive(hiveExec, "DROP TABLE " + TOPIC); hiveExec.createAvroTable(TOPIC, avroSchema); hiveExec.addPartition(TOPIC, PARTITION); hiveExec.setPartitionLoc(TOPIC, PARTITION); String[] expectedResult = {"true", "12", "12", "12.2", "12.2", "12"}; String result = runHive(hiveExec, "SELECT * from " + TOPIC); String[] rows = result.split("\n"); assertEquals(7, rows.length); for (String row: rows) { String[] parts = parseOutput(row); for (int j = 0; j < expectedResult.length; ++j) { assertEquals(expectedResult[j], parts[j]); } } }
Source:
public List<String> getUserStoresPrefixList() throws JSONException { UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> userDBName = DBOpenHelper.getUserDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return userDBName; }

Target:
public List<String> getUserStoresPrefixList() { UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> userDBName = DBOpenHelper.getUserDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return userDBName; }
Source:
public List<String> getNodeIpsAndPorts(MesosUnicastHostsProvider mesosUnicastHostsProvider) { String taskHostName = "_" + Configuration.TASK_NAME + "._tcp." + Configuration.FRAMEWORK_NAME + ".mesos"; final ArrayList<String> nodes = Lists.newArrayList(); Attributes attrs; NamingEnumeration<?> enumeration; try { attrs = ctx.getAttributes(taskHostName, new String[]{"SRV"}); final Attribute srvRecords = attrs.get("SRV"); if (srvRecords != null && srvRecords.size() > 0) { enumeration = srvRecords.getAll(); while (enumeration.hasMore()) { SrvRecord record = new SrvRecord((String) enumeration.next()); nodes.add(record.getHostAndPort()); } } } catch (NamingException e) { throw new RuntimeException("Failed to resolve hostname", e); } return nodes; }

Target:
public List<String> getNodeIpsAndPorts(MesosUnicastHostsProvider mesosUnicastHostsProvider) { String taskHostName = "_" + Configuration.TASK_NAME + "._tcp." + Configuration.FRAMEWORK_NAME + "." + Configuration.DOMAIN; final ArrayList<String> nodes = Lists.newArrayList(); Attributes attrs; NamingEnumeration<?> enumeration; try { attrs = ctx.getAttributes(taskHostName, new String[]{"SRV"}); final Attribute srvRecords = attrs.get("SRV"); if (srvRecords != null && srvRecords.size() > 0) { enumeration = srvRecords.getAll(); while (enumeration.hasMore()) { SrvRecord record = new SrvRecord((String) enumeration.next()); nodes.add(record.getHostAndPort()); } } } catch (NamingException e) { throw new RuntimeException("Failed to resolve hostname", e); } return nodes; }
Source:
public void testUseMetaAfterCreate() throws IOException { DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>()); w.create(Schema.create(Type.NULL), new ByteArrayOutputStream()); w.setMeta("foo", "bar"); w.close(); }

Target:
public void testUseMetaAfterCreate() throws IOException { try (DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>())) { w.create(Schema.create(Type.NULL), new ByteArrayOutputStream()); w.setMeta("foo", "bar"); } }
Source:
public DocumentTypeDescriptor merge(DocumentTypeDescriptor other) { if (schemas == null) { schemas = other.schemas; } else { if (other.schemas != null) { List<SchemaDescriptor> mergedSchemas = new ArrayList<SchemaDescriptor>(Arrays.asList(schemas)); mergedSchemas.addAll(Arrays.asList(other.schemas)); schemas = mergedSchemas.toArray(new SchemaDescriptor[mergedSchemas.size()]); } } if (facets == null) { facets = other.facets; } else { if (other.facets != null) { List<String> mergedFacets = new ArrayList<String>(Arrays.asList(facets)); mergedFacets.addAll(Arrays.asList(other.facets)); facets = mergedFacets.toArray(new String[mergedFacets.size()]); } } if (prefetch == null) { prefetch = other.prefetch; } else { if (other.prefetch != null) { prefetch = prefetch + " " + other.prefetch; } } if (subtypes == null) { subtypes = other.subtypes; } else if (other.subtypes != null) { List<String> mergedTypes = new ArrayList<String>(Arrays.asList(subtypes)); mergedTypes.addAll(Arrays.asList(other.subtypes)); subtypes = mergedTypes.toArray(new String[mergedTypes.size()]); } if (blacklistedSubtypes == null) { blacklistedSubtypes = other.blacklistedSubtypes; } else if (other.blacklistedSubtypes != null) { List<String> mergedTypes = new ArrayList<String>(Arrays.asList(blacklistedSubtypes)); mergedTypes.addAll(Arrays.asList(other.blacklistedSubtypes)); blacklistedSubtypes = mergedTypes.toArray(new String[mergedTypes.size()]); } return this; }

Target:
public DocumentTypeDescriptor merge(DocumentTypeDescriptor other) { if (schemas == null) { schemas = other.schemas; } else { if (other.schemas != null) { List<SchemaDescriptor> mergedSchemas = new ArrayList<SchemaDescriptor>(Arrays.asList(schemas)); mergedSchemas.addAll(Arrays.asList(other.schemas)); schemas = mergedSchemas.toArray(new SchemaDescriptor[mergedSchemas.size()]); } } if (facets == null) { facets = other.facets; } else { if (other.facets != null) { List<String> mergedFacets = new ArrayList<String>(Arrays.asList(facets)); mergedFacets.addAll(Arrays.asList(other.facets)); facets = mergedFacets.toArray(new String[mergedFacets.size()]); } } if (prefetch == null) { prefetch = other.prefetch; } else { if (other.prefetch != null) { prefetch = prefetch + " " + other.prefetch; } } if (subtypes == null) { subtypes = other.subtypes; } else if (other.subtypes != null) { List<String> mergedTypes = new ArrayList<>(Arrays.asList(subtypes)); mergedTypes.addAll(Arrays.asList(other.subtypes)); subtypes = mergedTypes.toArray(new String[mergedTypes.size()]); } if (forbiddenSubtypes == null) { forbiddenSubtypes = other.forbiddenSubtypes; } else if (other.forbiddenSubtypes != null) { List<String> mergedTypes = new ArrayList<>(Arrays.asList(forbiddenSubtypes)); mergedTypes.addAll(Arrays.asList(other.forbiddenSubtypes)); forbiddenSubtypes = mergedTypes.toArray(new String[mergedTypes.size()]); } return this; }