auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean isExistingUser(Map<String, String> subject) throws InternalErrorException { if (subject.isEmpty()) { return false; } String login = subject.get("login"); PerunSession sess = getSession(); List<User> usersFromREMS = perunBl.getUsersManagerBl().getUsersByExtSourceTypeAndLogin(sess, ExtSourcesManager.EXTSOURCE_REMS, login); if (usersFromREMS.size() > 0) { return true; } String extSource = subject.get("additionalues_1"); if (extSource == null) { log.error("Failed to get additionalues_1 from subject {}", subject); throw new InternalErrorException("Failed to get additionalues_1 from subject: " + subject); } String[] extSourceSplit = subject.get("additionalues_1").split("\\|", 4); if(extSourceSplit.length != 4) { log.error("Ivalid format of additionalues_1. It should be '{extSourceName}|{extSourceClass}|{eppn}|0'. Actual: {}", extSource); throw new InternalErrorException("Ivalid format of additionalues_1. It should be '{extSourceName}|{extSourceClass}|{eppn}|0', Actual: " + extSource); } String extSourceName = extSourceSplit[0]; String eppn = extSourceSplit[2]; try { perunBl.getUsersManagerBl().getUserByExtSourceNameAndExtLogin(sess, extSourceName, eppn); return true; } catch (ExtSourceNotExistsException | UserExtSourceNotExistsException e) { log.error("Failed to get extSource with name '{}'", extSourceName); } catch (UserNotExistsException e) { return false; } return false; }

Target:
private boolean isExistingUser(Map<String, String> subject) throws InternalErrorException { if (subject == null || subject.isEmpty()) { throw new InternalErrorException("Subject can not be empty or null: " + subject); } String login = subject.get("login"); if (login == null || login.isEmpty()) { log.error("Failed to get user's login from subject {}"); return false; } PerunSession sess = getSession(); List<User> usersFromREMS = perunBl.getUsersManagerBl().getUsersByExtSourceTypeAndLogin(sess, ExtSourcesManager.EXTSOURCE_REMS, login); if (usersFromREMS.size() > 0) { return true; } List<String> extSources = getAdditionalUESes(subject); if (extSources.isEmpty()) { log.error("Failed to get any additionalues from subject {}", subject); return false; } for (String ues : extSources) { if (existsSubjectWithUes(ues)) { return true; } } return false; }
Source:
private static synchronized void initializeModes() { if (modes != null) { return; } modes = new LinkedHashMap<>(); modes.put(GroupLaunchElement.MODE_INHERIT, new InheritModeGroup()); Set<ILaunchGroup> sortedGroups = new TreeSet<>((a, b) -> a.getLabel().compareTo(b.getLabel())); LaunchConfigurationManager mgr = DebugUIPlugin.getDefault().getLaunchConfigurationManager(); sortedGroups.addAll(Arrays.asList(mgr.getLaunchGroups())); for (ILaunchGroup launchGroup : sortedGroups) { LaunchHistory history = mgr.getLaunchHistory(launchGroup.getIdentifier()); if (history == null) { continue; } String modeName = launchGroup.getMode(); if (!modes.containsKey(modeName)) { modes.put(modeName, launchGroup); } } }

Target:
private static synchronized void initializeModes() { if (modes != null) { return; } modes = new LinkedHashMap<>(); modes.put(GroupLaunchElement.MODE_INHERIT, new InheritModeGroup()); Set<ILaunchGroup> sortedGroups = new TreeSet<>(Comparator.comparing(ILaunchGroup::getLabel)); LaunchConfigurationManager mgr = DebugUIPlugin.getDefault().getLaunchConfigurationManager(); sortedGroups.addAll(Arrays.asList(mgr.getLaunchGroups())); for (ILaunchGroup launchGroup : sortedGroups) { LaunchHistory history = mgr.getLaunchHistory(launchGroup.getIdentifier()); if (history == null) { continue; } String modeName = launchGroup.getMode(); if (!modes.containsKey(modeName)) { modes.put(modeName, launchGroup); } } }
Source:
public void send(String recipient, String messageSubject, String messageBody) throws MessagingException { try { Message msg = new MimeMessage(session); msg.setFrom(from); InternetAddress address = new InternetAddress(recipient); msg.setRecipient(Message.RecipientType.TO, address); if (replyTo != null) { msg.setReplyTo(new Address[] { replyTo }); } msg.setSubject(messageSubject); if (isBodyHtml){ msg.setContent(String.format("<html><head><title>%s</title></head><body><p>%s</body></html>", messageSubject, messageBody), "text/html"); } else { msg.setText(messageBody); } msg.setSentDate(new Date()); if (isSSL) { Transport transport = session.getTransport("smtps"); transport.connect(); transport.sendMessage(msg, new Address[] { address }); } else { Transport.send(msg); } } catch (MessagingException mex) { StringBuilder errorMsg = new StringBuilder("Failed to send message "); if (from != null) { errorMsg.append(" from " + from.toString()); } if (recipient != null) { errorMsg.append(" to " + recipient); } if (messageSubject != null) { errorMsg.append(" with subject " + messageSubject); } errorMsg.append(" due to to error: " + mex.getMessage()); log.error(errorMsg.toString(), mex); throw mex; } }

