auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ReloadableRegistrationHandle<T> set(Key<T> key, Provider<T> impl, String pluginName) { NamedProvider<T> old = ref.get(); final NamedProvider<T> item = new NamedProvider<T>(impl, pluginName); if (replaceable) { ref.compareAndSet(old, item); } else { while (!ref.compareAndSet(null, item)) { if (old != null) { throw new ProvisionException(String.format( "%s already provided by %s, ignoring plugin %s", this.key.getTypeLiteral(), old.pluginName, pluginName)); } } } return new ReloadableHandle(key, item, old); }

Target:
public ReloadableRegistrationHandle<T> set(Key<T> key, Provider<T> impl, String pluginName) { final NamedProvider<T> item = new NamedProvider<T>(impl, pluginName); while (!ref.compareAndSet(null, item)) { NamedProvider<T> old = ref.get(); if (old != null) { throw new ProvisionException(String.format( "%s already provided by %s, ignoring plugin %s", this.key.getTypeLiteral(), old.pluginName, pluginName)); } } return new ReloadableHandle(key, item); }
Source:
private Stream<Metacard> loadFile(File file, Function<? super Map, Metacard> mapper) { if (!file.exists()) { LOGGER.debug("Could not locate {}", file.getName()); return Stream.empty(); } String payload = getFileContent(file); if (payload == null) { LOGGER.debug("Problem reading {}", file.getName()); return Stream.empty(); } try { return Stream.of(Boon.fromJson(payload)) .map(List.class::cast) .flatMap(List::stream) .filter(Map.class::isInstance) .map(Map.class::cast) .map(mapper) .filter(Objects::nonNull) .collect(Collectors.toList()) .stream(); } catch (ClassCastException e) { LOGGER.warn( "Could not load forms configuration in {}, JSON should be a list of maps", file.getName()); return Stream.empty(); } }

Target:
private Stream<Metacard> loadFile(File file, Function<? super Map, Metacard> mapper) { if (!file.exists()) { LOGGER.debug("Could not locate {}", file.getName()); return Stream.empty(); } String payload = getFileContent(file); if (payload == null) { LOGGER.debug("Problem reading {}", file.getName()); return Stream.empty(); } Object configObject = Boon.fromJson(payload); if (!List.class.isInstance(configObject)) { LOGGER.warn( "Could not load forms configuration in {}, JSON should be a list of maps", file.getName()); return Stream.empty(); } List<Object> configs = (List) configObject; return configs .stream() .peek(obj -> loggingConsumerFactory(file).accept(obj)) .filter(Map.class::isInstance) .map(Map.class::cast) .map(mapper) .filter(Objects::nonNull); }
Source:
public void loadHacoMap() { String clientDirPath = "."; DfHacoMapFile hacoMapFile = new DfHacoMapFile(() -> DBFluteSystem.currentLocalDateTime()); try { List<DfHacoMapPiece> pieceList = hacoMapFile.readPieceList(clientDirPath); OptionalThing<DfHacoMapPickup> optPickup = hacoMapFile.readPickup(clientDirPath); _hacoMapPickup = hacoMapFile.merge(optPickup, pieceList); } catch (RuntimeException e){ final ExceptionMessageBuilder br = new ExceptionMessageBuilder(); br.addNotice("Failed to load haco-map."); br.addItem("Exception"); br.addElement(e.getClass().getName()); br.addElement(e.getMessage()); final String msg = br.buildExceptionMessage(); throw new IllegalStateException(msg, e); } }

Target:
public void loadHacoMap() { String clientDirPath = "."; DfHacoMapFile hacoMapFile = new DfHacoMapFile(() -> DBFluteSystem.currentLocalDateTime()); try { List<DfHacoMapPiece> pieceList = hacoMapFile.readPieceList(clientDirPath); OptionalThing<DfHacoMapPickup> optPickup = hacoMapFile.readPickup(clientDirPath); _hacoMapPickup = hacoMapFile.merge(optPickup, pieceList); } catch (RuntimeException e) { final ExceptionMessageBuilder br = new ExceptionMessageBuilder(); br.addNotice("Failed to load haco-map."); br.addItem("File Path"); br.addElement(clientDirPath); final String msg = br.buildExceptionMessage(); throw new IllegalStateException(msg, e); } }
Source:
public void onModified(final ContentletPublishEvent<Persona> contentletPublishEvent) { try { final Optional<Versionable> versionable = APILocator.getVersionableAPI() .findPreviousVersion(contentletPublishEvent.getContentlet().getIdentifier()); if (versionable.isPresent()) { final Contentlet previousPersonaContent = APILocator.getContentletAPI().find (versionable.get().getInode(), APILocator.systemUser(), false); if (null != previousPersonaContent) { final String currentKeyTag = contentletPublishEvent.getContentlet().getKeyTag(); final String previousKeyTag = previousPersonaContent.getStringProperty(PersonaAPI.KEY_TAG_FIELD); if (UtilMethods.isSet(currentKeyTag) && UtilMethods.isSet(previousKeyTag) && !currentKeyTag.equals(previousKeyTag)) { APILocator.getMultiTreeAPI().updatePersonalization ( this.wrapPersonaScheme(previousKeyTag), this.wrapPersonaScheme(currentKeyTag)); } } } } catch (Exception e) { Logger.error(this, e.getMessage(), e); } }

Target:
public void onModified(final ContentletPublishEvent<Persona> contentletPublishEvent) { try { if (null != contentletPublishEvent.getContentlet() && contentletPublishEvent.getContentlet().isLive()) { final Optional<Versionable> versionable = APILocator.getVersionableAPI() .findPreviousVersion(contentletPublishEvent.getContentlet().getIdentifier()); if (versionable.isPresent()) { final Contentlet previousPersonaContent = APILocator.getContentletAPI().find (versionable.get().getInode(), APILocator.systemUser(), false); if (null != previousPersonaContent) { final String currentKeyTag = contentletPublishEvent.getContentlet().getKeyTag(); final String previousKeyTag = previousPersonaContent.getStringProperty(PersonaAPI.KEY_TAG_FIELD); if (UtilMethods.isSet(currentKeyTag) && UtilMethods.isSet(previousKeyTag) && !currentKeyTag.equals(previousKeyTag)) { APILocator.getMultiTreeAPI().updatePersonalization( this.wrapPersonaScheme(previousKeyTag), this.wrapPersonaScheme(currentKeyTag)); } } } } } catch (Exception e) { Logger.error(this, e.getMessage(), e); } }
Source:
public boolean onMediaButtonEvent(Intent mediaButtonIntent) { setCurrentControllerInfo(); boolean result = Callback.this.onMediaButtonEvent(mediaButtonIntent); clearCurrentControllerInfo(); if (result) return true; else return super.onMediaButtonEvent(mediaButtonIntent); }

