auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void test_loading_java10_class() throws Exception { BytecodeCompleter bytecodeCompleter = new BytecodeCompleter( new SquidClassLoader(Collections.singletonList(new File("src/test/files/bytecode/java10/bin"))), new ParametrizedTypeCache()); new Symbols(bytecodeCompleter); TypeJavaSymbol classSymbol = (TypeJavaSymbol) bytecodeCompleter.loadClass("org.foo.A"); classSymbol.complete(); assertThat(classSymbol.getFullyQualifiedName()).isEqualTo("org.foo.A"); Collection<Symbol> memberSymbols = classSymbol.memberSymbols(); assertThat(memberSymbols).hasSize(2); Symbol implicitDefaultConstructor = null; Symbol foo = null; for (Symbol symbol : memberSymbols) { if ("foo".equals(symbol.name())) { foo = symbol; } else { implicitDefaultConstructor = symbol; } } assertThat(implicitDefaultConstructor.name()).isEqualTo("<init>"); assertThat(implicitDefaultConstructor.isMethodSymbol()).isTrue(); assertThat(((JavaSymbol.MethodJavaSymbol) implicitDefaultConstructor).isConstructor()).isTrue(); assertThat(((JavaSymbol.MethodJavaSymbol) implicitDefaultConstructor).parameterTypes()).isEmpty(); assertThat(foo.name()).isEqualTo("foo"); assertThat(foo.isMethodSymbol()).isTrue(); assertThat(((JavaSymbol.MethodJavaSymbol) foo).isConstructor()).isFalse(); assertThat(((JavaSymbol.MethodJavaSymbol) foo).parameterTypes()).isEmpty(); }

Target:
public void test_loading_java10_class() throws Exception { BytecodeCompleter bytecodeCompleter = new BytecodeCompleter( new SquidClassLoader(Collections.singletonList(new File("src/test/files/bytecode/java10/bin"))), new ParametrizedTypeCache()); new Symbols(bytecodeCompleter); TypeJavaSymbol classSymbol = (TypeJavaSymbol) bytecodeCompleter.loadClass("org.foo.A"); classSymbol.complete(); assertThat(classSymbol.getFullyQualifiedName()).isEqualTo("org.foo.A"); assertThat(classSymbol.memberSymbols()).hasSize(2); Scope members = classSymbol.members(); Symbol implicitDefaultConstructor = members.lookup("<init>").get(0); Symbol foo = members.lookup("foo").get(0); assertThat(implicitDefaultConstructor.name()).isEqualTo("<init>"); assertThat(implicitDefaultConstructor.isMethodSymbol()).isTrue(); assertThat(((JavaSymbol.MethodJavaSymbol) implicitDefaultConstructor).isConstructor()).isTrue(); assertThat(((JavaSymbol.MethodJavaSymbol) implicitDefaultConstructor).parameterTypes()).isEmpty(); assertThat(foo.name()).isEqualTo("foo"); assertThat(foo.isMethodSymbol()).isTrue(); assertThat(((JavaSymbol.MethodJavaSymbol) foo).isConstructor()).isFalse(); assertThat(((JavaSymbol.MethodJavaSymbol) foo).parameterTypes()).isEmpty(); }
Source:
public byte[][] transformToBytesValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new byte[DocIdSetPlanNode.MAX_DOC_PER_CALL][]; } String[] argumentValues = _transformFunction.transformToStringValuesSV(projectionBlock); int length = projectionBlock.getNumDocs(); for (int i = 0; i < length; i++) { try { Geometry geometry = _reader.read(argumentValues[i]); _results[i] = GeometrySerializer.serialize(geometry); } catch (ParseException e) { throw new RuntimeException(String.format("Failed to parse geometry from String %s", argumentValues[i])); } } return _results; }

Target:
public byte[][] transformToBytesValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new byte[DocIdSetPlanNode.MAX_DOC_PER_CALL][]; } String[] argumentValues = _transformFunction.transformToStringValuesSV(projectionBlock); int length = projectionBlock.getNumDocs(); for (int i = 0; i < length; i++) { try { Geometry geometry = _reader.read(argumentValues[i]); _results[i] = GeometrySerializer.serialize(geometry); } catch (ParseException e) { Utils.rethrowException( new RuntimeException(String.format("Failed to parse geometry from string: %s", argumentValues[i]))); } } return _results; }
Source:
private QueryResult executeTearDown( Query query, String gateway, String username, String password, Duration timeout, List<QueryResult> postQueryResults, int teardownRetries) { int attempt = 0; QueryResult tearDownResult; do { tearDownResult = tearDown( query, postQueryResults, postQuery -> executeQuery( gateway, username, password, query, postQuery, timeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); log.info(format("Query teardown failed on attempt #%d, will sleep and retry", attempt)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } attempt++; } while (attempt < teardownRetries); return tearDown( query, postQueryResults, postQuery -> executeQuery( gateway, username, password, query, postQuery, timeout, sessionProperties)); }

Target:
private QueryResult executeTearDown( Query query, String gateway, String username, String password, Duration timeout, List<QueryResult> postQueryResults, int teardownRetries) { int attempt = 0; QueryResult tearDownResult; do { tearDownResult = tearDown(query, postQueryResults, postQuery -> executeQuery(gateway, username, password, query, postQuery, timeout, sessionProperties)); if (tearDownResult.getState() == State.SUCCESS) { break; } try { TimeUnit.MINUTES.sleep(1); log.info("Query teardown failed on attempt #%s, will sleep and retry", attempt); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } attempt++; } while (attempt < teardownRetries); return tearDown(query, postQueryResults, postQuery -> executeQuery(gateway, username, password, query, postQuery, timeout, sessionProperties)); }
Source:
public static void disableHintAnnouncement(@NonNull TextView textView) { ViewCompat.setAccessibilityDelegate(textView, new AccessibilityDelegateCompat() { @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); info.setHintText(null); } }); }