Target:
public void send(String recipient, String messageSubject, String messageBody) throws MessagingException { try { Message msg = new MimeMessage(session); msg.setFrom(from); InternetAddress address = new InternetAddress(recipient); msg.setRecipient(Message.RecipientType.TO, address); if (replyTo != null) { msg.setReplyTo(new Address[] { replyTo }); } msg.setSubject(messageSubject); if (isBodyHtml){ msg.setContent(String.format("<html><head><title>%s</title></head><body><p>%s</body></html>", messageSubject, messageBody), "text/html"); } else { msg.setText(messageBody); } msg.setSentDate(new Date()); if (isSSL) { Transport transport = session.getTransport("smtps"); transport.connect(); transport.sendMessage(msg, new Address[] { address }); } else { Transport.send(msg); } } catch (MessagingException mex) { StringBuilder errorMsg = new StringBuilder("Failed to send message "); if (from != null) { errorMsg.append(" from " + from.toString()); } if (StringUtils.isNotBlank(recipient)) { errorMsg.append(" to " + recipient); } if (StringUtils.isNotBlank(messageSubject)) { errorMsg.append(" with subject " + messageSubject); } errorMsg.append(" due to to error: " + mex.getMessage()); log.error(errorMsg.toString(), mex); throw mex; } }
Source:
public void when_assemble_expect_poolContentStackedOnChannel() { ChannelStackPoolContentAssembler sut = new ChannelStackPoolContentAssembler(); INDArray[] poolContent = new INDArray[] { Nd4j.rand(2, 2), Nd4j.rand(2, 2), }; INDArray result = sut.assemble(poolContent); assertEquals(3, result.shape().length); assertEquals(2, result.shape()[0]); assertEquals(2, result.shape()[1]); assertEquals(2, result.shape()[2]); assertEquals(poolContent[0].getDouble(new int[] { 0, 0 }), result.getDouble(new int[] { 0, 0, 0 }), 0.0001); assertEquals(poolContent[0].getDouble(new int[] { 0, 1 }), result.getDouble(new int[] { 0, 0, 1 }), 0.0001); assertEquals(poolContent[0].getDouble(new int[] { 1, 0 }), result.getDouble(new int[] { 0, 1, 0 }), 0.0001); assertEquals(poolContent[0].getDouble(new int[] { 1, 1 }), result.getDouble(new int[] { 0, 1, 1 }), 0.0001); assertEquals(poolContent[1].getDouble(new int[] { 0, 0 }), result.getDouble(new int[] { 1, 0, 0 }), 0.0001); assertEquals(poolContent[1].getDouble(new int[] { 0, 1 }), result.getDouble(new int[] { 1, 0, 1 }), 0.0001); assertEquals(poolContent[1].getDouble(new int[] { 1, 0 }), result.getDouble(new int[] { 1, 1, 0 }), 0.0001); assertEquals(poolContent[1].getDouble(new int[] { 1, 1 }), result.getDouble(new int[] { 1, 1, 1 }), 0.0001); }

Target:
public void when_assemble_expect_poolContentStackedOnChannel() { ChannelStackPoolContentAssembler sut = new ChannelStackPoolContentAssembler(); INDArray[] poolContent = new INDArray[] { Nd4j.rand(2, 2), Nd4j.rand(2, 2), }; INDArray result = sut.assemble(poolContent); assertEquals(3, result.shape().length); assertEquals(2, result.shape()[0]); assertEquals(2, result.shape()[1]); assertEquals(2, result.shape()[2]); assertEquals(poolContent[0].getDouble(0, 0), result.getDouble(0, 0, 0), 0.0001); assertEquals(poolContent[0].getDouble(0, 1), result.getDouble(0, 0, 1), 0.0001); assertEquals(poolContent[0].getDouble(1, 0), result.getDouble(0, 1, 0), 0.0001); assertEquals(poolContent[0].getDouble(1, 1), result.getDouble(0, 1, 1), 0.0001); assertEquals(poolContent[1].getDouble(0, 0), result.getDouble(1, 0, 0), 0.0001); assertEquals(poolContent[1].getDouble(0, 1), result.getDouble(1, 0, 1), 0.0001); assertEquals(poolContent[1].getDouble(1, 0), result.getDouble(1, 1, 0), 0.0001); assertEquals(poolContent[1].getDouble(1, 1), result.getDouble(1, 1, 1), 0.0001); }
Source:
public PdpFeedFileBaseEntry createPdpFileBaseEntryThatDoesNotContainNonReimbursableSections(PdpFeedFileBaseEntry pdpFeedFileBaseEntry, ConcurStandardAccountingExtractBatchReportData reportData) { LOG.debug("Entering removeNonReimbursableSectionsFromPdpFeedFileBaseEntry"); PdpFeedFileBaseEntry newBaseEntry = new PdpFeedFileBaseEntry(); newBaseEntry.setHeader(copyHeaderEntry(pdpFeedFileBaseEntry.getHeader())); newBaseEntry.setVersion(pdpFeedFileBaseEntry.getVersion()); addGroupEntriesToNewBaseEntry(newBaseEntry, pdpFeedFileBaseEntry); newBaseEntry.setTrailer(buildPdpFeedTrailerEntry(newBaseEntry, reportData)); return newBaseEntry; }

Target:
public PdpFeedFileBaseEntry createPdpFileBaseEntryThatDoesNotContainNonReimbursableSections(PdpFeedFileBaseEntry pdpFeedFileBaseEntry, ConcurStandardAccountingExtractBatchReportData reportData) { LOG.debug("Entering createPdpFileBaseEntryThatDoesNotContainNonReimbursableSections"); PdpFeedFileBaseEntry newBaseEntry = new PdpFeedFileBaseEntry(); newBaseEntry.setHeader(copyHeaderEntry(pdpFeedFileBaseEntry.getHeader())); newBaseEntry.setVersion(pdpFeedFileBaseEntry.getVersion()); addGroupEntriesToNewBaseEntry(newBaseEntry, pdpFeedFileBaseEntry); newBaseEntry.setTrailer(buildPdpFeedTrailerEntry(newBaseEntry, reportData)); return newBaseEntry; }
Source:
private byte[] idBufferBlob(final Entry e) { try { final InputStream is = e.openInputStream(); if (is == null) return zeroid; try { initializeDigestAndReadBuffer(); final long length = e.getLength(); if (!options.isAutocrlf()) return calculateHash(is, length); if (length <= MAXIMUM_FILE_SIZE_TO_READ_FULLY) { final byte[] bytes = IO.readFully(is, (int) length); if (RawText.isBinary(new ByteArrayInputStream(bytes))) return calculateHash(new ByteArrayInputStream(bytes), length); final long canonicalLength = determineCanonicalizedLength(new ByteArrayInputStream( bytes)); return calculateHash(new EolCanonicalizingInputStream( new ByteArrayInputStream(bytes)), canonicalLength); } final InputStream binaryIs = e.openInputStream(); try { if (RawText.isBinary(binaryIs)) return calculateHash(is, length); } finally { binaryIs.close(); } final long canonicalLength; final InputStream lengthIs = e.openInputStream(); try { canonicalLength = determineCanonicalizedLength(lengthIs); } finally { lengthIs.close(); } return calculateHash(new EolCanonicalizingInputStream(is), canonicalLength); } finally { try { is.close(); } catch (IOException err2) { } } } catch (IOException err) { return zeroid; } }