Target:
public boolean onMediaButtonEvent(Intent mediaButtonIntent) { setCurrentControllerInfo(); boolean result = Callback.this.onMediaButtonEvent(mediaButtonIntent); clearCurrentControllerInfo(); return result || super.onMediaButtonEvent(mediaButtonIntent); }
Source:
public TargetReference build() { Objects.requireNonNull( method ); Objects.requireNonNull( typeFactory ); if ( targetName == null ) { return null; } String targetNameTrimmed = targetName.trim(); if ( !targetName.equals( targetNameTrimmed ) && messager != null ) { messager.printMessage( method.getExecutable(), annotationMirror, targetAnnotationValue, Message.PROPERTYMAPPING_WHITESPACE_TRIMMED, targetName, targetNameTrimmed ); } String[] segments = targetNameTrimmed.split( "\\." ); Parameter parameter = method.getMappingTargetParameter(); boolean foundEntryMatch; Type resultType = typeBasedOnMethod( method.getResultType() ); String[] targetPropertyNames = segments; List<PropertyEntry> entries = getTargetEntries( resultType, targetPropertyNames ); foundEntryMatch = (entries.size() == targetPropertyNames.length); if ( !foundEntryMatch && segments.length > 1 && matchesSourceOrTargetParameter( segments[0], parameter, isReversed ) ) { targetPropertyNames = Arrays.copyOfRange( segments, 1, segments.length ); entries = getTargetEntries( resultType, targetPropertyNames ); foundEntryMatch = (entries.size() == targetPropertyNames.length); } if ( !foundEntryMatch && errorMessage != null && !isReversed ) { errorMessage.report( ); } return new TargetReference( parameter, entries, foundEntryMatch ); }

Target:
public TargetReference build() { Objects.requireNonNull( method ); Objects.requireNonNull( typeFactory ); Objects.requireNonNull( messager ); if ( targetName == null ) { return null; } String targetNameTrimmed = targetName.trim(); if ( !targetName.equals( targetNameTrimmed ) ) { messager.printMessage( method.getExecutable(), annotationMirror, targetAnnotationValue, Message.PROPERTYMAPPING_WHITESPACE_TRIMMED, targetName, targetNameTrimmed ); } String[] segments = targetNameTrimmed.split( "\\." ); Parameter parameter = method.getMappingTargetParameter(); boolean foundEntryMatch; Type resultType = typeBasedOnMethod( method.getResultType() ); String[] targetPropertyNames = segments; List<PropertyEntry> entries = getTargetEntries( resultType, targetPropertyNames ); foundEntryMatch = (entries.size() == targetPropertyNames.length); if ( !foundEntryMatch && segments.length > 1 && matchesSourceOrTargetParameter( segments[0], parameter, isReversed ) ) { targetPropertyNames = Arrays.copyOfRange( segments, 1, segments.length ); entries = getTargetEntries( resultType, targetPropertyNames ); foundEntryMatch = (entries.size() == targetPropertyNames.length); } if ( !foundEntryMatch && errorMessage != null && !isReversed ) { errorMessage.report( ); } return new TargetReference( parameter, entries, foundEntryMatch ); }
Source:
public void testNewEpochZxidWithTxnlogOnly() throws Exception { long peerZxid; db.txnLog.add(createProposal(getZxid(1, 1))); db.txnLog.add(createProposal(getZxid(2, 1))); db.txnLog.add(createProposal(getZxid(2, 2))); db.txnLog.add(createProposal(getZxid(4, 1))); db.lastProcessedZxid = getZxid(6, 0); peerZxid = getZxid(3, 0); assertTrue(learnerHandler.syncFollower(peerZxid, db, leader)); reset(); peerZxid = getZxid(4, 0); assertTrue(learnerHandler.syncFollower(peerZxid, db, leader)); reset(); peerZxid = getZxid(5, 0); assertTrue(learnerHandler.syncFollower(peerZxid, db, leader)); reset(); peerZxid = getZxid(6, 0); assertFalse(learnerHandler.syncFollower(peerZxid, db, leader)); assertOpType(Leader.DIFF, getZxid(6, 0), getZxid(6, 0)); assertEquals(1, learnerHandler.getQueuedPackets().size()); reset(); }

Target:
public void testNewEpochZxidWithTxnlogOnly() throws Exception { long peerZxid; db.txnLog.add(createProposal(getZxid(1, 1))); db.txnLog.add(createProposal(getZxid(2, 1))); db.txnLog.add(createProposal(getZxid(2, 2))); db.txnLog.add(createProposal(getZxid(4, 1))); db.lastProcessedZxid = getZxid(6, 0); peerZxid = getZxid(3, 0); assertFalse(learnerHandler.syncFollower(peerZxid, db, leader)); assertOpType(Leader.DIFF, getZxid(6, 0), getZxid(4, 1)); assertEquals(3, learnerHandler.getQueuedPackets().size()); queuedPacketMatches(new long[] { getZxid(4, 1)}); reset(); peerZxid = getZxid(4, 0); assertFalse(learnerHandler.syncFollower(peerZxid, db, leader)); assertOpType(Leader.DIFF, getZxid(6, 0), getZxid(4, 1)); assertEquals(3, learnerHandler.getQueuedPackets().size()); queuedPacketMatches(new long[] { getZxid(4, 1)}); reset(); peerZxid = getZxid(5, 0); assertFalse(learnerHandler.syncFollower(peerZxid, db, leader)); assertOpType(Leader.DIFF, getZxid(6, 0), getZxid(5, 0)); assertEquals(1, learnerHandler.getQueuedPackets().size()); reset(); peerZxid = getZxid(6, 0); assertFalse(learnerHandler.syncFollower(peerZxid, db, leader)); assertOpType(Leader.DIFF, getZxid(6, 0), getZxid(6, 0)); assertEquals(1, learnerHandler.getQueuedPackets().size()); reset(); }
Source:
MkNotifications(final int quantity) { int identifier = 0; this.notifications = Collections .<Notification>nCopies( quantity, new MkNotification(identifier += 1) ); }

Target:
MkNotifications(final int quantity) { this.notifications = new ArrayList<Notification>(quantity); for (int index = 0; index < quantity; ++index) { this.notifications.add(index, new MkNotification(index)); } }
Source:
public int getCardinality(FloatColumnSelector selector) { return -1; }