Target:
public static void disableHintAnnouncement(@NonNull TextView textView) { setAccessibilityDelegateSafely(textView, new AccessibilityDelegateCompat() { @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) { super.onInitializeAccessibilityNodeInfo(host, info); info.setHintText(null); } }); }
Source:
private void generateSourceAndSave(final ExportFile exportFile) { final Set<APTClass> exportedTypes = exportFile.exportedTypes.stream() .map(s -> new APTClass(s.asType())) .collect(toSet()); final String className = ExportFileName.encodeAnnotationNameAsExportFileName(exportFile); final String fullClassName = exportFilesPackagePath() + "." + className; final ClassStructureBuilder<?> classBuilder = ClassBuilder.define(fullClassName).publicScope().body(); exportedTypes.forEach( exportedType -> classBuilder.publicField(RandomStringUtils.randomAlphabetic(6), exportedType).finish()); try { final String generatedSource = classBuilder.toJavaString(); final Element[] originatingElements = exportFile.exportedTypes.toArray(new Element[0]); final JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(fullClassName, originatingElements); try (Writer writer = sourceFile.openWriter()) { writer.write(generatedSource); } System.out.println("Successfully generated export file [" + className + "]"); } catch (final IOException e) { throw new RuntimeException("Error writing generated export file", e); } }