Target:
private byte[] idBufferBlob(final Entry e) { try { final InputStream is = e.openInputStream(); if (is == null) return zeroid; try { initializeDigestAndReadBuffer(); final long length = e.getLength(); if (!options.isAutoCRLF()) return calculateHash(is, length); if (length <= MAXIMUM_FILE_SIZE_TO_READ_FULLY) { final byte[] bytes = IO.readFully(is, (int) length); if (RawText.isBinary(bytes)) return calculateHash(new ByteArrayInputStream(bytes), length); final InputStream lengthIs = new ByteArrayInputStream(bytes); final long canonicalLength = determineCanonicalizedLength(lengthIs); final InputStream contentIs = new EolCanonicalizingInputStream( new ByteArrayInputStream(bytes)); return calculateHash(contentIs, canonicalLength); } final InputStream binaryIs = e.openInputStream(); try { if (RawText.isBinary(binaryIs)) return calculateHash(is, length); } finally { binaryIs.close(); } final long canonicalLength; final InputStream lengthIs = e.openInputStream(); try { canonicalLength = determineCanonicalizedLength(lengthIs); } finally { lengthIs.close(); } return calculateHash(new EolCanonicalizingInputStream(is), canonicalLength); } finally { try { is.close(); } catch (IOException err2) { } } } catch (IOException err) { return zeroid; } }
Source:
private void trimEvictionMaps() { long now = Time.monotonicNow(); demoteOldEvictableMmaped(now); while (true) { long evictableSize = evictable.size(); long evictableMmappedSize = evictableMmapped.size(); if (evictableSize + evictableMmappedSize <= maxTotalSize) { return; } ShortCircuitReplica replica; if (evictableSize == 0) { replica = (ShortCircuitReplica) evictableMmapped .get(evictableMmapped.firstKey()); } else { replica = (ShortCircuitReplica) evictable.get(evictable.firstKey()); } if (LOG.isTraceEnabled()) { LOG.trace(this + ": trimEvictionMaps is purging " + replica + StringUtils.getStackTrace(Thread.currentThread())); } purge(replica); } }

Target:
private void trimEvictionMaps() { long now = Time.monotonicNow(); demoteOldEvictableMmaped(now); while (evictable.size() + evictableMmapped.size() > maxTotalSize) { ShortCircuitReplica replica; if (evictable.isEmpty()) { replica = (ShortCircuitReplica) evictableMmapped .get(evictableMmapped.firstKey()); } else { replica = (ShortCircuitReplica) evictable.get(evictable.firstKey()); } if (LOG.isTraceEnabled()) { LOG.trace(this + ": trimEvictionMaps is purging " + replica + StringUtils.getStackTrace(Thread.currentThread())); } purge(replica); } }
Source:
public List<Itinerary> filter(List<Itinerary> itineraries) { List<Itinerary> reminding = remindingItineraries(itineraries); List<Itinerary> filtered = delegate.filter(reminding); for (Itinerary it : reminding) { if(!filtered.contains(it)) { markItineraryAsDeleted(it); } } return itineraries; }

Target:
public List<Itinerary> filter(List<Itinerary> itineraries) { List<Itinerary> previouslyUnfiltered = remindingItineraries(itineraries); List<Itinerary> filtered = delegate.filter(previouslyUnfiltered); for (Itinerary it : previouslyUnfiltered) { if(!filtered.contains(it)) { markItineraryAsDeleted(it); } } return itineraries; }
Source:
public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); String regexp = REGEXP_HTTP_CHANGE_ID; List<CommentLinkInfo> list = new ArrayList<CommentLinkInfo>(); list.add(new CommentLinkInfo("StandardHtmlLinks", HTTP_URL_PATTERN, "", "")); Set<String> subsections = config.getSubsections(COMMENTLINK); for (String subsection : subsections) { String match = config.getString("commentlink", subsection, "match"); String link = config.getString("commentlink", subsection, "link"); String html = config.getString("commentlink", subsection, "html"); checkArgument(!Strings.isNullOrEmpty(match), "invalid commentlink.%s.match", subsection); try { Pattern compiledPattern = Pattern.compile(match); list.add(new CommentLinkInfo(subsection, compiledPattern, link, html)); regexp += "|(" + match + ")"; } catch (RuntimeException err) { System.err.println("Ommiting commentlink " + subsection); } } this.commentLinks = Collections.unmodifiableList(list); try { allPattern = Pattern.compile(regexp); } catch (RuntimeException err) { System.err.println("Could not compile all commentlinks as a whole"); } }

Target:
public Linkifier(GitilesUrls urls, Config config) { this.urls = checkNotNull(urls, "urls"); List<CommentLinkInfo> list = new ArrayList<>(); list.add(new CommentLinkInfo("StandardHtmlLinks", HTTP_URL_PATTERN, "", "")); Set<String> subsections = config.getSubsections(COMMENTLINK); List<String> patterns = new ArrayList<>(); patterns.add(HTTP_URL_PATTERN.pattern()); patterns.add(CHANGE_ID_PATTERN.pattern()); for (String subsection : subsections) { String match = config.getString("commentlink", subsection, "match"); String link = config.getString("commentlink", subsection, "link"); String html = config.getString("commentlink", subsection, "html"); checkArgument(!Strings.isNullOrEmpty(match), "invalid commentlink.%s.match", subsection); Pattern compiledPattern = Pattern.compile(match); list.add(new CommentLinkInfo(subsection, compiledPattern, link, html)); patterns.add(compiledPattern.pattern()); } this.commentLinks = Collections.unmodifiableList(list); allPattern = Pattern.compile(Joiner.on('|').join(patterns)); }
Source:
public byte[] getCacheKey() { byte[] previousStopBytes = previousStop == null ? new byte[]{} : StringUtils.toUtf8(previousStop); byte[] orderingBytes = StringUtils.toUtf8(ordering.toString()); int totalLen = 2 + previousStopBytes.length + orderingBytes.length; return ByteBuffer.allocate(totalLen) .put(CACHE_TYPE_ID) .put(previousStopBytes) .put(STRING_SEPARATOR) .put(orderingBytes) .array(); }

Target:
public byte[] getCacheKey() { byte[] previousStopBytes = previousStop == null ? new byte[]{} : StringUtils.toUtf8(previousStop); byte[] orderingBytes = ordering.getCacheKey(); int totalLen = 2 + previousStopBytes.length + orderingBytes.length; return ByteBuffer.allocate(totalLen) .put(CACHE_TYPE_ID) .put(previousStopBytes) .put(STRING_SEPARATOR) .put(orderingBytes) .array(); }
Source:
public void setDirectUploadEnabled(boolean enableDirectUpload) { if (enableDirectUpload) { throw new UnsupportedOperationException("Direct upload not supported."); } }