Target:
public int getCardinality(FloatColumnSelector selector) { return TopNColumnSelectorStrategy.CARDINALITY_UNKNOWN; }
Source:
private void renderOptimizeColumnSelection() { line("private ColumnSelection optimizeColumnSelection(ColumnSelection columns) {"); { line("if (columns.allColumnsSelected()) {"); { line("return allColumns;"); line("}"); } line("return columns;"); } line("}"); }

Target:
private void renderOptimizeColumnSelection() { line("private ColumnSelection optimizeColumnSelection(ColumnSelection columns) {"); { line("if (columns.allColumnsSelected()) {"); { line("return allColumns;"); } line("}"); line("return columns;"); } line("}"); }
Source:
public void rejectsExecutionsIfUnderlyingExecutorRejects() throws InterruptedException, ExecutionException { MultiplexingCompletionService<String, Integer> boundedService = MultiplexingCompletionService.create( ImmutableMap.of(KEY_1, createBoundedExecutor(2), KEY_2, createBoundedExecutor(2))); Callable<Integer> sleepForFiveSeconds = getSleepCallable(5_000); boundedService.submit(KEY_1, sleepForFiveSeconds); boundedService.submit(KEY_2, sleepForFiveSeconds); boundedService.submit(KEY_1, sleepForFiveSeconds); boundedService.submit(KEY_2, getSleepCallable(2)); boundedService.submit(KEY_1, sleepForFiveSeconds); assertThat(boundedService.poll(1, TimeUnit.SECONDS).get()).isEqualTo(2); assertThat(boundedService.poll()).isNull(); assertThatThrownBy(() -> boundedService.submit(KEY_1, sleepForFiveSeconds)) .isInstanceOf(RejectedExecutionException.class); }

Target:
public void rejectsExecutionsIfUnderlyingExecutorRejects() throws InterruptedException, ExecutionException { MultiplexingCompletionService<String, Integer> boundedService = MultiplexingCompletionService.create( ImmutableMap.of(KEY_1, createBoundedExecutor(1))); Callable<Integer> sleepForFiveSeconds = getSleepCallable(5_000); boundedService.submit(KEY_1, sleepForFiveSeconds); boundedService.submit(KEY_1, sleepForFiveSeconds); assertThat(boundedService.poll()).isNull(); assertThatThrownBy(() -> boundedService.submit(KEY_1, sleepForFiveSeconds)) .isInstanceOf(RejectedExecutionException.class); }
Source:
NewRoamingGroupEntity(String name, String description, RoamingGroupType type) { this.name = name; this.description = description; this.type = type; this.operatorIDs = Lists.newArrayList(); }

Target:
NewRoamingGroupEntity(String name, String description, RoamingGroupType type) { this.name = name; this.description = description; this.type = type; this.operatorIDs = ImmutableList.copyOf(Lists.newArrayList()); }
Source:
public final void compareCommitsPatch() throws Exception { final String patch = RtRepoCommitsITCase.repo().commits().patch( BASE, HEAD ); MatcherAssert.assertThat( patch, Matchers.startsWith( "From 9b2e6efde94fabec5876dc481b38811e8b4e992f" ) ); MatcherAssert.assertThat( patch, Matchers.containsString( "Subject: [PATCH] Issue #430 RepoCommit interface was added" ) ); }

Target:
public final void compareCommitsPatch() throws Exception { final String patch = RtRepoCommitsITCase.repo().commits().patch( "5339b8e35b", "9b2e6efde9" ); MatcherAssert.assertThat( patch, Matchers.startsWith( "From 9b2e6efde94fabec5876dc481b38811e8b4e992f" ) ); MatcherAssert.assertThat( patch, Matchers.containsString( "Subject: [PATCH] Issue #430 RepoCommit interface was added" ) ); }
Source:
public void onEditButtonClicked(final ClickEvent ignore) { presenter.openEditModal();; }

Target:
public void onEditButtonClicked(final ClickEvent ignore) { presenter.openEditModal(); }
Source:
private void importFlatGraph(final ElkNode elkgraph, final LGraph lgraph) { for (ElkNode child : elkgraph.getChildren()) { if (!child.getProperty(LayeredOptions.NO_LAYOUT)) { transformNode(child, lgraph); } } for (ElkEdge elkedge : elkgraph.getContainedEdges()) { ElkNode source = ElkGraphUtil.getSourceNode(elkedge); ElkNode target = ElkGraphUtil.getTargetNode(elkedge); boolean enableInsideSelfLoops = source.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_ACTIVATE); boolean isToBeLaidOut = !elkedge.getProperty(LayeredOptions.NO_LAYOUT); boolean isInsideSelfLoop = enableInsideSelfLoops && elkedge.isSelfloop() && elkedge.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_YO); boolean connectsSiblings = source.getParent() == elkgraph && source.getParent() == target.getParent(); boolean connectsToGraph = (source.getParent() == elkgraph && target == elkgraph) ^ (target.getParent() == elkgraph && source == elkgraph); if (isToBeLaidOut && !isInsideSelfLoop && (connectsToGraph || connectsSiblings)) { transformEdge(elkedge, elkgraph, lgraph); } } if (elkgraph.getParent() != null) { for (ElkEdge elkedge : elkgraph.getParent().getContainedEdges()) { ElkNode source = ElkGraphUtil.getSourceNode(elkedge); if (source == elkgraph && elkedge.isSelfloop()) { boolean enableInsideSelfLoops = source.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_ACTIVATE); boolean isInsideSelfLoop = enableInsideSelfLoops && elkedge.isSelfloop() && elkedge.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_YO); if (isInsideSelfLoop) { transformEdge(elkedge, elkgraph, lgraph); } } } } }