Target:
private void generateSourceAndSave(final ExportFile exportFile) { try { final Element[] originatingElements = exportFile.exportedTypes.toArray(new Element[0]); final JavaFileObject sourceFile = processingEnv.getFiler() .createSourceFile(exportFile.getFullClassName(), originatingElements); try (Writer writer = sourceFile.openWriter()) { writer.write(exportFile.generateSource()); } System.out.println("Successfully generated export file [" + exportFile.simpleClassName + "]"); } catch (final IOException e) { throw new RuntimeException("Error writing generated export file", e); } }
Source:
public void saveSync(SynchronizationAlgorithm syncAlgo) throws FileNotFoundException { if (fSyncFile == null) { return; } FileChannel fc; FileOutputStream fos; ObjectOutputStream oos; ByteBuffer buffer; int res; fos = new FileOutputStream(fSyncFile, false); fc = fos.getChannel(); buffer = ByteBuffer.allocate(HEADER_SIZE); buffer.clear(); try { fc.position(0); buffer.putInt(SYNC_FILE_MAGIC_NUMBER); buffer.putInt(FILE_VERSION); buffer.flip(); res = fc.write(buffer); assert (res <= HEADER_SIZE); fc.position(HEADER_SIZE); oos = new ObjectOutputStream(fos); oos.writeObject(syncAlgo); oos.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { fc.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } return; }

Target:
public void saveSync(SynchronizationAlgorithm syncAlgo) throws FileNotFoundException { if (fSyncFile == null) { return; } FileChannel fc; FileOutputStream fos; ObjectOutputStream oos; ByteBuffer buffer; int res; fos = new FileOutputStream(fSyncFile, false); fc = fos.getChannel(); buffer = ByteBuffer.allocate(HEADER_SIZE); buffer.clear(); try { fc.position(0); buffer.putInt(SYNC_FILE_MAGIC_NUMBER); buffer.putInt(FILE_VERSION); buffer.flip(); res = fc.write(buffer); assert (res <= HEADER_SIZE); fc.position(HEADER_SIZE); oos = new ObjectOutputStream(fos); oos.writeObject(syncAlgo); oos.close(); } catch (IOException e) { Activator.logError("Error saving trace synchronization data", e); } finally { try { fc.close(); fos.close(); } catch (IOException e) { Activator.logError("Error closing synchronization file", e); } } return; }
Source:
public IKernelAnalysisEventLayout getEventLayout(ITmfTrace trace) { IKernelAnalysisEventLayout layout = LttngEventLayout.getInstance(); if (trace instanceof LttngKernelTrace) { layout = ((LttngKernelTrace) trace).getKernelEventLayout(); } return layout; }

Target:
public IKernelAnalysisEventLayout getEventLayout(ITmfTrace trace) { if (trace instanceof LttngKernelTrace) { return ((LttngKernelTrace) trace).getKernelEventLayout(); } return LttngEventLayout.getInstance(); }
Source:
public void setEmergencyNumber() throws Exception { List<ID> ids = pretendThatWeHave( new NewOperator("name1", OperatorState.ACTIVE, "description1", "domainName1", "friendlyName1", "911"), new NewOperator("name2", OperatorState.ACTIVE, "description2", "domainName2", "friendlyName2", "1234") ); NewEmergencyNumber number = new NewEmergencyNumber(ids.get(0), "112"); repository.updateEmergencyNumber(number); List<Operator> got = repository.findAll(); List<Operator> want = Lists.newArrayList( new Operator(ids.get(1), "name2", OperatorState.ACTIVE, "description2", "domainName2", "friendlyName2", "1234"), new Operator(ids.get(0), "name1", OperatorState.ACTIVE, "description1", "domainName1", "friendlyName1", "112") ); assertThat(got, deepEquals(want)); }

Target:
public void setEmergencyNumber() throws Exception { Object id1 = repository.create(new NewOperator("name1", OperatorState.ACTIVE, "description1", "domainName1", "friendlyName1", "911")); Object id2 = repository.create(new NewOperator("name2", OperatorState.ACTIVE, "description2", "domainName2", "friendlyName2", "1234")); NewEmergencyNumber number = new NewEmergencyNumber(new ID(id1), "112"); repository.updateEmergencyNumber(number); List<Operator> got = repository.findAll(); List<Operator> want = Lists.newArrayList( new Operator(new ID(id2), "name2", OperatorState.ACTIVE, "description2", "domainName2", "friendlyName2", "1234"), new Operator(new ID(id1), "name1", OperatorState.ACTIVE, "description1", "domainName1", "friendlyName1", "112") ); assertThat(got, deepEquals(want)); }
Source:
private JSONObject processSymbolizer(Symbolizer symbolizer) { JSONObject ret = new JSONObject(); String name = symbolizer.getName(); if (name != null && !name.isEmpty()) { ret.element(NAME, name); } Unit<Length> uom = symbolizer.getUnitOfMeasure(); if (uom != null) { ret.element(UOM, uom.toString()); } Description desc = symbolizer.getDescription(); if (desc != null) { InternationalString title = desc.getTitle(); if (title != null) { ret.element(TITLE, title.toString()); } InternationalString abs = desc.getAbstract(); if (abs != null) { ret.element(ABSTRACT, abs.toString()); } } Expression geometry = symbolizer.getGeometry(); if (geometry != null) { ret.element(GEOMETRY, printExpression(geometry, Geometry.class)); } if (symbolizer instanceof PointSymbolizer) { ret = processPointSymbolizer(ret, (PointSymbolizer) symbolizer); } else if (symbolizer instanceof LineSymbolizer) { ret = processLineSymbolizer(ret, (LineSymbolizer) symbolizer); } else if (symbolizer instanceof PolygonSymbolizer) { ret = processPolygonSymbolizer(ret, (PolygonSymbolizer) symbolizer); } else if (symbolizer instanceof RasterSymbolizer) { ret = processRasterSymbolizer(ret, (RasterSymbolizer) symbolizer); } else if (symbolizer instanceof TextSymbolizer) { ret = processTextSymbolizer(ret, (TextSymbolizer) symbolizer); } Map<String, String> opts = symbolizer.getOptions(); ret = processVendorOptions(ret, opts); return ret; }

Target:
private JSONObject processSymbolizer(Symbolizer symbolizer) { JSONObject ret = new JSONObject(); String name = symbolizer.getName(); if (name != null && !name.isEmpty()) { ret.element(NAME, name); } Unit<Length> uom = symbolizer.getUnitOfMeasure(); if (uom != null) { ret.element(UOM, uom.toString()); } Description desc = symbolizer.getDescription(); if (desc != null) { InternationalString title = desc.getTitle(); if (title != null) { ret.element(TITLE, title.toString()); } InternationalString abs = desc.getAbstract(); if (abs != null) { ret.element(ABSTRACT, abs.toString()); } } Expression geometry = symbolizer.getGeometry(); if (geometry != null) { ret.element(GEOMETRY, toJSONValue(geometry, Geometry.class)); } if (symbolizer instanceof PointSymbolizer) { ret = processPointSymbolizer(ret, (PointSymbolizer) symbolizer); } else if (symbolizer instanceof LineSymbolizer) { ret = processLineSymbolizer(ret, (LineSymbolizer) symbolizer); } else if (symbolizer instanceof PolygonSymbolizer) { ret = processPolygonSymbolizer(ret, (PolygonSymbolizer) symbolizer); } else if (symbolizer instanceof RasterSymbolizer) { ret = processRasterSymbolizer(ret, (RasterSymbolizer) symbolizer); } else if (symbolizer instanceof TextSymbolizer) { ret = processTextSymbolizer(ret, (TextSymbolizer) symbolizer); } else { LOGGER.warning("unknown symbolizer type " + symbolizer.getClass().getName()); } Map<String, String> opts = symbolizer.getOptions(); ret = processVendorOptions(ret, opts); return ret; }
Source:
public StyledString getStyledText(Object element) { if (element == LSSymbolsContentProvider.COMPUTING) { return new StyledString(Messages.outline_computingSymbols); } if (element instanceof Throwable) { String message = ((Throwable) element).getMessage(); if (message != null) { return new StyledString(((Throwable) element).getMessage()); } return new StyledString(); } if (element instanceof LSPDocumentInfo) { return new StyledString(((LSPDocumentInfo)element).getFileUri().getPath()); } StyledString res = new StyledString(); if (element == null){ return res; } SymbolInformation symbol = (SymbolInformation) element; res.append(symbol.getName(), null); res.append(" :", null); res.append(symbol.getKind().toString(), StyledString.DECORATIONS_STYLER); if (showLocation) { URI uri = URI.create(symbol.getLocation().getUri()); res.append(' '); res.append(uri.getPath(), StyledString.QUALIFIER_STYLER); } return res; }

Target:
public StyledString getStyledText(Object element) { if (element == LSSymbolsContentProvider.COMPUTING) { return new StyledString(Messages.outline_computingSymbols); } if (element instanceof Throwable) { String message = ((Throwable) element).getMessage(); if (message == null) { message = element.getClass().getName(); } return new StyledString(message); } if (element instanceof LSPDocumentInfo) { return new StyledString(((LSPDocumentInfo)element).getFileUri().getPath()); } StyledString res = new StyledString(); if (element == null){ return res; } SymbolInformation symbol = (SymbolInformation) element; res.append(symbol.getName(), null); res.append(" :", null); res.append(symbol.getKind().toString(), StyledString.DECORATIONS_STYLER); if (showLocation) { URI uri = URI.create(symbol.getLocation().getUri()); res.append(' '); res.append(uri.getPath(), StyledString.QUALIFIER_STYLER); } return res; }
Source:
abstract protected T convert(S object) throws TrustLevelThresholdExceededException; abstract protected Class<T> getResultClass(); @Override public List<AtomicAction<T>> build(S object) throws TrustLevelThresholdExceededException { T result = convert(object); if (result != null) { AtomicAction<T> action = new AtomicAction<>(); action.setClazz(getResultClass()); action.setPayload(result); return Arrays.asList(action); } else { return Collections.emptyList(); } }

Target:
abstract protected T convert(S object) throws TrustLevelThresholdExceededException; abstract protected Class<T> getResultClass(); @Override public List<AtomicAction<T>> build(S object) throws TrustLevelThresholdExceededException { T result = convert(object); if (result != null) { AtomicAction<T> action = new AtomicAction<>(); action.setClazz(getResultClass()); action.setPayload(result); return Collections.singletonList(action); } else { return Collections.emptyList(); } }
Source:
public void testCommandLineConverter() throws Exception { checkConverterAvailability("testCommandLineConverter"); checkCommandAvailability("pdftoimage"); BlobHolder pdfBH = getBlobFromPath("test-docs/hello.pdf"); Map<String, Serializable> parameters = new HashMap<>(); parameters.put("targetFileName", "hello.png"); BlobHolder result = cs.convert("testCommandLineConverter", pdfBH, parameters); assertNotNull(result); List<Blob> blobs = result.getBlobs(); assertNotNull(blobs); assertEquals(1, blobs.size()); Blob mainBlob = result.getBlob(); assertEquals("hello.png", mainBlob.getFilename()); FileBlob fileBlob = ((FileBlob) mainBlob); String parentPath = fileBlob.getFile().getParent(); assertTrue(parentPath, parentPath.contains("clc-pdftoimage-")); }

Target:
public void testCommandLineConverter() throws Exception { checkConverterAvailability("testCommandLineConverter"); checkCommandAvailability("pdftoimage"); BlobHolder pdfBH = getBlobFromPath("test-docs/hello.pdf"); Map<String, Serializable> parameters = new HashMap<>(); parameters.put("targetFileName", "hello.png"); BlobHolder result = cs.convert("testCommandLineConverter", pdfBH, parameters); assertNotNull(result); List<Blob> blobs = result.getBlobs(); assertNotNull(blobs); assertEquals(1, blobs.size()); Blob mainBlob = result.getBlob(); assertEquals("hello.png", mainBlob.getFilename()); File file = mainBlob.getFile(); assertNotNull(file); String parentPath = file.getParent(); assertTrue(parentPath, parentPath.contains("clc-pdftoimage-")); }
Source:
private Response processResult(Object result, URI lraId, Method method, String type) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); if (result instanceof CompletionStage) { participantStatusMap.put(lraId, Optional.empty()); ((CompletionStage<?>) result) .thenAccept(res -> participantStatusMap.replace(lraId, Optional.ofNullable(res))) .exceptionally(throwable -> { participantStatusMap.replace(lraId, Optional.ofNullable(throwable)); return null; }); return builder.status(Response.Status.ACCEPTED).build(); } if (method.getReturnType().equals(Void.TYPE)) { builder.entity(type.equals(COMPLETE) ? ParticipantStatus.Completed.name() : ParticipantStatus.Compensated.name()); } else if (result == null) { builder.status(Response.Status.NOT_FOUND); } else if (result instanceof ParticipantStatus) { builder.entity(((ParticipantStatus) result).name()); } else if (result instanceof Response) { return (Response) result; } else { throw new InvalidLRAParticipantDefinitionException( method.toGenericString() + ": invalid type of returned object: " + result.getClass()); } return builder.build(); }