Target:
public void setDirectUploadEnabled(boolean enableDirectUpload) { }
Source:
private static void assertCorrectSnapshots(DiskImage disk) { for (int i = 0; i < NUM_DISKS_OF_EACH_KIND; ++i) { assertEquals("Wrong snapshot " + i + " for disk ", disk.getId(), disk.getSnapshots().get(i).getImageId()); } }

Target:
private static void assertCorrectSnapshots(DiskImage disk) { for (int i = 0; i < NUM_DISKS_OF_EACH_KIND; ++i) { assertEquals("Wrong snapshot " + i + " for disk ", disk.getId(), disk.getSnapshots().get(i).getId()); } }
Source:
private Menu fillMenu(Menu m) { for (IAction action : getActions()) { IContributionItem item; String actionText = action.getText(); if (actionText == null || actionText.isEmpty()) { item = new Separator(); } else { item = new ActionContributionItem(action); } item.fill(m, -1); } return m; }

Target:
private Menu fillMenu(Menu m) { for (IContributionItem item : getActions()) { item.fill(m, -1); } return m; }
Source:
public void givenReportOnlyCspThenInfoAlertRaised() throws Exception { rule.setAlertThreshold(Plugin.AlertThreshold.MEDIUM); String[] headers = {HEADER_HTML, HEADER_CSP, HEADER_REPORT_ONLY}; HttpMessage msg = createHttpMessageWithHeaders(headers); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), is(1)); assertCSPAlertAttributes(alertsRaised.get(0), "ro.", Alert.RISK_INFO); }

Target:
public void givenReportOnlyCspThenInfoAlertRaised() throws Exception { rule.setAlertThreshold(Plugin.AlertThreshold.MEDIUM); HttpMessage msg = createHttpMessageWithHeaders(HEADER_HTML, HEADER_REPORT_ONLY); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), is(2)); assertCSPAlertAttributes(alertsRaised.get(0), "", Alert.RISK_LOW); assertCSPAlertAttributes(alertsRaised.get(1), "ro.", Alert.RISK_INFO); }
Source:
public static JSONObject addBasicTypingModel(Collection col) { Models mm = col.getModels(); JSONObject m = mm.newModel("Basic (type in the answer)"); JSONObject fm = mm.newField("Front"); try { mm.addField(m, fm); } catch (ConfirmModSchemaException ignored) { } fm = mm.newField("Back"); try { mm.addField(m, fm); } catch (ConfirmModSchemaException ignored) { } JSONObject t = mm.newTemplate("Card 1"); try { t.put("qfmt", "{{"+"Front"+"}}\n\n{{type:"+"Back"+"}}"); t.put("afmt", "{{"+"Front"+"}}\n\n<hr id=answer>\n\n{{type:"+"Back"+"}}"); } catch (JSONException e) { throw new RuntimeException(e); } try { mm.addTemplate(m, t); } catch (ConfirmModSchemaException ignored) { } mm.add(m); return m; }

Target:
public static JSONObject addBasicTypingModel(Collection col) { JSONObject m = _newBasicTypingModel(col); col.getModels().add(m); return m; }
Source:
public void flush(final String value) { if (Objects.equals(value, originalValue)) { return; } final int rowIndex = context.getRowIndex(); final int columnIndex = context.getColumnIndex(); if (value == null || value.trim().isEmpty()) { sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), hasNoValueCommand.apply(new GridCellTuple(rowIndex, columnIndex, gridWidget))); } else { sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), hasValueCommand.apply(new GridCellValueTuple<>(rowIndex, columnIndex, gridWidget, new BaseGridCellValue<>(value)))); } }

Target:
public void flush(final String value) { widget.getCodeEditor().ifPresent(c -> c.dispose()); if (Objects.equals(value, originalValue)) { return; } final int rowIndex = context.getRowIndex(); final int columnIndex = context.getColumnIndex(); if (StringUtils.isEmpty(value)) { sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), hasNoValueCommand.apply(new GridCellTuple(rowIndex, columnIndex, gridWidget))); } else { sessionCommandManager.execute((AbstractCanvasHandler) sessionManager.getCurrentSession().getCanvasHandler(), hasValueCommand.apply(new GridCellValueTuple<>(rowIndex, columnIndex, gridWidget, new BaseGridCellValue<>(value)))); } }
Source:
default PriorityQueue<T> toPriorityQueue() { final Comparator<T> comparator; if (this instanceof PriorityQueue<?>) { return (PriorityQueue<T>) this; } else if (this instanceof Ordered<?>) { comparator = ((Ordered<T>) this).comparator(); } else { comparator = (Comparator<T> & Serializable) (o1, o2) -> ((Comparable<T>) o1).compareTo(o2); } return toPriorityQueue(comparator); }

Target:
default PriorityQueue<T> toPriorityQueue() { if (this instanceof PriorityQueue<?>) { return (PriorityQueue<T>) this; } else { final Comparator<T> comparator = (this instanceof Ordered<?>) ? ((Ordered<T>) this).comparator() : (Comparator<T> & Serializable) (o1, o2) -> ((Comparable<T>) o1).compareTo(o2); return toPriorityQueue(comparator); } }
Source:
public List<AuditLogEvent> getAuditLogEvents() throws SQLException { List<AuditLogEvent> auditLogEvents = new ArrayList<>(); Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { connection = ds.getConnection(); ps = connection.prepareStatement("" + "SELECT al.audit_log_id, al.log_type_name, " + " em_down.event_down_name," + " al.user_id, al.user_name, " + " al.vm_id, al.vm_name, al.vm_template_id, al.vm_template_name, " + " al.vds_id, al.vds_name, al.storage_pool_id, al.storage_pool_name, " + " al.storage_domain_id, al.storage_domain_name, " + " al.log_time, al.severity, al.message " + "FROM audit_log al " + "LEFT JOIN event_map em_down ON al.log_type_name = em_down.event_down_name " + "WHERE al.processed = FALSE ;"); rs = ps.executeQuery(); while (rs.next()) { auditLogEvents.add(extractAuditLogEvent(rs)); } } finally { DbUtils.closeQuietly(rs, ps, connection); } if (log.isDebugEnabled()) { log.debug(String.format("%d unprocessed events read from audit_log database table.", auditLogEvents.size())); for (int i = 0; i < auditLogEvents.size(); i++) { log.debug(String.format("event %d => %s", i, auditLogEvents.get(i).toString())); } } return auditLogEvents; }