Target:
private void importFlatGraph(final ElkNode elkgraph, final LGraph lgraph) { for (ElkNode child : elkgraph.getChildren()) { if (!child.getProperty(LayeredOptions.NO_LAYOUT)) { transformNode(child, lgraph); } } for (ElkEdge elkedge : elkgraph.getContainedEdges()) { ElkNode source = ElkGraphUtil.getSourceNode(elkedge); ElkNode target = ElkGraphUtil.getTargetNode(elkedge); boolean enableInsideSelfLoops = source.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_ACTIVATE); boolean isToBeLaidOut = !elkedge.getProperty(LayeredOptions.NO_LAYOUT); boolean isInsideSelfLoop = enableInsideSelfLoops && elkedge.isSelfloop() && elkedge.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_YO); boolean connectsSiblings = source.getParent() == elkgraph && source.getParent() == target.getParent(); boolean connectsToGraph = (source.getParent() == elkgraph && target == elkgraph) ^ (target.getParent() == elkgraph && source == elkgraph); if (isToBeLaidOut && !isInsideSelfLoop && (connectsToGraph || connectsSiblings)) { transformEdge(elkedge, elkgraph, lgraph); } } if (elkgraph.getParent() != null) { for (ElkEdge elkedge : elkgraph.getParent().getContainedEdges()) { ElkNode source = ElkGraphUtil.getSourceNode(elkedge); if (source == elkgraph && elkedge.isSelfloop()) { boolean isInsideSelfLoop = source.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_ACTIVATE) && elkedge.getProperty(LayeredOptions.INSIDE_SELF_LOOPS_YO); if (isInsideSelfLoop) { transformEdge(elkedge, elkgraph, lgraph); } } } } }
Source:
public void testGetConnection() throws Exception { Subject subject = new Subject(true, ImmutableSet.<Principal>of(), ImmutableSet.of("bugger"), ImmutableSet.of("PASSWORD")); assertFalse(subject.equals(UserContext.get().getSubject())); adaptor.init(context); try (Connection connection = getConfigOptions().getConnection()) { assertEquals("http://localhost/", connection.getConnection().getURI()); assertTrue(subject.equals(UserContext.get().getSubject())); } assertFalse(subject.equals(UserContext.get().getSubject())); }

Target:
public void testGetConnection() throws Exception { Subject subject = new Subject(true, ImmutableSet.<Principal>of(), ImmutableSet.of("test"), ImmutableSet.of("PASSWORD")); assertFalse(subject.equals(UserContext.get().getSubject())); adaptor.init(context); try (Connection connection = getConfigOptions().getConnection()) { assertEquals("http://localhost/", connection.getConnection().getURI()); assertTrue(subject.equals(UserContext.get().getSubject())); } assertFalse(subject.equals(UserContext.get().getSubject())); }
Source:
public List<Condition> getActiveConditions(Patient patient) { System.out.println("near query in getActiveConditions in core"); Query query = sessionFactory.getCurrentSession().createQuery( "from Condition c where c.patient.patientId = :patientId and c.voided = false and c.endDate is null order " + "by c.onsetDate desc"); query.setInteger("patientId", patient.getId()); return query.list(); }

Target:
public List<Condition> getActiveConditions(Patient patient) { Query query = sessionFactory.getCurrentSession().createQuery( "from Condition c where c.patient.patientId = :patientId and c.voided = false and c.endDate is null order " + "by c.onsetDate desc"); query.setInteger("patientId", patient.getId()); return query.list(); }
Source:
private Segment parseSegment(Node n) throws TypeImportException { Segment segment = LibraryElementFactory.eINSTANCE.createSegment(); NamedNodeMap mapSegment = n.getAttributes(); CommonElementImporter.readNameCommentAttributes(segment, mapSegment); Node dx1 = mapSegment.getNamedItem(LibraryElementTags.DX1_ATTRIBUTE); if(dx1 != null){ String dx1String = dx1.getNodeValue(); double dx1double = 0.; if ((null != dx1String) && dx1String.length() != 0) { dx1double = CoordinateConverter.INSTANCE.convertFrom1499XML(dx1.getNodeValue()); } segment.setWidth(((int) dx1double)); } CommonElementImporter.getXandY(mapSegment, segment); Node type = mapSegment.getNamedItem(LibraryElementTags.TYPE_ATTRIBUTE); if(type != null){ PaletteEntry entry = palette.getTypeEntry(type.getNodeValue()); if (entry instanceof SegmentTypePaletteEntry) { segment.setPaletteEntry(entry); } } parseSegmentNodeChildren(segment, n.getChildNodes()); return segment; }

Target:
private Segment parseSegment(Node n) throws TypeImportException { Segment segment = LibraryElementFactory.eINSTANCE.createSegment(); NamedNodeMap mapSegment = n.getAttributes(); CommonElementImporter.readNameCommentAttributes(segment, mapSegment); Node dx1 = mapSegment.getNamedItem(LibraryElementTags.DX1_ATTRIBUTE); if(dx1 != null){ segment.setWidth(CoordinateConverter.INSTANCE.convertFrom1499XML(dx1.getNodeValue())); } CommonElementImporter.getXandY(mapSegment, segment); Node type = mapSegment.getNamedItem(LibraryElementTags.TYPE_ATTRIBUTE); if(type != null){ PaletteEntry entry = palette.getTypeEntry(type.getNodeValue()); if (entry instanceof SegmentTypePaletteEntry) { segment.setPaletteEntry(entry); } } parseSegmentNodeChildren(segment, n.getChildNodes()); return segment; }
Source:
protected String detect( InputStream inputStream, Metadata metadata ) { try { IoUtil.closeQuietly(inputStream); MediaType detectedMimeType = detector.detect(null, metadata); if (logger.isTraceEnabled()) { logger.trace("MIME type for '" + metadata.get(Metadata.RESOURCE_NAME_KEY) + "' ==> " + detectedMimeType); } return detectedMimeType.toString(); } catch (Exception e) { logger.debug(e, "Unable to extract mime-type"); return null; } }

Target:
protected String detect( InputStream inputStream, Metadata metadata ) { try { MediaType detectedMimeType = detector.detect(null, metadata); if (logger.isTraceEnabled()) { logger.trace("MIME type for '" + metadata.get(Metadata.RESOURCE_NAME_KEY) + "' ==> " + detectedMimeType); } return detectedMimeType.toString(); } catch (Exception e) { logger.debug(e, "Unable to extract mime-type"); return null; } finally { IoUtil.closeQuietly(inputStream); } }
Source:
public void doTestImport(StorageDomain storageDomain, Cluster cluster, boolean collapseSnapshots, boolean importAsNewEntity) throws Exception { setUpGetEntityExpectations(1, StorageDomainType.ImportExport, GUIDS[2]); setUriInfo(setUpActionExpectations(VdcActionType.ImportVm, ImportVmParameters.class, new String[] { "ContainerId", "StorageDomainId", "SourceDomainId", "DestDomainId", "StoragePoolId", "VdsGroupId", "CopyCollapse", "ImportAsNewEntity" }, new Object[] { VM_ID, GUIDS[2], STORAGE_DOMAIN_ID, GUIDS[2], DATA_CENTER_ID, GUIDS[1], collapseSnapshots, importAsNewEntity })); Action action = new Action(); action.setStorageDomain(storageDomain); action.setCluster(cluster); if(collapseSnapshots){ VM vm = new VM(); vm.setSnapshots(new Snapshots()); vm.getSnapshots().setCollapseSnapshots(collapseSnapshots); action.setVm(vm); } action.setImportAsNewEntity(importAsNewEntity); verifyActionResponse(resource.doImport(action)); }