Target:
private Response processResult(Object result, URI lraId, Method method, String type) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); if (result instanceof CompletionStage) { participantStatusMap.put(lraId, Optional.empty()); ((CompletionStage<?>) result) .thenAccept(res -> participantStatusMap.replace(lraId, Optional.of(res))) .exceptionally(throwable -> { participantStatusMap.replace(lraId, Optional.of(throwable)); return null; }); return builder.status(Response.Status.ACCEPTED).build(); } if (method.getReturnType().equals(Void.TYPE)) { builder.entity(type.equals(COMPLETE) ? ParticipantStatus.Completed.name() : ParticipantStatus.Compensated.name()); } else if (result == null) { builder.status(Response.Status.NOT_FOUND); } else if (result instanceof ParticipantStatus) { ParticipantStatus status = (ParticipantStatus) result; if (status == ParticipantStatus.Compensating || status == ParticipantStatus.Completing) { return builder.status(Response.Status.ACCEPTED).build(); } else { builder.entity(status.name()); } } else if (result instanceof Response) { return (Response) result; } else if (result instanceof Throwable) { builder.entity(processThrowable((Throwable) result, type)); } else { throw new IllegalStateException( method.toGenericString() + ": invalid type of returned object: " + result.getClass()); } return builder.build(); }
Source:
public void initTable() throws Exception { Connection conn = null; PreparedStatement stmt = null; try { System.out.println("TABLE_NAME = " + TABLE_NAME); conn = DriverManager.getConnection(getUrl()); String ddl; ddl = "CREATE TABLE " + TABLE_NAME + " (k VARCHAR NOT NULL PRIMARY KEY, dec DECIMAL, doub DOUBLE, fl FLOAT, inte INTEGER, lon BIGINT, smalli SMALLINT, tinyi TINYINT)"; conn.createStatement().execute(ddl); conn.commit(); } finally { closeStmtAndConn(stmt, conn); } }

Target:
public void initTable() throws Exception { Connection conn = null; PreparedStatement stmt = null; try { conn = DriverManager.getConnection(getUrl()); String ddl; ddl = "CREATE TABLE " + TABLE_NAME + " (k VARCHAR NOT NULL PRIMARY KEY, dec DECIMAL, doub DOUBLE, fl FLOAT, inte INTEGER, lon BIGINT, smalli SMALLINT, tinyi TINYINT)"; conn.createStatement().execute(ddl); conn.commit(); } finally { closeStmtAndConn(stmt, conn); } }
Source:
private String validateNewBulkBranchName(String newBranchName, Repository[] repositories) { if (StringUtils.isEmptyOrNull(newBranchName) || newBranchName.trim().isEmpty()) { return CoreText.ValidationUtils_PleaseEnterNameMessage; } for (Repository repo : repositories) { IStatus status = Utils.validateNewRefName(newBranchName, repo, Constants.R_HEADS, true); if (status.getException() != null) { Activator.handleStatus(status, false); } if (!status.isOK()) { return Activator.getDefault().getRepositoryUtil() .getRepositoryName(repo) + ": " + status.getMessage(); } } return null; }

Target:
private String validateNewBulkBranchName(String newBranchName, Repository[] repositories) { if (StringUtils.isEmptyOrNull(newBranchName) || newBranchName.trim().isEmpty()) { return UIText.CreateBranchPage_ChooseNameMessage; } for (Repository repo : repositories) { IStatus status = Utils.validateNewRefName(newBranchName, repo, Constants.R_HEADS, true); if (status.getException() != null) { Activator.handleStatus(status, false); } if (!status.isOK()) { return Activator.getDefault().getRepositoryUtil() .getRepositoryName(repo) + ": " + status.getMessage(); } } return null; }
Source:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream input = null; try { input = getClass().getClassLoader().getResourceAsStream(META_RESOURCE_IN_JAR_OVERLAY); if (input == null) { resp.sendError(404); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(input)); resp.getWriter().write(reader.readLine()); resp.flushBuffer(); } finally { if (input != null) { input.close(); } } }

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try (InputStream input = getClass().getClassLoader().getResourceAsStream(META_RESOURCE_IN_JAR_OVERLAY)) { if (input == null) { resp.sendError(404); return; } try (InputStreamReader inputReader = new InputStreamReader(input); BufferedReader reader = new BufferedReader(inputReader)) { resp.getWriter().write(reader.readLine()); resp.flushBuffer(); } } }
Source:
private void persist(LocalDocument doc) throws IOException, JsonException { logger.debug("Saving document to RemotePipeline.."); if(!remotePipeline.save(doc)) { LocalDocument ld = new LocalDocument(doc); IOException e = new IOException("Unable to save changes to core"); if(!onException(ld, e)) { logger.error("Unable to persist an error to the database for doc '" + doc.getID() + "'", e); } } }