Target:
public List<AuditLogEvent> getAuditLogEvents() throws SQLException { List<AuditLogEvent> auditLogEvents = new ArrayList<>(); HashSet<String> downEvents = new HashSet<>(eventMap.values()); Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { connection = ds.getConnection(); ps = connection.prepareStatement("" + "SELECT al.audit_log_id, al.log_type_name, " + " al.user_id, al.user_name, " + " al.vm_id, al.vm_name, al.vm_template_id, al.vm_template_name, " + " al.vds_id, al.vds_name, al.storage_pool_id, al.storage_pool_name, " + " al.storage_domain_id, al.storage_domain_name, " + " al.log_time, al.severity, al.message " + "FROM audit_log al " + "WHERE al.processed = FALSE ;"); rs = ps.executeQuery(); while (rs.next()) { auditLogEvents.add(extractAuditLogEvent(rs, downEvents)); } } finally { DbUtils.closeQuietly(rs, ps, connection); } if (log.isDebugEnabled()) { log.debug(String.format("%d unprocessed events read from audit_log database table.", auditLogEvents.size())); for (int i = 0; i < auditLogEvents.size(); i++) { log.debug(String.format("event %d => %s", i, auditLogEvents.get(i).toString())); } } return auditLogEvents; }
Source:
private CorfuRuntime(@Nonnull CorfuRuntimeParameters parameters) { this.parameters = parameters; bootstrapLayoutServers = parameters.getLayoutServers().stream() .map(NodeLocator::toString) .collect(Collectors.toList()); layoutServers = new ArrayList<>(bootstrapLayoutServers); clusterId = parameters.getClusterId(); guidGenerator = new SnowflakeGuidGenerator(this.hashCode()); nettyEventLoop = parameters.nettyEventLoop == null ? getNewEventLoopGroup() : parameters.nettyEventLoop; nodeRouterPool = new NodeRouterPool(getRouterFunction); log.info("Corfu runtime version initialized.", getVersionString()); }

Target:
private CorfuRuntime(@Nonnull CorfuRuntimeParameters parameters) { this.parameters = parameters; bootstrapLayoutServers = parameters.getLayoutServers().stream() .map(NodeLocator::toString) .collect(Collectors.toList()); layoutServers = new ArrayList<>(bootstrapLayoutServers); clusterId = parameters.getClusterId(); guidGenerator = new SnowflakeGuidGenerator(System.identityHashCode(this)); nettyEventLoop = parameters.nettyEventLoop == null ? getNewEventLoopGroup() : parameters.nettyEventLoop; nodeRouterPool = new NodeRouterPool(getRouterFunction); log.info("Corfu runtime version initialized.", getVersionString()); }
Source:
public boolean disableSegments(String dataSource, Collection<String> segmentIds) { if (segmentIds.isEmpty()) { return false; } try { connector.getDBI().withHandle(handle -> { Batch batch = handle.createBatch(); segmentIds .forEach(segmentId -> batch.add( StringUtils.format( "UPDATE %s SET used=false WHERE id = '%s'", getSegmentsTable(), segmentId ) )); return batch.execute(); }); } catch (Exception e) { log.error(e, e.toString()); return false; } return true; }

Target:
public long disableSegments(String dataSource, Collection<String> segmentIds) { if (segmentIds.isEmpty()) { return 0; } final long[] result = new long[1]; try { connector.getDBI().withHandle(handle -> { Batch batch = handle.createBatch(); segmentIds .forEach(segmentId -> batch.add( StringUtils.format( "UPDATE %s SET used=false WHERE datasource = '%s' AND id = '%s' ", getSegmentsTable(), dataSource, segmentId ) )); final int[] resultArr = batch.execute(); result[0] = Arrays.stream(resultArr).filter(x -> x > 0).count(); return result[0]; }); } catch (Exception e) { throw new RuntimeException(e); } return result[0]; }
Source:
public boolean unsubscribe(PropertyChangeListener listener) { if (!subscribers.contains(listener)) { LOGGER.warn("The listener does not exist in the subscriber list."); return false; } subscribers.remove(listener); return true; }

Target:
public boolean unsubscribe(PropertyChangeListener listener) { if (!subscribers.contains(listener)) { LOGGER.warn(formatWarning("The listener does not exist in the subscriber list.")); return false; } subscribers.remove(listener); if (subscribers.size() <= 0) { subscribers = null; } return true; }
Source:
public byte convert(byte data) { try { BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(data, null); GenericRecord record = reader.read(null, binaryDecoder); return decodeRecordToJson(record); } catch (IOException exception) { throw new ConvertingException("Could not convert avro message to json. Message invalid with schema.", exception); } }

Target:
public byte convert(byte data) { try { BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(data, null); GenericRecord record = reader.read(null, binaryDecoder); return decodeRecordToJson(record); } catch (IOException exception) { throw new ConvertingException("Could not convert avro message to json. Invalid Message.", exception); } }
Source:
public ArrayInterface setFloat(int index, float value) { return setObject(index, value); }

Target:
public Array setFloat(int index, float value) { return setObject(index, value); }
Source:
public void moveMigratedFiles( File migrationDir, File storeDir, String versionToUpgradeFrom, String versionToMigrateTo ) throws IOException { if ( nativeLabelScanStoreMigrated ) { File nativeLabelIndex = new File( migrationDir, NativeLabelScanStore.FILE_NAME ); fileSystem.moveToDirectory( nativeLabelIndex, storeDir ); deleteLuceneLabelIndex( getLuceneStoreDirectory( storeDir ) ); } }