Target:
public void doTestImport(StorageDomain storageDomain, Cluster cluster, boolean collapseSnapshots, boolean importAsNewEntity) throws Exception { setUpGetEntityExpectations(1, StorageDomainType.ImportExport, GUIDS[2]); setUriInfo(setUpActionExpectations(VdcActionType.ImportVm, ImportVmParameters.class, new String[] { "ContainerId", "StorageDomainId", "SourceDomainId", "DestDomainId", "StoragePoolId", "VdsGroupId", "CopyCollapse", "ImportAsNewEntity" }, new Object[] { VM_ID, GUIDS[2], STORAGE_DOMAIN_ID, GUIDS[2], DATA_CENTER_ID, GUIDS[1], collapseSnapshots, importAsNewEntity })); Action action = new Action(); action.setStorageDomain(storageDomain); action.setCluster(cluster); if(collapseSnapshots){ VM vm = new VM(); vm.setSnapshots(new Snapshots()); vm.getSnapshots().setCollapseSnapshots(collapseSnapshots); action.setVm(vm); } action.setClone(importAsNewEntity); verifyActionResponse(resource.doImport(action)); }
Source:
public int getProjectProgress(int projectId) { String projectIdString = String.valueOf(projectId); SQLiteDatabase db = getReadableDatabase(); final String query = String.format("SELECT %s FROM %s WHERE %s=?", ProjectContract.ProjectEntry.PROJECT_PROGRESS, ProjectContract.ProjectEntry.TABLE_PROJECT, ProjectContract.ProjectEntry._ID); float progress = DatabaseUtils.longForQuery(db, query, new String[]{projectIdString}); db.close(); return Math.round(progress); }

Target:
public int getProjectProgress(int projectId) { String projectIdString = String.valueOf(projectId); SQLiteDatabase db = getReadableDatabase(); final String query = String.format("SELECT %s FROM %s WHERE %s=?", ProjectContract.ProjectEntry.PROJECT_PROGRESS, ProjectContract.ProjectEntry.TABLE_PROJECT, ProjectContract.ProjectEntry._ID ); float progress = DatabaseUtils.longForQuery(db, query, new String[]{projectIdString}); return Math.round(progress); }
Source:
private void assignUnitToTemplate() { Unit unit = unitList.getSelectedValue(); currentScenario.removeUnit(unit.getId()); currentScenario.addUnit(unit.getId(), templateList.getSelectedValue().getForceName()); unit.setScenarioId(currentScenario.getId()); MekHQ.triggerEvent(new DeploymentChangedEvent(unit, currentScenario)); if (!unit.getTransportedUnits().isEmpty()) { int optionChoice = JOptionPane.showConfirmDialog(null, unit.getName() + " is a transport with units assigned to it. \n" + "Would you also like to deploy these units?", "Also deploy transported units?", JOptionPane.YES_NO_OPTION); if (optionChoice == JOptionPane.YES_OPTION) { for (UUID id : unit.getTransportedUnits()) { Unit cargo = unit.getCampaign().getUnit(id); if (cargo != null) { currentScenario.removeUnit(cargo.getId()); currentScenario.addUnit(cargo.getId(), templateList.getSelectedValue().getForceName()); cargo.setScenarioId(currentScenario.getId()); MekHQ.triggerEvent(new DeploymentChangedEvent(cargo, currentScenario)); } } } } refreshUnitList(); }

Target:
private void assignUnitToTemplate() { Unit unit = unitList.getSelectedValue(); currentScenario.removeUnit(unit.getId()); currentScenario.addUnit(unit.getId(), templateList.getSelectedValue().getForceName()); unit.setScenarioId(currentScenario.getId()); MekHQ.triggerEvent(new DeploymentChangedEvent(unit, currentScenario)); if (!unit.getTransportedUnits().isEmpty()) { deployTransportedUnitsDialog(unit); } refreshUnitList(); }
Source:
public Matrix[] decompose(Matrix matrix, Factory factory) { if (matrix.rows() != matrix.columns()) { throw new IllegalArgumentException("Wrong matrix size: " + "rows != columns"); } Matrix l = factory.createMatrix(matrix.rows(), matrix.columns()); Matrix u = factory.createIdentityMatrix(matrix.rows()); double s=0; for (int j = 0; j < l.columns(); j++){ for (int i = j; i < l.rows(); i++){ s=0; for (int k = 0; k < j; k++){ s = s + l.get(i, k)*u.get(k, j); } l.set(i,j,matrix.get(i, j) - s); } for (int i = j; i < l.rows(); i++){ s=0; for (int k = 0; k < j; k++){ s = s + l.get(j, k)*u.get(k, i); } if (l.get(j, j) == 0) throw new IllegalArgumentException("Singular matrix!"); u.set(j,i,(matrix.get(j, i) - s)/l.get(j, j)); } } return new Matrix[] { l, u }; }

Target:
public Matrix[] decompose(Matrix matrix, Factory factory) { if (matrix.rows() != matrix.columns()) { throw new IllegalArgumentException("Wrong matrix size: " + "rows != columns"); } Matrix l = factory.createMatrix(matrix.rows(), matrix.columns()); Matrix u = factory.createIdentityMatrix(matrix.rows()); for (int j = 0; j < l.columns(); j++){ for (int i = j; i < l.rows(); i++){ double s = 0.0; for (int k = 0; k < j; k++){ s = s + l.get(i, k) * u.get(k, j); } l.set(i,j,matrix.get(i, j) - s); } for (int i = j; i < l.rows(); i++){ double s = 0.0; for (int k = 0; k < j; k++){ s = s + l.get(j, k) * u.get(k, i); } if (Math.abs(l.get(j, j)) < Matrices.EPS){ throw new IllegalArgumentException("Singular matrix!"); } u.set(j, i, (matrix.get(j, i) - s) / l.get(j, j)); } } return new Matrix[] { l, u }; }
Source:
public Boolean getMakeRedundant() { if (makeRedundant != null) { return makeRedundant; } return true; }