Target:
private void persist(LocalDocument doc) throws IOException, JsonException { logger.debug("Saving document to RemotePipeline.."); if(!remotePipeline.save(doc)) { IOException e = new IOException("Unable to save changes to core"); if(!onException(doc, e)) { logger.error("Unable to persist an error to the database for doc '" + doc.getID() + "'", e); } } }
Source:
public DnsSRVResult getService(String service, String protocol, String domain) throws Exception { StringBuilder dnsQuery = new StringBuilder(); dnsQuery.append(service).append(".").append(protocol).append(".").append(domain); try { return getService(dnsQuery.toString()); } catch (Exception ex) { log.errorFormat("Error: could not find DNS SRV record name: {0}.{1}.{2}.\nExpection message is: {3}\n" + "Possible causes: missing DNS entries in the DNS server or DNS resolving" + " issues from engine-core machine.\nPlease Ensure correct DNS entries exist in the DNS server" + " and ensure the DNS server is reachable from the engine-core machine.", service, protocol, domain, ex.getMessage()); throw ex; } }

Target:
public DnsSRVResult getService(String service, String protocol, String domain) throws Exception { StringBuilder dnsQuery = new StringBuilder(); dnsQuery.append(service).append(".").append(protocol).append(".").append(domain); try { return getService(dnsQuery.toString()); } catch (Exception ex) { log.errorFormat("Error: could not find DNS SRV record name: {0}.{1}.{2}.\nException message is: {3}\n" + "Possible causes: missing DNS entries in the DNS server or DNS resolving" + " issues from engine-core machine.\nPlease Ensure correct DNS entries exist in the DNS server" + " and ensure the DNS server is reachable from the engine-core machine.", service, protocol, domain, ex.getMessage()); throw ex; } }
Source:
public Set<Locator> getExcessEnumMetrics() throws IOException { final Set<Locator> excessEnumMetrics = new HashSet<Locator>(); Function<Row<Locator, Long>, Boolean> rowFunction = new Function<Row<Locator, Long>, Boolean>() { @Override public Boolean apply(Row<Locator, Long> row) { excessEnumMetrics.add(row.getKey()); return true; } }; ColumnFamily CF = CassandraModel.CF_METRICS_EXCESS_ENUMS; Timer.Context ctx = Instrumentation.getBatchReadTimerContext(CF.getName()); try { new AllRowsReader.Builder<Locator, Long>(AstyanaxIO.getKeyspace(), CassandraModel.CF_METRICS_EXCESS_ENUMS) .withColumnRange(null, null, false, 0) .forEachRow(rowFunction) .build() .call(); } catch (ConnectionException e) { LOG.error("Error with connection to ExcessEnum Metrics Table", e); Instrumentation.markReadError(e); throw new RuntimeException(e); } catch (Exception ex) { LOG.error("Error reading ExcessEnum Metrics Table", ex); Instrumentation.markExcessEnumReadError(); throw new IOException(ex); } finally { ctx.stop(); } return excessEnumMetrics; }

Target:
public Set<Locator> getExcessEnumMetrics() throws IOException { final Set<Locator> excessEnumMetrics = new HashSet<Locator>(); Function<Row<Locator, Long>, Boolean> rowFunction = new Function<Row<Locator, Long>, Boolean>() { @Override public Boolean apply(Row<Locator, Long> row) { excessEnumMetrics.add(row.getKey()); return true; } }; ColumnFamily CF = CassandraModel.CF_METRICS_EXCESS_ENUMS; Timer.Context ctx = Instrumentation.getBatchReadTimerContext(CF.getName()); try { new AllRowsReader.Builder<Locator, Long>(AstyanaxIO.getKeyspace(), CassandraModel.CF_METRICS_EXCESS_ENUMS) .withColumnRange(null, null, false, 0) .forEachRow(rowFunction) .build() .call(); } catch (ConnectionException e) { LOG.error("Error with connection to ExcessEnum Metrics Table", e); Instrumentation.markReadError(e); Instrumentation.markExcessEnumReadError(); throw new IOException(e); } catch (Exception ex) { LOG.error("Error reading ExcessEnum Metrics Table", ex); Instrumentation.markExcessEnumReadError(); throw new IOException(ex); } finally { ctx.stop(); } return excessEnumMetrics; }
Source:
public boolean eat(GlowPlayer player, ItemStack item) { FoodLevelChangeEvent foodLevelChangeEvent = new FoodLevelChangeEvent(player, foodLevel + player.getFoodLevel()); EventFactory.callEvent(foodLevelChangeEvent); if (foodLevelChangeEvent.isCancelled()) return false; player.setFoodLevelAndSaturdation(foodLevelChangeEvent.getFoodLevel(), saturation); player.setUsageItem(null); player.setUsageTime(0); item.setAmount(item.getAmount() - 1); return true; }

Target:
public boolean eat(GlowPlayer player, ItemStack item) { PlayerItemConsumeEvent event1 = new PlayerItemConsumeEvent(player, item); EventFactory.callEvent(event1); if (event1.isCancelled()) return false; FoodLevelChangeEvent event2 = new FoodLevelChangeEvent(player, getFoodLevel(item) + player.getFoodLevel()); EventFactory.callEvent(event2); if (!event2.isCancelled()) { player.setFoodLevelAndSaturation(event2.getFoodLevel(), getSaturation(item)); } player.setUsageItem(null); player.setUsageTime(0); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { player.getInventory().clear(player.getInventory().getHeldItemSlot()); } return true; }
Source:
public String translateErrorTextSingle(String errorMsg, Boolean changeIfNotFound) { String ret = ""; try { if ((errorMsg != null) && (errorMsg.length() > 0)) { String errMsgCopy = errorMsg; if (!isDynamicVariable(errorMsg)) { errorMsg = errorMsg.replace('.', '_'); } if (errors.getString(errorMsg) != null) { ret = errors.getString(errorMsg).replace("\n", "<br/>"); } else { errorMsg = errMsgCopy; if ((isDynamicVariable(errorMsg)) || (!changeIfNotFound)) { ret = errorMsg; } else { String[] splitted = errorMsg.toLowerCase().split("_"); ret = StringHelper.join(" ", splitted); } } } } catch (MissingResourceException e) { ret = errorMsg; } return ret; }