Target:
public void moveMigratedFiles( File migrationDir, File storeDir, String versionToUpgradeFrom, String versionToMigrateTo ) throws IOException { if ( nativeLabelScanStoreMigrated ) { File nativeLabelIndex = new File( migrationDir, NativeLabelScanStore.FILE_NAME ); moveNativeIndexFile( storeDir, nativeLabelIndex ); deleteLuceneLabelIndex( getLuceneStoreDirectory( storeDir ) ); } }
Source:
protected void contentChanged(ITmfTreeViewerEntry rootEntry) { TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); Set<Long> ids = (Set<Long>) ctx.getData(getClass() + CHECKED_ELEMENTS); Collection<ITmfTreeViewerEntry> prevModel = getCheckedViewerEntries(); boolean different = true; if (ids != null && rootEntry != null) { different = prevModel.size() != ids.size(); if (!different) { for (ITmfTreeViewerEntry prevItem : prevModel) { if (prevItem instanceof TmfGenericTreeEntry) { TmfGenericTreeEntry tmfGenericTreeEntry = (TmfGenericTreeEntry) prevItem; if (!ids.contains(tmfGenericTreeEntry.getModel().getId())) { different = true; } } } } List<ITmfTreeViewerEntry> checkedElements = new ArrayList<>(); checkEntries(ids, rootEntry, checkedElements); fCheckboxTree.setCheckedElements(checkedElements.toArray()); } if (fChartViewer != null && different) { fChartViewer.handleCheckStateChangedEvent(getCheckedViewerEntries()); } getTreeViewer().refresh(); }

Target:
protected void contentChanged(ITmfTreeViewerEntry rootEntry) { TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); Set<Long> ids = (Set<Long>) ctx.getData(getClass() + CHECKED_ELEMENTS); if (ids != null && rootEntry != null) { List<ITmfTreeViewerEntry> checkedElements = new ArrayList<>(); checkEntries(ids, rootEntry, checkedElements); fCheckboxTree.setCheckedElements(checkedElements.toArray()); } if (fChartViewer != null) { fChartViewer.handleCheckStateChangedEvent(getCheckedViewerEntries()); } getTreeViewer().refresh(); }
Source:
public synchronized Patient create(DocumentReference creator) { try { XWikiContext context = this.xcontextProvider.get(); Patient patient = super.create(creator); XWikiDocument doc = patient.getXDocument(); doc.getXObject(Patient.CLASS_REFERENCE).setLongValue("identifier", Integer.parseInt(patient.getDocumentReference().getName().replaceAll("\\D++", ""))); if (creator != null) { doc.setCreatorReference(creator); doc.setAuthorReference(creator); doc.setContentAuthorReference(creator); } context.getWiki().saveDocument(doc, context); for (PatientRecordInitializer initializer : this.initializers.get()) { try { initializer.initialize(patient); } catch (Exception ex) { this.logger.warn("Patient initializer failed: {}", initializer.getClass().getName(), ex.getMessage(), ex); } } return patient; } catch (Exception ex) { this.logger.warn("Failed to create patient: {}", ex.getMessage(), ex); return null; } }

Target:
public synchronized Patient create(DocumentReference creator) { try { XWikiContext context = this.xcontextProvider.get(); Patient patient = super.create(creator); XWikiDocument doc = patient.getXDocument(); doc.getXObject(Patient.CLASS_REFERENCE).setLongValue("identifier", Integer.parseInt(patient.getId().replaceAll("\\D++", ""))); if (creator != null) { doc.setCreatorReference(creator); doc.setAuthorReference(creator); doc.setContentAuthorReference(creator); } context.getWiki().saveDocument(doc, context); for (PatientRecordInitializer initializer : this.initializers.get()) { try { initializer.initialize(patient); } catch (Exception ex) { this.logger.warn("Patient initializer failed: {}", initializer.getClass().getName(), ex.getMessage(), ex); } } return patient; } catch (Exception ex) { this.logger.warn("Failed to create patient: {}", ex.getMessage(), ex); return null; } }
Source:
private void processDiagnostics(ExtendedPublishDiagnosticsParams diagnosticsMessage) { final Path path = Path.valueOf(diagnosticsMessage.getParams().getUri()); final Optional<Node> resource = tree.getNodeStorage() .getAll() .stream() .filter( node -> node instanceof ResourceNode && ((ResourceNode) node).getData().isFile()) .filter(node -> path.equals(((ResourceNode) node).getData().asFile().getLocation())) .findAny(); resource.ifPresent(node -> setHasError((ResourceNode) node)); EditorPartPresenter openedEditor = editorAgent.getOpenedEditor(path); if (openedEditor == null) { return; } if (openedEditor instanceof TextEditor) { TextEditorConfiguration editorConfiguration = ((TextEditor) openedEditor).getConfiguration(); AnnotationModel annotationModel = editorConfiguration.getAnnotationModel(); if (annotationModel != null && annotationModel instanceof DiagnosticCollector) { DiagnosticCollector collector = (DiagnosticCollector) annotationModel; String languageServerId = diagnosticsMessage.getLanguageServerId(); collector.beginReporting(languageServerId); try { for (Diagnostic diagnostic : diagnosticsMessage.getParams().getDiagnostics()) { collector.acceptDiagnostic(languageServerId, diagnostic); } } finally { collector.endReporting(languageServerId); } } } }

Target:
public void processDiagnostics(ExtendedPublishDiagnosticsParams diagnosticsMessage) { final Path path = Path.valueOf(diagnosticsMessage.getParams().getUri()); findVisibleResource(path).ifPresent(this::setHasError); EditorPartPresenter openedEditor = editorAgent.getOpenedEditor(path); if (openedEditor == null) { return; } if (openedEditor instanceof TextEditor) { TextEditorConfiguration editorConfiguration = ((TextEditor) openedEditor).getConfiguration(); AnnotationModel annotationModel = editorConfiguration.getAnnotationModel(); if (annotationModel != null && annotationModel instanceof DiagnosticCollector) { DiagnosticCollector collector = (DiagnosticCollector) annotationModel; String languageServerId = diagnosticsMessage.getLanguageServerId(); collector.beginReporting(languageServerId); try { for (Diagnostic diagnostic : diagnosticsMessage.getParams().getDiagnostics()) { collector.acceptDiagnostic(languageServerId, diagnostic); } } finally { collector.endReporting(languageServerId); } } } }
Source:
private SiteInit createSiteInit() { final ConsoleUI ui = getConsoleUI(); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule(standalone)); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); List<String> plugins = Objects.firstNonNull(getInstallPlugins(), Lists.<String> newArrayList()); bind(new TypeLiteral<List<String>>() {}).annotatedWith( InstallPlugins.class).toInstance(plugins); bind(SecureStore.class).toProvider(SecureStorePrvider.class); } }); m.add(new GerritServerConfigModule()); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }

Target:
private SiteInit createSiteInit() { final ConsoleUI ui = getConsoleUI(); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule(standalone)); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); List<String> plugins = Objects.firstNonNull(getInstallPlugins(), Lists.<String> newArrayList()); bind(new TypeLiteral<List<String>>() {}).annotatedWith( InstallPlugins.class).toInstance(plugins); bind(SecureStore.class).toProvider(SecureStoreProvider.class).in( Scopes.SINGLETON); } }); m.add(new GerritServerConfigModule()); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }
Source:
public void afterTaskInputVariableChangedEvent(TaskEvent event, Map<String, Object> variables) { if (variables == null || variables.isEmpty()) { return; } Task task = event.getTask(); List<TaskVariableImpl> taskVariables = indexVariables(task, variables, VariableType.INPUT); AuditTaskImpl auditTaskImpl = createAuditTask(task, event.getEventDate()); sendMessage(new AuditTaskData(auditTaskImpl, null, taskVariables, null), 2); }

Target:
public void afterTaskInputVariableChangedEvent(TaskEvent event, Map<String, Object> variables) { if (variables == null || variables.isEmpty()) { return; } Task task = event.getTask(); List<TaskVariableImpl> taskVariables = indexVariables(task, variables, VariableType.INPUT); sendMessage(new AuditTaskData(null, null, taskVariables, null), 2); }
Source:
public void decorate(Object element, IDecoration decoration) { ImageDescriptor priorityOverlay = getPriorityImageDescriptor(element); if (priorityOverlay != null) { decoration.addOverlay(priorityOverlay, IDecoration.BOTTOM_LEFT); } if (element instanceof ITask) { ITask task = (ITask) element; if (!task.isCompleted() && (TasksUiPlugin.getTaskActivityManager().isDueToday(task) || TasksUiPlugin.getTaskActivityManager() .isOverdue(task))) { decoration.addOverlay(CommonImages.OVERLAY_DATE_OVERDUE, IDecoration.TOP_RIGHT); } else if (!task.isCompleted() && task.getDueDate() != null) { decoration.addOverlay(CommonImages.OVERLAY_DATE_DUE, IDecoration.TOP_RIGHT); } else if (hasNotes(task)) { decoration.addOverlay(TasksUiImages.NOTES, IDecoration.BOTTOM_RIGHT); } } else if (element instanceof ITaskRepositoryElement) { ITaskRepositoryElement repositoryElement = (ITaskRepositoryElement) element; String repositoryUrl = repositoryElement.getRepositoryUrl(); TaskRepository taskRepository = TasksUi.getRepositoryManager().getRepository( repositoryElement.getConnectorKind(), repositoryUrl); if (taskRepository != null) { decoration.addSuffix(" [" + taskRepository.getRepositoryLabel() + "]"); } } else if (element instanceof TaskRepository) { ImageDescriptor overlay = TasksUiPlugin.getDefault().getOverlayIcon( ((TaskRepository) element).getConnectorKind()); if (overlay != null) { decoration.addOverlay(overlay, IDecoration.BOTTOM_RIGHT); } } }

Target:
public void decorate(Object element, IDecoration decoration) { ImageDescriptor priorityOverlay = getPriorityImageDescriptor(element); if (priorityOverlay != null) { decoration.addOverlay(priorityOverlay, IDecoration.BOTTOM_LEFT); } if (element instanceof ITask) { ITask task = (ITask) element; if (!task.isCompleted() && (TasksUiPlugin.getTaskActivityManager().isDueToday(task) || TasksUiPlugin.getTaskActivityManager() .isOverdue(task))) { decoration.addOverlay(CommonImages.OVERLAY_DATE_OVERDUE, IDecoration.TOP_RIGHT); } else if (!task.isCompleted() && task.getDueDate() != null) { decoration.addOverlay(CommonImages.OVERLAY_DATE_DUE, IDecoration.TOP_RIGHT); } if (hasNotes(task)) { decoration.addOverlay(TasksUiImages.NOTES, IDecoration.BOTTOM_RIGHT); } } else if (element instanceof ITaskRepositoryElement) { ITaskRepositoryElement repositoryElement = (ITaskRepositoryElement) element; String repositoryUrl = repositoryElement.getRepositoryUrl(); TaskRepository taskRepository = TasksUi.getRepositoryManager().getRepository( repositoryElement.getConnectorKind(), repositoryUrl); if (taskRepository != null) { decoration.addSuffix(" [" + taskRepository.getRepositoryLabel() + "]"); } } else if (element instanceof TaskRepository) { ImageDescriptor overlay = TasksUiPlugin.getDefault().getOverlayIcon( ((TaskRepository) element).getConnectorKind()); if (overlay != null) { decoration.addOverlay(overlay, IDecoration.BOTTOM_RIGHT); } } }
Source:
private synchronized LoadingCache<List<String>,WeightedRandomCollection> getCache( VolumeChooserEnvironment env) { if (choiceCache == null) { String propertyValue = env.getContext().getConfiguration().getCustom(RECOMPUTE_INTERVAL); long computationCacheDuration = StringUtils.isNotBlank(propertyValue) ? Long.parseLong(propertyValue) : defaultComputationCacheDuration; choiceCache = CacheBuilder.newBuilder() .expireAfterWrite(computationCacheDuration, TimeUnit.MILLISECONDS) .build(new CacheLoader<List<String>,WeightedRandomCollection>() { @Override public WeightedRandomCollection load(List<String> key) { return new WeightedRandomCollection(key, env, random); } }); } return choiceCache; }

Target:
private synchronized LoadingCache<List<String>,WeightedRandomCollection> getCache( VolumeChooserEnvironment env) { if (choiceCache == null) { String propertyValue = env.getServiceEnv().getConfiguration().getCustom(RECOMPUTE_INTERVAL); long computationCacheDuration = StringUtils.isNotBlank(propertyValue) ? Long.parseLong(propertyValue) : defaultComputationCacheDuration; choiceCache = CacheBuilder.newBuilder() .expireAfterWrite(computationCacheDuration, TimeUnit.MILLISECONDS) .build(new CacheLoader<List<String>,WeightedRandomCollection>() { @Override public WeightedRandomCollection load(List<String> key) { return new WeightedRandomCollection(key, env, random); } }); } return choiceCache; }
Source:
public void startWatching(LockWatchRequest locksToWatch) { RangeSet<LockDescriptor> newRanges = newRangesToWatch(locksToWatch.ranges()); if (newRanges.isEmpty()) { return; } addToWatches(newRanges); logOpenLocks(newRanges); logLockWatchEvent(locksToWatch); }