Target:
public Boolean getMakeRedundant() { return makeRedundant; }
Source:
public void loadAwardsFromStream(InputStream inputStream, String fileName){ AwardSet awardSet = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(AwardSet.class, Award.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); awardSet = unmarshaller.unmarshal(MekHqXmlUtil.createSafeXmlSource(inputStream), AwardSet.class).getValue(); Map<String, Award> tempAwardMap = new HashMap<>(); String currentSetName = fileName.replaceFirst("[.][^.]+$", ""); for (Award award : awardSet.getAwards()){ award.setSet(currentSetName); tempAwardMap.put(award.getName(), award); } awardsMap.put(currentSetName, tempAwardMap); } catch (SAXException | ParserConfigurationException e) { MekHQ.getLogger().error(AwardsFactory.class, "loadAwards", e); } catch (JAXBException e) { MekHQ.getLogger().error(AwardsFactory.class, "loadAwards", "Error loading XML for awards", e); } }

Target:
public void loadAwardsFromStream(InputStream inputStream, String fileName){ AwardSet awardSet; try { JAXBContext jaxbContext = JAXBContext.newInstance(AwardSet.class, Award.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); awardSet = unmarshaller.unmarshal(MekHqXmlUtil.createSafeXmlSource(inputStream), AwardSet.class).getValue(); Map<String, Award> tempAwardMap = new HashMap<>(); String currentSetName = fileName.replaceFirst("[.][^.]+$", ""); int i = 0; for (Award award : awardSet.getAwards()){ award.setId(i); i++; award.setSet(currentSetName); tempAwardMap.put(award.getName(), award); } awardsMap.put(currentSetName, tempAwardMap); } catch (JAXBException e) { MekHQ.getLogger().error(AwardsFactory.class, "loadAwards", "Error loading XML for awards", e); } }
Source:
private String getCollectionNameForAlias(NamedList<Object> response, String alias) { LinkedHashMap aliases = (LinkedHashMap) response.findRecursive("cluster", "aliases"); Object collectionName = aliases.getOrDefault(alias, null); if(collectionName != null) { return collectionName.toString(); } else { throw new RuntimeException("The alias " + alias + " does not match any collections in Solr"); } }

Target:
private String getCollectionNameForAlias(NamedList<Object> response, String alias) { LinkedHashMap aliases = (LinkedHashMap) response.findRecursive("cluster", "aliases"); Object collectionName = aliases.get(alias); if(collectionName != null) { return collectionName.toString(); } else { throw new RuntimeException("The alias " + alias + " does not match any collections in Solr"); } }
Source:
protected int getPatternMatchRule(String pattern, String string) { String start; try { start= string.substring(0, pattern.length()); } catch (StringIndexOutOfBoundsException e) { String message= "Error retrieving proposal text.\nDisplay string:\n" + string + "\nPattern:\n" + pattern; JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, message, e)); return -1; } if (start.equalsIgnoreCase(pattern)) { return SearchPattern.R_PREFIX_MATCH; } else if (isCamelCaseMatching() && CharOperation.camelCaseMatch(pattern.toCharArray(), string.toCharArray())) { return SearchPattern.R_CAMELCASE_MATCH; } else if (isSubstringMatching() && CharOperation.substringMatch(pattern.toCharArray(), string.toCharArray())) { return SearchPattern.R_SUBSTRING_MATCH; } else if (CharOperation.subWordMatch(pattern.toCharArray(), string.toCharArray())) { return SearchPattern.R_SUBWORD_MATCH; } else { return -1; } }

Target:
protected int getPatternMatchRule(String pattern, String string) { String start; try { start= string.substring(0, pattern.length()); } catch (StringIndexOutOfBoundsException e) { String message= "Error retrieving proposal text.\nDisplay string:\n" + string + "\nPattern:\n" + pattern; JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, message, e)); return -1; } if (start.equalsIgnoreCase(pattern)) { return SearchPattern.R_PREFIX_MATCH; } else if (isCamelCaseMatching() && CharOperation.camelCaseMatch(pattern.toCharArray(), string.toCharArray())) { return SearchPattern.R_CAMELCASE_MATCH; } else if (isSubstringMatching() && CharOperation.substringMatch(pattern.toCharArray(), string.toCharArray())) { return SearchPattern.R_SUBSTRING_MATCH; } else if (isSubwordMatching() && CharOperation.subWordMatch(pattern.toCharArray(), string.toCharArray())) { return SearchPattern.R_SUBWORD_MATCH; } else { return -1; } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_clear_all_saved_pages: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.dialog_title_clear_saved_pages); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { app.getPersister(SavedPage.class).deleteAll(); Utils.deleteRecursive(new File(SavedPage.getSavedPagesDir()), true); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; default: throw new RuntimeException("Unknown menu item clicked!"); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_clear_all_saved_pages: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.dialog_title_clear_saved_pages); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { app.getPersister(SavedPage.class).deleteAll(); (new SaneAsyncTask<Void>(SaneAsyncTask.SINGLE_THREAD) { @Override public Void performTask() throws Throwable { Utils.delete(new File(SavedPage.getSavedPagesDir()), true); return null; } }).execute(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; default: throw new RuntimeException("Unknown menu item clicked!"); } }
Source:
protected void initMatching() { if (fMatches != null) { fMatches.init(fTraces); } List<ITmfMatchEventDefinition> deflist = fMatchDefinitions.get(getMatchingType()); if (deflist == null) { return; } for (ITmfTrace trace : fTraces) { for (ITmfMatchEventDefinition def : deflist) { if (def.canMatchTrace(trace)) { fMatchMap.put(trace, def); break; } } } }

Target:
protected void initMatching() { fMatches.init(fTraces); List<ITmfMatchEventDefinition> deflist = fMatchDefinitions.get(getMatchingType()); if (deflist == null) { return; } for (ITmfTrace trace : fTraces) { for (ITmfMatchEventDefinition def : deflist) { if (def.canMatchTrace(trace)) { fMatchMap.put(trace, def); break; } } } }
Source:
private StreamStoreCellDeletion findCellsToPropagateDeletes( Map<GenericStreamIdentifier, StreamMetadata> streamIdentifierToMetadata) { ImmutableStreamStoreCellDeletion.Builder builder = ImmutableStreamStoreCellDeletion.builder(); for (Map.Entry<GenericStreamIdentifier, StreamMetadata> entry : streamIdentifierToMetadata.entrySet()) { GenericStreamIdentifier streamId = entry.getKey(); StreamMetadata streamMetadata = entry.getValue(); builder.addAllValueTableCellsToDelete(cellCreator.constructValueTableCellSet( streamId, getNumberOfBlocksFromMetadata(entry.getValue()))); builder.addMetadataTableCellsToDelete(cellCreator.constructMetadataTableCell(streamId)); builder.addHashTableCellsToDelete(cellCreator.constructHashTableCell(streamId, streamMetadata.getHash())); } return builder.build(); }