Target:
public String translateErrorTextSingle(String errorMsg, Boolean changeIfNotFound) { String ret = ""; try { if ((errorMsg != null) && (errorMsg.length() > 0)) { String errMsgCopy = errorMsg; if (!isDynamicVariable(errorMsg)) { errorMsg = errorMsg.replace('.', '_'); } if (errors.getString(errorMsg) != null) { ret = errors.getString(errorMsg).replace("\n", "<br/>"); } else { if ((isDynamicVariable(errorMsg)) || (!changeIfNotFound)) { ret = errorMsg; } else { errorMsg = errMsgCopy; String[] splitted = errorMsg.toLowerCase().split("_"); ret = StringHelper.join(" ", splitted); } } } } catch (MissingResourceException e) { ret = errorMsg; } return ret; }
Source:
private void close(TableItem ti) { if (ti.getData() instanceof EditorReference) { int index = table.indexOf(ti); EditorReference ed = (EditorReference) ti.getData(); page.closeEditors(new IEditorReference[] { ed }, false); table.setFocus(); tableViewer.setInput(getInput(page)); if (table.getItemCount() == 0) { cancel(dialog); } if (table.isDisposed()) return; if (index > 0 && index <= table.getItemCount()) { index -= 1; } table.select(index); table.setSelection(index); } }

Target:
private void close(TableItem ti) { if (ti.getData() instanceof EditorReference) { int index = table.indexOf(ti); EditorReference ed = (EditorReference) ti.getData(); page.closeEditors(new IEditorReference[] { ed }, false); table.setFocus(); tableViewer.setInput(getInput(page)); if (table.getItemCount() == 0) { cancel(dialog); } if (table.isDisposed()) { return; } if (index > 0 && index <= table.getItemCount()) { index -= 1; } table.setSelection(index); } }
Source:
public static boolean isDateToday(String arg0){ Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); String arg1 = DateFormat.getDateInstance().format(c.getTime()); if (arg1.equals(arg0)) { return true; } return false; }

Target:
public static boolean isDateToday(String arg0){ Calendar c = Calendar.getInstance(); String arg1 = DateFormat.getDateInstance().format(c.getTime()); if (arg1.equals(arg0)) { return true; } return false; }
Source:
private static Integer shortSignedAtOffset(byte[] c, int offset) { Integer lowerByte = c[offset] & 0xFF; Integer upperByte = (int) c[offset + 1]; return (upperByte << 8) + lowerByte; }

Target:
private static int shortSignedAtOffset(byte[] c, int offset) { int lowerByte = c[offset] & 0xFF; int upperByte = (int) c[offset + 1]; return (upperByte << 8) + lowerByte; }
Source:
public void testStartsInMgmtSpecifiedDirectory() { String dir = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); shutdown(); LocalManagementContext mgmt = new LocalManagementContext(); ((BrooklynProperties)mgmt.getConfig()).put(BrooklynConfigKeys.BROOKLYN_DATA_DIR, dir); app = ApplicationBuilder.newManagedApp(TestApplication.class, mgmt); doTestSpecifiedDirectory(dir, dir); Os.tryDeleteDirectory(dir); }

Target:
public void testStartsInMgmtSpecifiedDirectory() { String dir = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); shutdown(); LocalManagementContext mgmt = new LocalManagementContext(); mgmt.getBrooklynProperties().put(BrooklynConfigKeys.BROOKLYN_DATA_DIR, dir); app = ApplicationBuilder.newManagedApp(TestApplication.class, mgmt); doTestSpecifiedDirectory(dir, dir); Os.tryDeleteDirectory(dir); }
Source:
public void authenticate(String user, String password) { String adminUser = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.name"); String adminPassword = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.password"); if (!user.equals(adminUser) || !password.equals(adminPassword)) { throw new AAAExtensionException(AAAExtensionException.AAAExtensionError.INCORRECT_CREDENTIALS, ""); } }

Target:
public void authenticate(String user, String password) { String adminUser = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.name"); String adminPassword = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.password"); if (!(user.equals(adminUser) && password.equals(adminPassword))) { throw new AAAExtensionException(AAAExtensionException.AAAExtensionError.INCORRECT_CREDENTIALS, ""); } }
Source:
public void redeployApplications(String[] appNames) throws AxisFault { try { for (String appName: appNames) { stub.redeployApplication(appName); } } catch (java.lang.Exception e) { handleException(bundle.getString("cannot.get.service.data"), e); } }

Target:
public void redeployApplications(String[] appNames) throws AxisFault { for (String appName: appNames) { try { stub.redeployApplication(appName); } catch (java.lang.Exception e) { handleException(bundle.getString("cannot.get.service.data"), e); } } }
Source:
public void minionHeartBeatTestForLastUpdated() { Date startOfTest = new Date(); InetSocketAddress pgsql = m_testEnvironment.getServiceAddress(ContainerAlias.POSTGRES, 5432); HibernateDaoFactory daoFactory = new HibernateDaoFactory(pgsql); MinionDao minionDao = daoFactory.getDao(MinionDaoHibernate.class); NodeDao nodeDao = daoFactory.getDao(NodeDaoHibernate.class); await().atMost(900, SECONDS) .pollInterval(5, SECONDS) .until(DaoUtils.countMatchingCallable(minionDao, new CriteriaBuilder(OnmsMinion.class).ge("lastUpdated", startOfTest).toCriteria()), greaterThan(0)); await().atMost(90, SECONDS) .pollInterval(5, SECONDS) .until(DaoUtils.countMatchingCallable(nodeDao, new CriteriaBuilder(OnmsNode.class).eq("foreignSource", "Minions@MINION") .eq("foreignId", "00000000-0000-0000-0000-000000ddba11") .toCriteria()), equalTo(1)); Assert.assertEquals("MINION", nodeDao.get("Minions@MINION:00000000-0000-0000-0000-000000ddba11").getLocation().getLocationName()); }