Target:
public void startWatching(LockWatchRequest locksToWatch) { addToWatches(locksToWatch); logOpenLocks(locksToWatch); logLockWatchEvent(locksToWatch); }
Source:
public ItalyProviderLiveTest() { super(new ItalyProvider("<LINK_0>", secretProperty("navitia.authorization"))); }

Target:
public ItalyProviderLiveTest() { super(new ItalyProvider("<LINK_1>", secretProperty("navitia.authorization"))); }
Source:
protected void doGetText(HttpServletRequest req, HttpServletResponse res) throws IOException { GitilesView view = ViewFilter.getView(req); Repository repo = ServletUtils.getRepository(req); ObjectReader reader = repo.newObjectReader(); try { ObjectLoader loader = reader.open(view.getRevision().getId()); if (loader.getType() != OBJ_COMMIT) { res.setStatus(SC_NOT_FOUND); } else { res.setHeader(PathServlet.MODE_HEADER, "160000"); try (Writer writer = startRenderText(req, res); OutputStream out = BaseEncoding.base64().encodingStream(writer)) { loader.copyTo(out); } } } finally { reader.release(); } }

Target:
protected void doGetText(HttpServletRequest req, HttpServletResponse res) throws IOException { GitilesView view = ViewFilter.getView(req); Repository repo = ServletUtils.getRepository(req); ObjectReader reader = repo.newObjectReader(); try { ObjectLoader loader = reader.open(view.getRevision().getId()); if (loader.getType() != OBJ_COMMIT) { res.setStatus(SC_NOT_FOUND); } else { PathServlet.setTypeHeader(res, loader.getType()); try (Writer writer = startRenderText(req, res); OutputStream out = BaseEncoding.base64().encodingStream(writer)) { loader.copyTo(out); } } } finally { reader.release(); } }
Source:
public static void main(String[] args) { UploadDirectoryToCDN uploadDirToCDN = new UploadDirectoryToCDN(); try { uploadDirToCDN.init(args); uploadDirToCDN.uploadDirectory(args[2], args[3]); uploadDirToCDN.enableCdnContainer(args[3]); } catch (Exception e) { e.printStackTrace(); } finally { uploadDirToCDN.close(); } }

Target:
public static void main(String[] args) { UploadDirectoryToCDN uploadDirToCDN = new UploadDirectoryToCDN(args[0], args[1]); try { uploadDirToCDN.uploadDirectory(args[2], args[3]); uploadDirToCDN.enableCdnContainer(args[3]); } catch (Exception e) { e.printStackTrace(); } finally { uploadDirToCDN.close(); } }
Source:
public boolean equals(@Nullable Object obj) { if (!(obj instanceof DataDrivenValueEventName)) { return false; } return true; }

Target:
public boolean equals(@Nullable Object obj) { if (!(obj instanceof DataDrivenValueEventName)) { return false; } return super.equals(obj); }
Source:
public void transformResource(final ResourceTransformationContext ctx, final PathAddress address, final Resource original) throws OperationFailedException { final DiscardPolicy discardPolicy = determineDiscardPolicy(ctx, address); switch (discardPolicy) { case REJECT_AND_WARN: ctx.getLogger().logRejectedResourceWarning(address, null); return; case DISCARD_AND_WARN: ctx.getLogger().logDiscardedResourceWarning(address); case SILENT: ResourceTransformer.DISCARD.transformResource(ctx, address, original); return; } final Iterator<TransformationRule> iterator = rules.iterator(); final TransformationRule.ChainedResourceContext context = new TransformationRule.ChainedResourceContext(ctx) { @Override void invokeNext(final Resource resource) throws OperationFailedException { if(iterator.hasNext()) { final TransformationRule next = iterator.next(); next.transformResource(resource, address, this); } else { resourceTransformer.transformResource(ctx, address, resource); } } }; final TransformationRule rule = new AttributeTransformationRule(attributeTransformations); rule.transformResource(original, address, context); }

Target:
public void transformResource(final ResourceTransformationContext ctx, final PathAddress address, final Resource original) throws OperationFailedException { final DiscardPolicy discardPolicy = determineDiscardPolicy(ctx, address); switch (discardPolicy) { case REJECT_AND_WARN: ctx.getLogger().logRejectedResourceWarning(address, null); return; case DISCARD_AND_WARN: ctx.getLogger().logDiscardedResourceWarning(address, ctx.getTarget().getHostName()); case SILENT: ResourceTransformer.DISCARD.transformResource(ctx, address, original); return; } final Iterator<TransformationRule> iterator = rules.iterator(); final TransformationRule.ChainedResourceContext context = new TransformationRule.ChainedResourceContext(ctx) { @Override void invokeNext(final Resource resource) throws OperationFailedException { if(iterator.hasNext()) { final TransformationRule next = iterator.next(); next.transformResource(resource, address, this); } else { resourceTransformer.transformResource(ctx, address, resource); } } }; final TransformationRule rule = new AttributeTransformationRule(attributeTransformations); rule.transformResource(original, address, context); }
Source:
public Date unmarshal(@Nullable Object o) { if (o instanceof String) { try { return DEFAULT_FORMAT.parse((String) o); } catch (ParseException e) { return null; } } return null; }

Target:
public Instant unmarshal(@Nullable Object o) { if (o instanceof String) { try { return Instant.from(FORMATTER.parse((String) o)); } catch(DateTimeParseException ignored) { return null; } } return null; }
Source:
private <T> DtoProvider<T> getDtoProvider(Class<T> dtoInterface) { DtoProvider<?> dtoProvider = dtoInterface2Providers.get(dtoInterface); if (dtoProvider == null) { if (dtoInterface.isAnnotationPresent(DTO.class)) { throw new IllegalArgumentException("Implementation for DTO type " + dtoInterface + " isn't found."); } else { throw new IllegalArgumentException("Is not a DTO type " + dtoInterface); } } return (DtoProvider<T>)dtoProvider; }

Target:
private <T> DtoProvider<T> getDtoProvider(Class<T> dtoInterface) { DtoProvider<?> dtoProvider = dtoInterface2Providers.get(dtoInterface); if (dtoProvider == null) { if (!dtoInterface.isInterface()) { throw new IllegalArgumentException(format("Only interfaces can be DTO, but %s is not", dtoInterface)); } if (hasDtoAnnotation(dtoInterface)) { throw new IllegalArgumentException(format("Provider of implementation for DTO type %s isn't found", dtoInterface)); } else { throw new IllegalArgumentException(dtoInterface + " is not a DTO type"); } } return (DtoProvider<T>)dtoProvider; }