Target:
private StreamStoreCellDeletion findCellsToPropagateDeletes( Map<GenericStreamIdentifier, StreamMetadata> streamIdentifierToMetadata) { ImmutableStreamStoreCellDeletion.Builder builder = ImmutableStreamStoreCellDeletion.builder(); for (Map.Entry<GenericStreamIdentifier, StreamMetadata> entry : streamIdentifierToMetadata.entrySet()) { GenericStreamIdentifier streamId = entry.getKey(); StreamMetadata streamMetadata = entry.getValue(); builder.addAllValueTableCellsToDelete(cellCreator.constructValueTableCellSet( streamId, StreamMetadatas.getNumberOfBlocksFromMetadata(streamMetadata))); builder.addMetadataTableCellsToDelete(cellCreator.constructMetadataTableCell(streamId)); builder.addHashTableCellsToDelete(cellCreator.constructHashTableCell(streamId, streamMetadata.getHash())); } return builder.build(); }
Source:
public void testList() { dataCenters = dataCenterApi().list(); currentDataCenter = dataCenters.get(0); assertNotNull(dataCenters); assertFalse(dataCenters.isEmpty()); Assert.assertTrue(dataCenters.size() > 0); }

Target:
public void testList() { dataCenters = dataCenterApi().list(); assertNotNull(dataCenters); currentDataCenter = dataCenters.get(0); assertFalse(dataCenters.isEmpty()); Assert.assertTrue(dataCenters.size() > 0); }
Source:
public Optional<URL> findFullText(BibEntry entry) throws IOException { Objects.requireNonNull(entry); Optional<DOI> doi = entry.getField(StandardField.DOI).flatMap(DOI::parse); if (!doi.isPresent()) { return Optional.empty(); } Optional<String> id = getId(doi.get().getDOI()); if (id.isPresent()) { String pdfRequestUrl = PDF_URL + id.get(); int code = Unirest.head(pdfRequestUrl).asJson().getStatus(); if (code == 200) { LOGGER.info("Fulltext PDF found @ APS."); try { return Optional.of(new URL(pdfRequestUrl)); } catch (MalformedURLException e) { LOGGER.info("APS returned malformed URL, cannot find PDF."); } } } return Optional.empty(); }

Target:
public Optional<URL> findFullText(BibEntry entry) throws IOException { Objects.requireNonNull(entry); Optional<DOI> doi = entry.getField(StandardField.DOI).flatMap(DOI::parse); if (!doi.isPresent()) { return Optional.empty(); } Optional<String> id = getId(doi.get().getDOI()); if (id.isPresent()) { String pdfRequestUrl = PDF_URL + id.get(); int code = Unirest.head(pdfRequestUrl).asJson().getStatus(); if (code == 200) { LOGGER.info("Fulltext PDF found @ APS."); try { return Optional.of(new URL(pdfRequestUrl)); } catch (MalformedURLException e) { LOGGER.warn("APS returned malformed URL, cannot find PDF."); } } } return Optional.empty(); }
Source:
public void addDynamicTemplateData(String key, Object value) { if (dynamicTemplateData == null) { dynamicTemplateData = new HashMap<String,Object>(); dynamicTemplateData.put(key, value); } else { dynamicTemplateData.put(key, value); } }

Target:
public void addDynamicTemplateData(String key, Object value) { if (dynamicTemplateData == null) { dynamicTemplateData = new HashMap<String,Object>(); } dynamicTemplateData.put(key, value); }
Source:
public void assignStates() { Map<OperatorID, OperatorState> localOperators = new HashMap<>(operatorStates); checkStateMappingCompleteness(allowNonRestoredState, operatorStates, tasks); for (ExecutionJobVertex executionJobVertex : this.tasks) { List<OperatorIDPair> operatorIDPairs = executionJobVertex.getOperatorIDs(); Map<OperatorID, OperatorState> operatorStates = new HashMap<>(operatorIDPairs.size()); for (OperatorIDPair operatorIDPair : operatorIDPairs) { OperatorID operatorID = operatorIDPair.getUserDefinedOperatorID().orElse(operatorIDPair.getGeneratedOperatorID()); OperatorState operatorState = localOperators.remove(operatorID); if (operatorState == null) { operatorState = new OperatorState( operatorID, executionJobVertex.getParallelism(), executionJobVertex.getMaxParallelism()); } operatorStates.put(operatorIDPair.getGeneratedOperatorID(), operatorState); } final TaskStateAssignment stateAssignment = new TaskStateAssignment(executionJobVertex, operatorStates); vertexAssignments.put(executionJobVertex, stateAssignment); for (final IntermediateResult producedDataSet : executionJobVertex.getInputs()) { consumerAssignment.put(producedDataSet, stateAssignment); } } for (TaskStateAssignment stateAssignment : vertexAssignments.values()) { if (stateAssignment.hasState) { assignAttemptState(stateAssignment); } } for (TaskStateAssignment stateAssignment : vertexAssignments.values()) { if (stateAssignment.hasState) { assignTaskStateToExecutionJobVertices(stateAssignment); } } }

Target:
public void assignStates() { Map<OperatorID, OperatorState> localOperators = new HashMap<>(operatorStates); checkStateMappingCompleteness(allowNonRestoredState, operatorStates, tasks); for (ExecutionJobVertex executionJobVertex : this.tasks) { List<OperatorIDPair> operatorIDPairs = executionJobVertex.getOperatorIDs(); Map<OperatorID, OperatorState> operatorStates = new HashMap<>(operatorIDPairs.size()); for (OperatorIDPair operatorIDPair : operatorIDPairs) { OperatorID operatorID = operatorIDPair.getUserDefinedOperatorID().orElse(operatorIDPair.getGeneratedOperatorID()); OperatorState operatorState = localOperators.remove(operatorID); if (operatorState == null) { operatorState = new OperatorState( operatorID, executionJobVertex.getParallelism(), executionJobVertex.getMaxParallelism()); } operatorStates.put(operatorIDPair.getGeneratedOperatorID(), operatorState); } final TaskStateAssignment stateAssignment = new TaskStateAssignment(executionJobVertex, operatorStates); vertexAssignments.put(executionJobVertex, stateAssignment); for (final IntermediateResult producedDataSet : executionJobVertex.getInputs()) { consumerAssignment.put(producedDataSet.getId(), stateAssignment); } } for (TaskStateAssignment stateAssignment : vertexAssignments.values()) { if (stateAssignment.hasState) { assignAttemptState(stateAssignment); } } for (TaskStateAssignment stateAssignment : vertexAssignments.values()) { if (stateAssignment.hasState) { assignTaskStateToExecutionJobVertices(stateAssignment); } } }
Source:
public static char getVersion(File jacocoExec) throws IOException { char version; try (DataInputStream in = new DataInputStream(new FileInputStream(jacocoExec))) { if (in.read() != ExecutionDataWriter.BLOCK_HEADER) { throw new IOException("Invalid execution data file."); } if (in.readChar() != ExecutionDataWriter.MAGIC_NUMBER) { throw new IOException("Invalid execution data file."); } version = in.readChar(); } return version; }