Target:
public void minionHeartBeatTestForLastUpdated() { Date startOfTest = new Date(); InetSocketAddress pgsql = m_testEnvironment.getServiceAddress(ContainerAlias.POSTGRES, 5432); HibernateDaoFactory daoFactory = new HibernateDaoFactory(pgsql); MinionDao minionDao = daoFactory.getDao(MinionDaoHibernate.class); NodeDao nodeDao = daoFactory.getDao(NodeDaoHibernate.class); await().atMost(900, SECONDS) .pollInterval(5, SECONDS) .until(DaoUtils.countMatchingCallable(minionDao, new CriteriaBuilder(OnmsMinion.class).ge("lastUpdated", startOfTest).toCriteria()), greaterThan(0)); await().atMost(90, SECONDS) .pollInterval(5, SECONDS) .until(DaoUtils.countMatchingCallable(nodeDao, new CriteriaBuilder(OnmsNode.class).eq("foreignSource", "Minions") .eq("foreignId", "00000000-0000-0000-0000-000000ddba11") .toCriteria()), equalTo(1)); Assert.assertEquals("MINION", nodeDao.get("Minions:00000000-0000-0000-0000-000000ddba11").getLocation().getLocationName()); }
Source:
public Set<Property> getProperties(String name) { Set<Property> ret = new HashSet<Property>(); for (Property property : this.properties) { if (property.getName().equals(name)) { ret.add(property); } } return ret; }

Target:
public Set<Property> getProperties(String name) { return this.properties.stream().filter(property -> property.getName().equals(name)).collect(Collectors.toSet()); }
Source:
public GetDeviceListVDSCommandParameters(Guid vdsId, StorageType storageType) { super(vdsId); setStorageType(storageType); setCheckStatus(false); }

Target:
public GetDeviceListVDSCommandParameters(Guid vdsId, StorageType storageType) { this(vdsId, storageType, false, null); }
Source:
public void saveProjects(Collection<Project> projects) throws IOException { log.info("Migrating projects..."); StudyType other = null; for (StudyType st : serviceManager.getStudyDao().listAllStudyTypes()) { if (st.getName().equals("Other")) { other = st; break; } } for (Project project : projects) { project.setSecurityProfile(new SecurityProfile(migrationUser)); valueTypeLookup.resolveAll(project); if (project.getStudies() == null) project.setStudies(new HashSet<Study>()); if (project.getStudies().isEmpty()) { Study study = new StudyImpl(); study.setAlias((project.getShortName() == null ? project.getAlias() : project.getShortName()) + " study"); study.setDescription(""); study.setStudyType(other); study.setLastModifier(migrationUser); project.getStudies().add(study); } project.setId(serviceManager.getProjectDao().save(project)); for (Study study : project.getStudies()) { study.setProject(project); study.inheritPermissions(project); study.setId(serviceManager.getStudyDao().save(study)); } log.debug("Saved project " + project.getAlias()); } log.info(projects.size() + " projects migrated."); }

Target:
public void saveProjects(Collection<Project> projects) throws IOException { log.info("Migrating projects..."); StudyType other = null; for (StudyType st : serviceManager.getStudyDao().listAllStudyTypes()) { if (st.getName().equals("Other")) { other = st; break; } } if (other == null) { throw new IllegalStateException("Cannot find “other” study type."); } for (Project project : projects) { project.setSecurityProfile(new SecurityProfile(migrationUser)); valueTypeLookup.resolveAll(project); if (project.getStudies() == null) project.setStudies(new HashSet<Study>()); if (project.getStudies().isEmpty()) { Study study = new StudyImpl(); study.setAlias((project.getShortName() == null ? project.getAlias() : project.getShortName()) + " study"); study.setDescription(""); study.setStudyType(other); study.setLastModifier(migrationUser); project.getStudies().add(study); } project.setId(serviceManager.getProjectDao().save(project)); for (Study study : project.getStudies()) { study.setProject(project); study.inheritPermissions(project); study.setId(serviceManager.getStudyDao().save(study)); } log.debug("Saved project " + project.getAlias()); } log.info(projects.size() + " projects migrated."); }
Source:
public boolean isEnableForComponent(Component invoker) { if (invoker.getName() != null && invoker.getName().equals(ParamsPanel.PANEL_NAME)) { this.paramTable = (JTable) invoker; if (paramTable.getSelectedRowCount() != 1) { this.setEnabled(false); return true; } HtmlParameterStats item = ((ParamsTableModel) paramTable.getModel()).getHtmlParameterStatsAtRow(paramTable.getSelectedRow()); if (item != null) { this.setEnabled(true); return true; } this.setEnabled(false); return true; } return false; }

Target:
public boolean isEnableForComponent(Component invoker) { if (invoker.getName() != null && invoker.getName().equals(ParamsPanel.PANEL_NAME)) { this.paramTable = (JTable) invoker; this.setEnabled(paramTable.getSelectedRowCount() == 1); return true; } return false; }
Source:
private static Map<String, String> buildClientUserAgentMap() { String[] propertyNames = {"os.name", "os.version", "os.arch", "java.version", "java.vendor", "java.vm.version", "java.vm.vendor"}; Map<String, String> clientUserAgentMap = new HashMap<>(); for (String propertyName : propertyNames) { clientUserAgentMap.put(propertyName, System.getProperty(propertyName)); } clientUserAgentMap.put("bindings.version", Stripe.VERSION); clientUserAgentMap.put("lang", "Java"); clientUserAgentMap.put("publisher", "Stripe"); if (Stripe.getAppInfo() != null) { clientUserAgentMap.put("application", ApiResource.GSON.toJson(Stripe.getAppInfo())); } Set<String> keySet = new HashSet<>(clientUserAgentMap.keySet()); for (String key: keySet) { String value = clientUserAgentMap.get(key); clientUserAgentMap.remove(key); String formattedKey = key.replace('.', '_'); clientUserAgentMap.put(formattedKey, value); } return clientUserAgentMap; }

Target:
private static Map<String, String> buildClientUserAgentMap() { String[] propertyNames = {"os.name", "os.version", "os.arch", "java.version", "java.vendor", "java.vm.version", "java.vm.vendor"}; Map<String, String> clientUserAgentMap = new HashMap<>(); for (String propertyName : propertyNames) { clientUserAgentMap.put(propertyName, System.getProperty(propertyName)); } clientUserAgentMap.put("bindings.version", Stripe.VERSION); clientUserAgentMap.put("lang", "Java"); clientUserAgentMap.put("publisher", "Stripe"); if (Stripe.getAppInfo() != null) { clientUserAgentMap.put("application", ApiResource.GSON.toJson(Stripe.getAppInfo())); } Set<String> keySet = new HashSet<>(clientUserAgentMap.keySet()); for (String key: keySet) { String value = clientUserAgentMap.get(key); String formattedKey = key.replace('.', '_'); clientUserAgentMap.remove(key); clientUserAgentMap.put(formattedKey, value); } return clientUserAgentMap; }
Source:
public List<Project> getUserProjects(User user) { ArrayList<Project> array = new ArrayList<Project>(); List<Project> projects = getProjects(); for (Project project : projects) { Permission perm = project.getUserPermission(user); if (perm != null && (perm.isPermissionSet(Type.ADMIN) || perm .isPermissionSet(Type.READ))) { array.add(project); } } return array; }

Target:
public List<Project> getUserProjects(User user) { ArrayList<Project> userProjects = new ArrayList<>(); for (Project project : getProjects()) { Permission perm = project.getUserPermission(user); if (perm != null && (perm.isPermissionSet(Type.ADMIN) || perm .isPermissionSet(Type.READ))) { userProjects.add(project); } } return userProjects; }
Source:
public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof ICalledFunction) { ICalledFunction calledFunction = (ICalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText; ISymbolProvider provider = SymbolProviderManager.getInstance().getSymbolProvider(trace); if (calledFunction.getSymbol() instanceof ITmfStateValue) { ITmfStateValue symbol = ((ITmfStateValue) calledFunction.getSymbol()); switch (symbol.getType()) { case LONG: Long longAddress = symbol.unboxLong(); symbolText = provider.getSymbolText(longAddress); if (symbolText == null) { return "0x" + Long.toHexString(longAddress); } return symbolText; case STRING: return symbol.unboxStr(); case INTEGER: Integer intAddress = symbol.unboxInt(); symbolText = provider.getSymbolText(intAddress); if (symbolText == null) { return "0x" + Integer.toHexString(intAddress); } return symbolText; case DOUBLE: case NULL: case CUSTOM: default: break; } } } } return null; }

Target:
public @Nullable Object resolve(@NonNull ISegment segment) { if (segment instanceof ICalledFunction) { ICalledFunction calledFunction = (ICalledFunction) segment; ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { String symbolText; Object symbol = calledFunction.getSymbol(); if (symbol instanceof Long) { Long longAddress = (Long)symbol; ISymbolProvider provider = SymbolProviderManager.getInstance().getSymbolProvider(trace); symbolText = provider.getSymbolText(longAddress); if (symbolText == null) { return "0x" + Long.toHexString(longAddress); } return symbolText; } return String.valueOf(symbol); } } return null; }
Source:
public Optional<String> getCurrentSuggestion() { if (currentSuggestionIndex.isPresent() && isValidSuggestionIndex()) { return Optional.of(getSuggestedLabel()); } return Optional.empty(); }

Target:
public Optional<String> getCurrentSuggestion() { if (currentSuggestionIndex.isPresent()) { assert isValidSuggestionIndex(); return Optional.of(getSuggestedLabel()); } return Optional.empty(); }
Source:
public void handle_shouldUnvoidMembersAssociatedWithThePatient() throws Exception { executeDataSet(COHORT_XML); CohortService cs = Context.getCohortService(); Cohort cohort = cs.getCohort(2); Patient patient = Context.getPatientService().getPatient(7); CohortMembership membership = new CohortMembership(patient); cs.addMembershipToCohort(cohort, membership); Assert.assertTrue(cohort.contains(patient)); patient = Context.getPatientService().voidPatient(patient, "Void Reason"); Assert.assertTrue(patient.getVoided()); Assert.assertTrue(membership.getVoided()); Assert.assertNotNull(membership.getDateVoided()); Assert.assertNotNull(membership.getVoidedBy()); Assert.assertNotNull(membership.getVoidReason()); patient.setVoided(false); User user = Context.getUserService().getUser(1); new PatientDataUnvoidHandler().handle(patient, user, patient.getDateVoided(), null); Assert.assertFalse(membership.getVoided()); Assert.assertNull(membership.getDateVoided()); Assert.assertNull(membership.getVoidedBy()); Assert.assertNull(membership.getVoidReason()); }

Target:
public void handle_shouldUnvoidMembersAssociatedWithThePatient() throws Exception { executeDataSet(COHORT_XML); CohortService cs = Context.getCohortService(); Cohort cohort = cs.getCohort(2); Patient patient = Context.getPatientService().getPatient(7); CohortMembership membership = new CohortMembership(patient.getPatientId()); cs.addMembershipToCohort(cohort, membership); Assert.assertTrue(cohort.contains(patient)); patient = Context.getPatientService().voidPatient(patient, "Void Reason"); Assert.assertTrue(patient.getVoided()); Assert.assertTrue(membership.getVoided()); Assert.assertNotNull(membership.getDateVoided()); Assert.assertNotNull(membership.getVoidedBy()); Assert.assertNotNull(membership.getVoidReason()); Context.getPatientService().unvoidPatient(patient); Assert.assertFalse(membership.getVoided()); Assert.assertNull(membership.getDateVoided()); Assert.assertNull(membership.getVoidedBy()); Assert.assertNull(membership.getVoidReason()); }
Source:
private String load(IResource resource) { IProject project = resource.getProject(); String dcName = ResourceUtils.getDeploymentConfigNameFor(resource); if (StringUtils.isEmpty(dcName)) { return null; } IDeploymentConfig dc = connection.getResource(ResourceKind.DEPLOYMENT_CONFIG, project.getName(), dcName); if (dc == null) { return null; } IDeploymentImageChangeTrigger trigger = getImageChangeTrigger(dc.getTriggers()); if (trigger == null) { return null; } DockerImageURI uri = trigger.getFrom(); return getImageStreamTag(uri, resource.getNamespace()); }

Target:
private String load(IResource resource) throws CoreException { IDeploymentConfig dc = ResourceUtils.getDeploymentConfigFor(resource, connection); if (dc == null) { return null; } IDeploymentImageChangeTrigger trigger = getImageChangeTrigger(dc.getTriggers()); if (trigger == null) { return null; } DockerImageURI uri = trigger.getFrom(); return getImageStreamTag(uri, resource.getNamespace()); }