Target:
public static char getVersion(File jacocoExec) throws IOException { char version; try (DataInputStream in = new DataInputStream(new FileInputStream(jacocoExec))) { if (in.read() != ExecutionDataWriter.BLOCK_HEADER) { throw new IOException("Invalid execution data file. Unrecognized block header."); } if (in.readChar() != ExecutionDataWriter.MAGIC_NUMBER) { throw new IOException("Invalid execution data file. Unrecognized magic number."); } version = in.readChar(); } return version; }
Source:
@Test public void emptyAdapters() throws Exception { try { Moshi moshi = new Moshi.Builder() .add(new EmptyJsonAdapter()).build(); } catch (IllegalArgumentException expected){ assertThat(expected.getMessage()).contains( "Expected at least one @ToJson or @FromJson method on", "EmptyJsonAdapter"); } }

Target:
@Test public void emptyAdapters() throws Exception { Moshi.Builder builder = new Moshi.Builder(); try { builder.add(new EmptyJsonAdapter()).build(); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage( "Expected at least one @ToJson or @FromJson method on " + "com.squareup.moshi.AdapterMethodsTest$EmptyJsonAdapter"); } }
Source:
public Construct exec(Target t, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException { if(args.length < 1){ throw new ConfigRuntimeException("You must send at least 1 arguments to msg", ExceptionType.InsufficientArgumentsException, t); } StringBuilder b = new StringBuilder(); for(int i = 0; i < args.length; i++){ b.append(args[i].val()); } Static.SendMessage(env.GetCommandSender(), b.toString(), t); return new CVoid(t); }

Target:
public Construct exec(Target t, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException { StringBuilder b = new StringBuilder(); for(int i = 0; i < args.length; i++){ b.append(args[i].val()); } Static.SendMessage(env.GetCommandSender(), b.toString(), t); return new CVoid(t); }
Source:
public String toString() { return new StringBuilder("JavaTypeDefinition [clazz=").append(clazz) .append(", definitionType=").append(getDefinitionType()) .append(", genericArgs=").append(genericArgs.stream().map(new Function<JavaTypeDefinition, String>() { @Override public String apply(final JavaTypeDefinition jtd) { return jtd.shallowString(); } }).collect(Collectors.toList())) .append(", isGeneric=").append(isGeneric) .append("]\n").toString(); }

Target:
public String toString() { final StringBuilder sb = new StringBuilder("JavaTypeDefinition [clazz=").append(clazz) .append(", definitionType=").append(getDefinitionType()) .append(", genericArgs=["); for (final JavaTypeDefinition jtd : genericArgs) { sb.append(jtd.shallowString()).append(", "); } return sb.replace(sb.length() - 3, sb.length() - 1, "]") .append(", isGeneric=").append(isGeneric) .append("]\n").toString(); }
Source:
public void testComponents() throws Exception { final Jar jar = new Jar("jar", "testresources/gogoEntry/source.jar"); final Processor p = new Processor(); final GogoPlugin e = new GogoPlugin(); final Map<String, Object> result = new HashMap<>(); e.setReporter(p); result.put(e.getProperties() .get(ReportEntryPlugin.ENTRY_NAME_PROPERTY), e.extract(jar, Locale.forLanguageTag("und"))); assertTrue(p.isOk()); final ByteArrayOutputStream s = new ByteArrayOutputStream(); new JsonReportSerializerPlugin().serialize(result, s); System.out.println(new String(s.toByteArray())); final StringBuffer ee = new StringBuffer(); for (final String l : Files.readAllLines(Paths.get("testresources/gogoEntry/result.json"), StandardCharsets.UTF_8)) { ee.append(l + "\n"); } ee.deleteCharAt(ee.length() - 1); assertEquals(ee.toString(), new String(s.toByteArray())); }

Target:
public void testComponents() throws Exception { try (final Jar jar = new Jar("jar", "testresources/gogoEntry/source.jar"); final Processor p = new Processor()) { final GogoPlugin e = new GogoPlugin(); final Map<String, Object> result = new HashMap<>(); e.setReporter(p); result.put(e.getProperties() .get(ReportEntryPlugin.ENTRY_NAME_PROPERTY), e.extract(jar, Locale.forLanguageTag("und"))); assertTrue(p.isOk()); final ByteArrayOutputStream s = new ByteArrayOutputStream(); new JsonReportSerializerPlugin().serialize(result, s); System.out.println(new String(s.toByteArray())); final StringBuffer ee = new StringBuffer(); for (final String l : Files.readAllLines(Paths.get("testresources/gogoEntry/result.json"), StandardCharsets.UTF_8)) { ee.append(l + "\n"); } ee.deleteCharAt(ee.length() - 1); assertEquals(ee.toString(), new String(s.toByteArray())); } }
Source:
private void checkPostConstructContainsParameter(final Class<?> clazz) throws ControllerValidationException { List<Method> methods = ReflectionHelper.getInheritedDeclaredMethods(clazz); if(null != methods) { for (Method method : methods) { if (method.isAnnotationPresent(PostConstruct.class)) { if (method.getParameterTypes().length > 0) { throw new ControllerValidationException("PostConstruct method " + method.getName() + " should not contain parameter in Controller " + clazz.getName()); } } } } }

Target:
private void checkPostConstructContainsParameter(final Class<?> clazz) throws ControllerValidationException { Assert.requireNonNull(clazz, "clazz"); final ControllerValidationException controllerValidationException = ReflectionHelper.getInheritedDeclaredMethods(clazz).stream(). filter(method -> method.isAnnotationPresent(PostConstruct.class)). filter(method -> method.getParameterTypes().length > 0). findAny().map(method ->new ControllerValidationException("PostConstruct method " + method.getName() + " should not contain parameter in Controller " + ControllerUtils.getControllerName(clazz))). orElse(null); if(controllerValidationException != null){ throw controllerValidationException; } }