auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void main(String args[]) { try { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); DumpDataTool dumpDataTool = new DumpDataTool(verifiableProperties); dumpDataTool.doOperation(); } catch (Exception e) { logger.error("Closed with exception ", e); } }

Target:
public static void main(String args[]) throws Exception { VerifiableProperties verifiableProperties = StoreToolsUtil.getVerifiableProperties(args); DumpDataTool dumpDataTool = new DumpDataTool(verifiableProperties); dumpDataTool.doOperation(); }
Source:
public void addResourceHandlers(ResourceHandlerRegistry registry) { int cachePeriod; if (environment.equals("development")) { cachePeriod = 0; } else { cachePeriod = 31536000; } registry .addResourceHandler(PATTERN_CSS) .addResourceLocations("/css/", "classpath:/css/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_IMG) .addResourceLocations("/img/", "classpath:/img/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_JS) .addResourceLocations("/js/", "classpath:/js/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_MOLGENIS_UI) .addResourceLocations("/ui/", "classpath:/@molgenis-ui/") .setCachePeriod(3600); registry .addResourceHandler(PATTERN_FONTS) .addResourceLocations("/fonts/", "classpath:/fonts/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_SWAGGER) .addResourceLocations("/swagger/", "classpath:/swagger/") .setCachePeriod(cachePeriod); registry .addResourceHandler("/generated-doc/**") .addResourceLocations("/generated-doc/") .setCachePeriod(3600); registry .addResourceHandler("/html/**") .addResourceLocations("/html/", "classpath:/html/") .setCachePeriod(3600); FileStore fileStore = fileStore(); registry .addResourceHandler("/" + PATH_SEGMENT_APPS + "/**") .addResourceLocations( "file:/ registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(3600) .resourceChain(true); }

Target:
public void addResourceHandlers(ResourceHandlerRegistry registry) { int cachePeriod; if (environment.equals("development")) { cachePeriod = 0; } else { cachePeriod = 31536000; } registry .addResourceHandler(PATTERN_CSS) .addResourceLocations("/css/", "classpath:/css/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_IMG) .addResourceLocations("/img/", "classpath:/img/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_JS) .addResourceLocations("/js/", "classpath:/js/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_MOLGENIS_UI) .addResourceLocations("/ui/@molgenis-ui/", "classpath:/ui/@molgenis-ui/") .setCachePeriod(3600); registry .addResourceHandler(PATTERN_FONTS) .addResourceLocations("/fonts/", "classpath:/fonts/") .setCachePeriod(cachePeriod); registry .addResourceHandler(PATTERN_SWAGGER) .addResourceLocations("/swagger/", "classpath:/swagger/") .setCachePeriod(cachePeriod); registry .addResourceHandler("/generated-doc/**") .addResourceLocations("/generated-doc/") .setCachePeriod(3600); registry .addResourceHandler("/html/**") .addResourceLocations("/html/", "classpath:/html/") .setCachePeriod(3600); FileStore fileStore = fileStore(); registry .addResourceHandler("/" + PATH_SEGMENT_APPS + "/**") .addResourceLocations( "file:/ registry .addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(3600) .resourceChain(true); }
Source:
public void receiveCollisionEvent(HorizontalCollisionEvent collisionEvent, EntityRef oreon, MinionMoveComponent moveComponent) { if (lastCollisionLocation == null) { lastCollisionLocation = collisionEvent.getLocation(); } else { if (lastCollisionLocation.getX() == collisionEvent.getLocation().getX() && lastCollisionLocation.getZ() == collisionEvent.getLocation().getZ()) { logger.info("oreon stuck"); moveComponent.target = null; oreon.saveComponent(moveComponent); abandonTask(oreon); } else { lastCollisionLocation = null; } } }

Target:
public void receiveCollisionEvent(HorizontalCollisionEvent collisionEvent, EntityRef oreon, MinionMoveComponent moveComponent) { if (lastCollisionLocation == null) { lastCollisionLocation = collisionEvent.getLocation(); } else { if (isSameCollisionLocation(lastCollisionLocation, collisionEvent.getLocation())) { logger.info("oreon stuck"); moveComponent.target = null; oreon.saveComponent(moveComponent); abandonTask(oreon); } else { lastCollisionLocation = null; } } }
Source:
public void testFetchDuringCooperativeRebalance() { buildFetcher(); subscriptions.subscribe(singleton(topicName), listener); subscriptions.assignFromSubscribed(singleton(tp0)); subscriptions.seek(tp0, 0); client.updateMetadata(initialUpdateResponse); assertEquals(1, fetcher.sendFetches()); subscriptions.assignFromSubscribed(singleton(tp0)); client.prepareResponse(fullFetchResponse(tp0, this.records, Errors.NONE, 100L, 0)); consumerClient.poll(time.timer(0)); assertFalse(fetcher.fetchedRecords().isEmpty()); }

Target:
public void testFetchDuringCooperativeRebalance() { buildFetcher(); subscriptions.subscribe(singleton(topicName), listener); subscriptions.assignFromSubscribed(singleton(tp0)); subscriptions.seek(tp0, 0); client.updateMetadata(initialUpdateResponse); assertEquals(1, fetcher.sendFetches()); subscriptions.assignFromSubscribed(singleton(tp0)); client.prepareResponse(fullFetchResponse(tp0, this.records, Errors.NONE, 100L, 0)); consumerClient.poll(time.timer(0)); Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> fetchedRecords = fetchedRecords(); assertEquals(1, fetchedRecords.size()); assertEquals(3, fetchedRecords.get(tp0).size()); }
Source:
boolean needsUpdate(LedgerMetadata metadata) throws Exception; } MetadataUpdateLoop(LedgerManager lm, long ledgerId, Supplier<LedgerMetadata> currentLocalValue, NeedsUpdatePredicate needsTransformation, Function<LedgerMetadata, LedgerMetadata> transform, BiPredicate<LedgerMetadata, LedgerMetadata> updateLocalValue) { this.lm = lm; this.ledgerId = ledgerId; this.currentLocalValue = currentLocalValue; this.needsTransformation = needsTransformation; this.transform = transform; this.updateLocalValue = updateLocalValue; this.logContext = String.format("UpdateLoop(ledgerId=%d,loopId=%s)", ledgerId, UUID.randomUUID().toString().substring(0, 8)); }

Target:
boolean needsUpdate(LedgerMetadata metadata) throws Exception; } interface MetadataTransform { LedgerMetadata transform(LedgerMetadata metadata) throws Exception; }
Source:
private void validateRemoteHosts() { try { if (getCapabilities().has("hostMachines")) { JSONArray hostMachines = getHostMachineObject(); for (Object hostMachine : hostMachines) { JSONObject hostMachineJson = ((JSONObject) hostMachine); boolean isCloud = hostMachineJson.has("isCloud"); if (isCloud) { isCloud = hostMachineJson.getBoolean("isCloud"); } String machineIP = (String) hostMachineJson.get("machineIP"); if (isCloud || InetAddress.getByName(machineIP).isReachable(5000)) { LOGGER.info("ATD is Running on " + machineIP); } else { FigletHelper.figlet("Unable to connect to Remote Host " + machineIP); throw new ConnectException(); } } } } catch (Exception e) { e.printStackTrace(); } }

Target:
private void validateRemoteHosts() { try { if (!hasHostMachines()) { return; } JSONArray hostMachines = getHostMachineObject(); for (Object hostMachine : hostMachines) { JSONObject hostMachineJson = ((JSONObject) hostMachine); boolean isCloud = hostMachineJson.has("isCloud"); if (isCloud) { isCloud = hostMachineJson.getBoolean("isCloud"); } String machineIP = (String) hostMachineJson.get("machineIP"); if (isCloud || InetAddress.getByName(machineIP).isReachable(5000)) { LOGGER.info("ATD is Running on " + machineIP); } else { FigletHelper.figlet("Unable to connect to Remote Host " + machineIP); throw new ConnectException(); } } } catch (Exception e) { throw new RuntimeException("Provide hostMachine in Caps.json for execution"); } }
Source:
public static void main(String[] args) throws IOException { logger.info("REQUEST__SHORT_NOROOT_STRING = " + generateJson(false, false, false)); logger.info("REQUEST__SHORT_NOROOT_OBJECT = " + generateJson(false, false, true)); logger.info("REQUEST__SHORT_ROOT___STRING = " + generateJson(false, true, false)); logger.info("REQUEST__SHORT_ROOT___OBJECT = " + generateJson(false, true, true)); logger.info("REQUEST__FULL__NOROOT_STRING = " + generateJson(true, false, false)); logger.info("REQUEST__FULL__NOROOT_OBJECT = " + generateJson(true, false, true)); logger.info("REQUEST__FULL__ROOT___STRING = " + generateJson(true, true, false)); logger.info("REQUEST__FULL__ROOT___OBJECT = " + generateJson(true, true, true)); }

Target:
public static void main(String[] args) throws IOException { OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__SHORT_NOROOT_STRING.json", generateJson(false, false, false)); OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__SHORT_NOROOT_OBJECT.json", generateJson(false, false, true)); OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__SHORT_ROOT___STRING.json", generateJson(false, true, false)); OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__SHORT_ROOT___OBJECT.json", generateJson(false, true, true)); OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__FULL__NOROOT_STRING.json", generateJson(true, false, false)); OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__FULL__NOROOT_OBJECT.json", generateJson(true, false, true)); OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__FULL__ROOT___STRING.json", generateJson(true, true, false)); OpenRtbJsonFactoryHelper.writeFile("openrtb-core/src/test/resources/REQUEST__FULL__ROOT___OBJECT.json", generateJson(true, true, true)); }
Source:
public synchronized int write(ByteBuffer src) throws IOException { if (!src.hasArray()) { throw new IllegalArgumentException( "NettyResponseChannel does not work with ByteBuffers that are not backed by " + "byte arrrays"); } return addToResponseBody(src); }

Target:
public synchronized int write(ByteBuffer src) throws IOException { if (!isOpen()) { throw new ClosedChannelException(); } responseMetadataFinalized.set(true); int bytesWritten = src.remaining(); for (int i = 0; i < bytesWritten; i++) { bodyBytes.write(src.get()); } return bytesWritten; }
Source:
private void initCalculations() { try { startDate = (Date) sprint.getAttributes(AtsAttributeTypes.StartDate).getExactlyOne().getValue(); endDate = (Date) sprint.getAttributes(AtsAttributeTypes.EndDate).getExactlyOne().getValue(); } catch (Exception e) { throw new OseeCoreException("Date not available in sprint %s", sprint.getName()); } numActionsCompleted = 0; workCompleted = 0; walkupCompleted = 0; numActionsCompleted = 0; numActionsStarted = 0; numActionsBacklog = 0; }

Target:
private void initCalculations() { try { startDate = adjustDate((Date) sprint.getSoleAttributeValue(AtsAttributeTypes.StartDate), false); endDate = adjustDate((Date) sprint.getSoleAttributeValue(AtsAttributeTypes.EndDate), true); } catch (Exception e) { throw new OseeCoreException("Date not available in sprint %s", sprint.getName()); } numActionsCompleted = 0; workCompleted = 0; walkupCompleted = 0; numActionsCompleted = 0; numActionsStarted = 0; numActionsBacklog = 0; }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.RAISE_STMT, ctx -> { RaiseStatement raiseStatement = (RaiseStatement) ctx.syntaxNode(); if (raiseStatement.expressions().isEmpty()) { return; } Expression raisedExpression = raiseStatement.expressions().get(0); if (!raisedExpression.type().canBeOrExtend(BASE_EXCEPTION)) { ctx.addIssue(raiseStatement, MESSAGE); return; } Symbol symbol = null; if (raisedExpression instanceof HasSymbol) { symbol = ((HasSymbol) raisedExpression).symbol(); } else if (raisedExpression.is(Tree.Kind.CALL_EXPR)) { symbol = ((CallExpression) raisedExpression).calleeSymbol(); } if (!inheritsFromBaseException(symbol)) { ctx.addIssue(raiseStatement, MESSAGE); } }); }

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.RAISE_STMT, ctx -> { RaiseStatement raiseStatement = (RaiseStatement) ctx.syntaxNode(); if (raiseStatement.expressions().isEmpty()) { return; } Expression raisedExpression = raiseStatement.expressions().get(0); if (!raisedExpression.type().canBeOrExtend(BASE_EXCEPTION)) { ctx.addIssue(raiseStatement, MESSAGE); return; } Symbol symbol = null; if (raisedExpression instanceof HasSymbol) { symbol = ((HasSymbol) raisedExpression).symbol(); } else if (raisedExpression.is(Tree.Kind.CALL_EXPR)) { symbol = ((CallExpression) raisedExpression).calleeSymbol(); } if (!mayInheritFromBaseException(symbol)) { ctx.addIssue(raiseStatement, MESSAGE); } }); }
Source:
public HorizontalChildViewHolder(View itemView) { super(itemView); mDataTextView = (TextView) itemView.findViewById(R.id.list_item_horizontal_child_textView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "Child at " + getAdapterChildPosition() + ", with parent at " + getAdapterParentPosition() + " clicked, child item is \"" + getChildListItem() + "\""); } }); }

Target:
public HorizontalChildViewHolder(View itemView) { super(itemView); mDataTextView = (TextView) itemView.findViewById(R.id.list_item_horizontal_child_textView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "Child at " + getChildAdapterPosition() + ", with parent at " + getParentAdapterPosition() + " clicked, child item is \"" + getChildListItem() + "\""); } }); }
Source:
public synchronized void handleRemoval() { final Bridge bridge; final ThingHandler handler; if ((bridge = getBridge()) == null || (handler = bridge.getHandler()) == null) { super.handleRemoval(); return; } final HomematicConfig config = bridge.getConfiguration().as(HomematicConfig.class); final boolean unpairOnDeletion = config.isUnpairOnDeletion() || config.isFactoryResetOnDeletion(); final boolean factoryResetOnDeletion = config.isFactoryResetOnDeletion(); if (unpairOnDeletion) { deviceDeletionPending = true; ((HomematicBridgeHandler) handler).deleteFromGateway(UidUtils.getHomematicAddress(thing), factoryResetOnDeletion, false, true); } else { super.handleRemoval(); } }

Target:
public synchronized void handleRemoval() { final Bridge bridge; final ThingHandler handler; if ((bridge = getBridge()) == null || (handler = bridge.getHandler()) == null) { super.handleRemoval(); return; } final HomematicConfig config = bridge.getConfiguration().as(HomematicConfig.class); final boolean factoryResetOnDeletion = config.isFactoryResetOnDeletion(); final boolean unpairOnDeletion = factoryResetOnDeletion || config.isUnpairOnDeletion(); if (unpairOnDeletion) { deviceDeletionPending = true; ((HomematicBridgeHandler) handler).deleteFromGateway(UidUtils.getHomematicAddress(thing), factoryResetOnDeletion, false, true); } else { super.handleRemoval(); } }
Source:
public void restoreStateFromViewItem(PatternflyListViewItem<HostInterfaceLineModel> originalViewItem) { super.restoreStateFromViewItem(originalViewItem); if (originalViewItem instanceof HostNetworkInterfaceBondedListViewItem) { HostNetworkInterfaceBondedListViewItem original = (HostNetworkInterfaceBondedListViewItem) originalViewItem; setSlavesExpanded(original.getSlavesState()); } }

Target:
public void restoreStateFromViewItem(PatternflyListViewItem<HostInterfaceLineModel> originalViewItem) { super.restoreStateFromViewItem(originalViewItem); if (originalViewItem instanceof HostNetworkInterfaceBondedListViewItem) { setSlavesExpanded(((HostNetworkInterfaceBondedListViewItem) originalViewItem).getSlavesState()); } }
Source:
public void dispose() { if (disposed) { throw new IllegalStateException("Attempt to invoke ApplicationInstance.dispose() on disposed instance."); } try { if (defaultWindow != null) { defaultWindow.doDispose(); defaultWindow.register(null); } synchronized (taskQueueMap) { taskQueueMap.clear(); } } finally { synchronized(disposed) { disposed = true; } } }

Target:
public void dispose() { if (disposed) { throw new IllegalStateException("Attempt to invoke ApplicationInstance.dispose() on disposed instance."); } try { if (defaultWindow != null) { defaultWindow.doDispose(); defaultWindow.register(null); } synchronized (taskQueueMap) { taskQueueMap.clear(); } } finally { disposed = true; } }
Source:
public final void throwsExceptionOnActinOnUnproperMethod() throws IOException { final String proper = RandomStringUtils.random(10); String unproper; do { unproper = RandomStringUtils.random(10); } while (unproper.equals(proper)); new TkMethods( Mockito.mock(Take.class), proper ).act( new RqFake(unproper) ); }

Target:
public void throwsExceptionOnActinOnUnproperMethod() throws IOException { new TkMethods(Mockito.mock(Take.class), "PROPER").act( new RqFake("UNPROPER") ); }
Source:
void stopPresenting() { if (observable != null) { observable.detachObservers(); } if (humanTpService != null) { humanTpService.disconnect(); } }

Target:
void stopPresenting() { unsubscribe(observable); humanTpService.disconnect(); }
Source:
public TableManager(Config config) { new JavaTableConfig(config).getTableIds().forEach(tableId -> { addTable(tableId, config); logger.info("Added table " + tableId); }); }

Target:
public TableManager(Config config) { new JavaTableConfig(config).getTableIds().forEach(tableId -> { addTable(tableId, config); logger.debug("Added table " + tableId); }); logger.info(String.format("Added %d tables", tableContexts.size())); }
Source:
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (unsafeParamNames.isEmpty() || !SAFE_ARG_OF.matches(tree, state)) { return Description.NO_MATCH; } List<? extends ExpressionTree> args = tree.getArguments(); ExpressionTree argNameExpression = args.get(0); if (compileTimeConstExpressionMatcher.matches(argNameExpression, state)) { String argName = (String) ((JCTree.JCLiteral) argNameExpression).getValue(); if (unsafeParamNames.stream().anyMatch(unsafeArgName -> unsafeArgName.equalsIgnoreCase(argName))) { return buildDescription(tree) .setMessage("Arguments with name '" + argName + "' must be marked as unsafe.") .addFix(SuggestedFix.builder() .replace(tree.getMethodSelect(), "UnsafeArg.of") .addImport("com.palantir.logsafe.UnsafeArg") .build()) .build(); } } return Description.NO_MATCH; }

Target:
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (unsafeParamNames.isEmpty() || !SAFE_ARG_OF.matches(tree, state)) { return Description.NO_MATCH; } List<? extends ExpressionTree> args = tree.getArguments(); ExpressionTree argNameExpression = args.get(0); if (compileTimeConstExpressionMatcher.matches(argNameExpression, state)) { String argName = (String) ((JCTree.JCLiteral) argNameExpression).getValue(); if (unsafeParamNames.stream().anyMatch(unsafeArgName -> unsafeArgName.equalsIgnoreCase(argName))) { SuggestedFix.Builder builder = SuggestedFix.builder(); String unsafeArg = SuggestedFixes.qualifyType(state, builder, "com.palantir.logsafe.UnsafeArg"); return buildDescription(tree) .setMessage("Arguments with name '" + argName + "' must be marked as unsafe.") .addFix(builder.replace(tree.getMethodSelect(), unsafeArg + ".of") .build()) .build(); } } return Description.NO_MATCH; }
Source:
@Override public void printLastErrors() { kernal.context().exceptionRegistry().printErrors(log); }

Target:
@Override public void printLastErrors() { kernal.printLastErrors(); }
Source:
public Set<EClass> getSubTypesTopIntersection(EClass eCls1, EClass eCls2) { final Set<EClass> result = new LinkedHashSet<EClass>(); final Set<EClass> subTypes1 = queryEnvironment.getEPackageProvider().getAllSubTypes(eCls1); final Set<EClass> subTypes2 = queryEnvironment.getEPackageProvider().getAllSubTypes(eCls2); final Set<EClass> intersection = new LinkedHashSet<EClass>(); for (EClass subType1 : subTypes1) { if (subTypes2.contains(subType1)) { intersection.add(subType1); } } for (EClass eCls : intersection) { boolean isTopEClass = true; for (EClass superECls : eCls.getEAllSuperTypes()) { if (intersection.contains(superECls)) { isTopEClass = false; break; } } if (isTopEClass) { result.add(eCls); } } return result; }

Target:
public Set<EClass> getSubTypesTopIntersection(EClass eCls1, EClass eCls2) { final Set<EClass> result = new LinkedHashSet<EClass>(); final Set<EClass> subTypes1 = queryEnvironment.getEPackageProvider().getAllSubTypes(eCls1); final Set<EClass> subTypes2 = queryEnvironment.getEPackageProvider().getAllSubTypes(eCls2); final Set<EClass> intersection = Sets.intersection(subTypes1, subTypes2); for (EClass eCls : intersection) { final boolean isTopEClass = Collections.disjoint(eCls.getEAllSuperTypes(), intersection); if (isTopEClass) { result.add(eCls); } } return result; }
Source:
public boolean isPemFilePresent() { if (pemFile.isPresent()) { Path path = pemFile.get(); if (Files.isRegularFile(path) && Files.isReadable(path)) { return true; } } return false; }

Target:
public boolean isPemFilePresent() { return pemFile.isPresent(); }
Source:
void removeConsumer(EventConsumer consumer) { for (RegisteredConsumer cons : consumers) { if (cons.getConsumer().equals(consumer)) { this.consumers.remove(cons); return; } } }

Target:
void removeConsumer(EventConsumer consumer) { consumers.removeIf( registeredConsumer -> registeredConsumer.getConsumer().equals(consumer)); }
Source:
public ResponseEntity checkFileFormat(MultipartFile file,String fileHeaderMappring) { ResponseEntity response = null; RestReponseDTO responseDTO = new RestReponseDTO(); String finalMsg = null; if (file != null && file.getSize() > 0) { String fileNm = file.getOriginalFilename(); if (fileNm != null && fileNm.endsWith(".csv")) { String line; BufferedReader reader; InputStream is; try { is = file.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(fileHeaderMappring).withFirstRecordAsHeader().withTrim(); CSVParser csvParser = new CSVParser(reader, csvFileFormat); csvParser.parse(reader, csvFileFormat); } catch (Exception e) { finalMsg = ErrorConstants.ERR_NOT_CSV_FILE + ":The file format is not supported, please use correct CSV file, like *.csv "; responseDTO.setMessage(finalMsg); response = new ResponseEntity(responseDTO, org.springframework.http.HttpStatus.BAD_REQUEST); } } else { finalMsg = ErrorConstants.ERR_NOT_CSV_FILE + ":The file format is not supported, please use correct CSV file, like *.csv "; responseDTO.setMessage(finalMsg); response = new ResponseEntity(responseDTO, org.springframework.http.HttpStatus.BAD_REQUEST); } } else { finalMsg = ErrorConstants.ERR_BLANK_FILE + ":The file null or blank"; responseDTO.setMessage(finalMsg); response = new ResponseEntity(responseDTO, org.springframework.http.HttpStatus.BAD_REQUEST); } return response; }

Target:
public void checkFileFormat(MultipartFile file, String fileHeaderMappring) { ResponseEntity response = null; RestReponseDTO responseDTO = new RestReponseDTO(); String finalMsg = null; if (file != null && file.getSize() > 0) { String fileNm = file.getOriginalFilename(); if (fileNm != null && fileNm.endsWith(".csv")) { String line; BufferedReader reader; InputStream is; try { is = file.getInputStream(); reader = new BufferedReader(new InputStreamReader(is)); CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(fileHeaderMappring).withFirstRecordAsHeader().withTrim(); CSVParser csvParser = new CSVParser(reader, csvFileFormat); csvParser.parse(reader, csvFileFormat); } catch (Exception e) { throw new OpenClinicaSystemException(ErrorConstants.ERR_NOT_CSV_FILE); } } else { throw new OpenClinicaSystemException(ErrorConstants.ERR_NOT_CSV_FILE); } } else { throw new OpenClinicaSystemException(ErrorConstants.ERR_BLANK_FILE); } }
Source:
private void applyUpdate() throws IOException, ErrnoException { Slog.i(TAG, "Applying SELinux policy"); File backup = new File(updateDir.getParentFile(), "backup"); File current = new File(updateDir.getParentFile(), "current"); File tmp = new File(updateDir.getParentFile(), "tmp"); if (current.exists()) { deleteRecursive(backup); Os.rename(current.getPath(), backup.getPath()); } Os.rename(tmp.getPath(), current.getPath()); SystemProperties.set("selinux.reload_policy", "1"); }

Target:
private void applyUpdate() throws IOException, ErrnoException { Slog.i(TAG, "Applying SELinux policy"); File backup = new File(updateDir.getParentFile(), "backup"); File current = new File(updateDir.getParentFile(), "current"); File tmp = new File(updateDir.getParentFile(), "tmp"); if (current.exists()) { deleteRecursive(backup); Os.rename(current.getPath(), backup.getPath()); } try { Os.rename(tmp.getPath(), current.getPath()); SystemProperties.set("selinux.reload_policy", "1"); } catch (ErrnoException e) { Slog.e(TAG, "Could not update selinux policy: ", e); if (backup.exists()) { Os.rename(backup.getPath(), current.getPath()); } } }
Source:
public void setConnectionId(String connectionId) { setAsString(AtomXPath.id, connectionId); }

Target:
public void setConnectionId(String connectionId) { super.setId(connectionId); }
Source:
ServiceBusSessionReceiverClient(ServiceBusSessionReceiverAsyncClient asyncClient, Duration operationTimeout) { this.sessionAsyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = Objects.requireNonNull(operationTimeout, "'operationTimeout' cannot be null."); }

Target:
ServiceBusSessionReceiverClient(ServiceBusSessionReceiverAsyncClient asyncClient, Duration operationTimeout) { this.sessionAsyncClient = Objects.requireNonNull(asyncClient, "'asyncClient' cannot be null."); this.operationTimeout = operationTimeout; }
Source:
protected void configure(Host hc, Session session) { SshUriProperties sshProperties = sshKeysByHostname.get(hc.getHostName()); String hostKeyAlgorithm = sshProperties.getHostKeyAlgorithm(); if (hostKeyAlgorithm != null) { session.setConfig("server_host_key", hostKeyAlgorithm); } if (sshProperties.getHostKey() == null || !sshProperties.isStrictHostKeyChecking()) { session.setConfig("StrictHostKeyChecking", "no"); } else { session.setConfig("StrictHostKeyChecking", "yes"); } }

Target:
protected void configure(Host hc, Session session) { SshUri sshProperties = sshKeysByHostname.get(hc.getHostName()); String hostKeyAlgorithm = sshProperties.getHostKeyAlgorithm(); if (hostKeyAlgorithm != null) { session.setConfig(SERVER_HOST_KEY, hostKeyAlgorithm); } if (sshProperties.getHostKey() == null || !sshProperties.isStrictHostKeyChecking()) { session.setConfig(STRICT_HOST_KEY_CHECKING, NO_OPTION); } else { session.setConfig(STRICT_HOST_KEY_CHECKING, YES_OPTION); } }
Source:
public void textWithSingleQuote() throws Exception { FreeStyleProject upstream = r.createFreeStyleProject("upstream"); r.createFreeStyleProject("d0wnstr3'am"); upstream.getPublishersList().add(new BuildTrigger("d0wnstr3'am", Result.SUCCESS)); FreeStyleBuild b = r.buildAndAssertSuccess(upstream); r.waitUntilNoActivity(); HtmlPage rsp = r.createWebClient().goTo(b.getUrl()+"console"); System.out.println("Before:\n"+rsp.getWebResponse().getContentAsString()+"\n\n"); try { assertThat(String.valueOf(rsp.getAnchorByText("d0wnstr3'am").click().getWebResponse().getStatusCode()), containsString("200")); } catch(Exception enfe) { String str = "str->\n"; str += rsp.getWebResponse().getContentAsString()+"\n\n"; for(HtmlAnchor ha: rsp.getAnchors()) { str += "getNameAttribute: " + ha.getNameAttribute() + " getTextContent: " + ha.getTextContent() + "\n"; } throw new Exception(str); } }

Target:
public void textWithSingleQuote() throws Exception { FreeStyleProject upstream = r.createFreeStyleProject("upstream"); r.createFreeStyleProject("d0wnstr3'am"); upstream.getPublishersList().add(new BuildTrigger("d0wnstr3'am", Result.SUCCESS)); FreeStyleBuild b = r.buildAndAssertSuccess(upstream); r.waitUntilNoActivity(); HtmlPage rsp = r.createWebClient().goTo(b.getUrl()+"console"); assertThat(String.valueOf(rsp.getAnchorByText("d0wnstr3'am").click().getWebResponse().getStatusCode()), containsString("200")); }
Source:
public void queue( TileCanvasViewGroup tileCanvasViewGroup, Set<Tile> renderSet ) { mTileCanvasViewGroupWeakReference = new WeakReference<>( tileCanvasViewGroup ); mHandler.setTileCanvasViewGroup( tileCanvasViewGroup ); tileCanvasViewGroup.onRenderTaskPreExecute(); for( Runnable runnable : getQueue() ) { if( runnable instanceof TileRenderRunnable ) { TileRenderRunnable tileRenderRunnable = (TileRenderRunnable) runnable; if( tileRenderRunnable.isDone() || tileRenderRunnable.isCancelled() ) { continue; } Tile tile = tileRenderRunnable.getTile(); if( tile != null && !renderSet.contains( tile ) ) { tile.reset(); } } } for( Tile tile : renderSet ) { if( isShutdownOrTerminating() ) { return; } tile.execute( this, tileCanvasViewGroup.getBitmapCleanup()); } }

Target:
public void queue( TileCanvasViewGroup tileCanvasViewGroup, Set<Tile> renderSet ) { mTileCanvasViewGroupWeakReference = new WeakReference<>( tileCanvasViewGroup ); mHandler.setTileCanvasViewGroup( tileCanvasViewGroup ); tileCanvasViewGroup.onRenderTaskPreExecute(); for( Runnable runnable : getQueue() ) { if( runnable instanceof TileRenderRunnable ) { TileRenderRunnable tileRenderRunnable = (TileRenderRunnable) runnable; if( tileRenderRunnable.isDone() || tileRenderRunnable.isCancelled() ) { continue; } Tile tile = tileRenderRunnable.getTile(); if( tile != null && !renderSet.contains( tile ) ) { tile.reset(); } } } for( Tile tile : renderSet ) { if( isShutdownOrTerminating() ) { return; } tile.execute( this, tileCanvasViewGroup.getBitmapRecycler() ); } }
Source:
public void testRouterClosedDuringOperation() throws Exception { testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, RouterErrorCode.RouterClosed, new ErrorCodeChecker() { @Override public void check(RouterErrorCode expectedError) throws Exception { future = router.deleteBlob(blobIdString, new ClientCallback()); router.close(); checkErrorCode(future, expectedError); } }); }

Target:
public void testRouterClosedDuringOperation() throws Exception { testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, RouterErrorCode.RouterClosed, new ErrorCodeChecker() { @Override public void testAndAssert(RouterErrorCode expectedError) throws Exception { future = router.deleteBlob(blobIdString); router.close(); assertFailureAndCheckErrorCode(future, expectedError); } }); }
Source:
private void waitForInputTransformers() throws InterruptedException { final String propertyId = "id"; Set<String> propertyValues = new HashSet<>(inputTransformerIds.getTransformerIds()); if (propertyValues.isEmpty()) { return; } long lastChecked = new Date().getTime(); long end = lastChecked + transformerWaitTimeoutMillis; for (; ; ) { if (configDeleted.get()) { throw new IllegalStateException(); } for (ServiceReference serviceReference : inputTransformers) { Object propertyValue = serviceReference.getProperty(propertyId); if (propertyValue instanceof String) { propertyValues.remove(propertyValue); LOGGER.debug("Remaining property values {}", propertyValues); } } if (propertyValues.isEmpty()) { LOGGER.trace("Finished finding all InputTransformers"); break; } if (lastChecked >= end) { LOGGER.warn( "Not all input transformers were found, starting up CDM route anyways. Ingested resources may not have expected metadata"); break; } else { LOGGER.trace( "Waiting seconds before checking InputTransformers again", TimeUnit.MILLISECONDS.toSeconds(transformerCheckPeriodMillis)); lastChecked += transformerCheckPeriodMillis; lock.wait(transformerCheckPeriodMillis); } } }

Target:
private void waitForInputTransformers() throws InterruptedException { Set<String> configuredInputTransformers = inputTransformerIds.getIds(); if (configuredInputTransformers.isEmpty()) { return; } Set<String> requiredInputTransformers = new HashSet<>(configuredInputTransformers); long lastChecked = System.currentTimeMillis(); long end = lastChecked + transformerWaitTimeoutMillis; LOGGER.trace( "Beginning wait for InputTransformers for seconds", TimeUnit.MILLISECONDS.toSeconds(transformerWaitTimeoutMillis)); for (; ; ) { for (ServiceReference serviceReference : inputTransformers) { Object propertyValue = serviceReference.getProperty(TRANSFORMER_ID_PROPERTY); if (propertyValue instanceof String) { requiredInputTransformers.remove(propertyValue); LOGGER.debug("Remaining property values {}", requiredInputTransformers); } } if (requiredInputTransformers.isEmpty()) { LOGGER.trace("Finished finding all InputTransformers"); break; } if (lastChecked >= end) { throw new IllegalArgumentException( String.format( "Not all expected Input Transformers were found within %s seconds. Expected: %s, but didn't find: %s. " + "CDMs will not be able to start without all required InputTransformers. Either remove the un-found " + "IDs from the InputTransformer ID JSON files under etc/transformers, or ensure the bundle providing " + "the missing InputTransformer is started.", TimeUnit.MILLISECONDS.toSeconds(transformerWaitTimeoutMillis), configuredInputTransformers, requiredInputTransformers)); } else { LOGGER.trace( "Waiting seconds before checking InputTransformers again", TimeUnit.MILLISECONDS.toSeconds(transformerCheckPeriodMillis)); lastChecked += transformerCheckPeriodMillis; synchronized (lock) { lock.wait(transformerCheckPeriodMillis); } } } }
Source:
public static IProject[] getValidOpenProjects(Repository repository) throws CoreException { final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); List<IProject> result = new ArrayList<IProject>(); final Path repositoryPath = new Path( repository.getWorkTree().getAbsolutePath()); for (IProject p : projects) { IPath projectLocation = p.getLocation(); if (!p.isOpen() || projectLocation == null) continue; IPath projectFilePath = projectLocation .append(IProjectDescription.DESCRIPTION_FILE_NAME); if (projectFilePath.toFile().exists()) { if (repositoryPath.isPrefixOf(projectLocation)) { result.add(p); } } } return result.toArray(new IProject[result.size()]); }

Target:
public static IProject[] getValidOpenProjects(Repository repository) throws CoreException { final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); List<IProject> result = new ArrayList<IProject>(); final Path repositoryPath = new Path( repository.getWorkTree().getAbsolutePath()); for (IProject p : projects) { IPath projectLocation = p.getLocation(); if (!p.isOpen() || projectLocation == null || repositoryPath.isPrefixOf(projectLocation)) continue; IPath projectFilePath = projectLocation .append(IProjectDescription.DESCRIPTION_FILE_NAME); if (projectFilePath.toFile().exists()) { result.add(p); } } return result.toArray(new IProject[result.size()]); }
Source:
private AsyncHttpClient createHttpClient() { final AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder(); try { builder.setMaxConnectionsPerHost(-1); builder.setSSLContext(SslUtils.getInstance().getSSLContext(false)); } catch (GeneralSecurityException e) { e.printStackTrace(); } finally { return new AsyncHttpClient(builder.build()); } }

Target:
private AsyncHttpClient createHttpClient() throws KeyManagementException, NoSuchAlgorithmException { final AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder(); builder.setMaxConnectionsPerHost(-1); builder.setSSLContext(SslUtils.getInstance().getSSLContext()); return new AsyncHttpClient(builder.build()); }
Source:
public void canSaveAndRetrieveDataStoredInRedis() { UserClient client = testUser.getSession().getUserClient(); UserProfile profile = client.getProfile(); profile.setFirstName("☃"); profile.setLastName("지구상의 ３대 극지라 불리는"); client.saveProfile(profile); testUser.getSession().signOut(); Session session = ClientProvider.signIn(new SignInCredentials(testUser.getEmail(), testUser.getPassword())); profile = session.getUserClient().getProfile(); assertEquals("☃", profile.getFirstName()); assertEquals("지구상의 ３대 극지라 불리는", profile.getLastName()); }

Target:
public void canSaveAndRetrieveDataStoredInRedis() { TestUser testUser = TestUserHelper.createAndSignInUser(UTF8Test.class, true); try { UserClient client = testUser.getSession().getUserClient(); UserProfile profile = client.getProfile(); profile.setFirstName("☃"); profile.setLastName("지구상의 ３대 극지라 불리는"); client.saveProfile(profile); testUser.getSession().signOut(); Session session = ClientProvider.signIn(new SignInCredentials(testUser.getEmail(), testUser.getPassword())); profile = session.getUserClient().getProfile(); assertEquals("☃", profile.getFirstName()); assertEquals("지구상의 ３대 극지라 불리는", profile.getLastName()); } finally { testUser.signOutAndDeleteUser(); } }
Source:
public int getTop(final ViewGroup ancestor, View view){ if (view==ancestor){ return 0; } else { int top = view.getTop(); if (ViewGroup.class.isAssignableFrom(view.getParent().getClass())){ top += getTop(ancestor, (ViewGroup) view.getParent()); } else { Log.i("DataInteraction","giving up calculating the top"); } return top; } }

Target:
public int getTop(final ViewGroup ancestor, View view){ if (view == ancestor){ return 0; } else { int top = view.getTop(); if (ViewGroup.class.isAssignableFrom(view.getParent().getClass())){ top += getTop(ancestor, (ViewGroup) view.getParent()); } else { Log.i(TAG, "giving up calculating the top"); } return top; } }
Source:
public QueryableDruidServer pick() { synchronized (this) { TreeMap<Integer, Set<QueryableDruidServer>> prioritzedServers = Maps.newTreeMap(); for (QueryableDruidServer server : servers) { Set<QueryableDruidServer> theServers = prioritzedServers.get(server.getServer().getPriority()); if (theServers == null) { theServers = Sets.newHashSet(); prioritzedServers.put(server.getServer().getPriority(), theServers); } theServers.add(server); } final Set<QueryableDruidServer> highestPriorityServers = prioritzedServers.pollLastEntry().getValue(); final int size = highestPriorityServers.size(); switch (size) { case 0: return null; case 1: return highestPriorityServers.iterator().next(); default: return strategy.pick(highestPriorityServers); } } }

Target:
public QueryableDruidServer pick() { synchronized (this) { TreeMap<Integer, Set<QueryableDruidServer>> prioritizedServers = Maps.newTreeMap(); for (QueryableDruidServer server : servers) { Set<QueryableDruidServer> theServers = prioritizedServers.get(server.getServer().getPriority()); if (theServers == null) { theServers = Sets.newHashSet(); prioritizedServers.put(server.getServer().getPriority(), theServers); } theServers.add(server); } return strategy.pick(prioritizedServers, segment); } }
Source:
public void selectsMultipleOnSingleSelectTree() throws Exception { try { tree.select(1, 2, 3); fail("Expecting an exception"); } catch (Exception e) { assertEquals("Tree does not support SWT.MULTI, cannot make multiple selections.", e.getMessage()); } }

Target:
public void selectsMultipleOnSingleSelectTree() throws Exception { try { tree.select(1, 2, 3); fail("Expecting an exception"); } catch (Exception e) { assertEquals("Tree does not support SWT.MULTI, cannot make multiple selections.", e.getMessage()); } try { tree.select("Node 2", "Node 4"); fail("Expecting an exception"); } catch (Exception e) { assertEquals("Tree does not support SWT.MULTI, cannot make multiple selections.", e.getMessage()); } }
Source:
public AuthenticationConfiguration useMaskedPassword(MaskedPassword password) throws NoSuchAlgorithmException, InvalidKeySpecException { final PasswordFactory passwordFactory = PasswordFactory.getInstance(password.getAlgorithm()); final ClearPasswordSpec spec = passwordFactory.getKeySpec(password, ClearPasswordSpec.class); final char[] clearPassword = spec.getEncodedPassword(); PasswordFactory factory = PasswordFactory.getInstance(ClearPassword.ALGORITHM_CLEAR); Password finalPassword = factory.generatePassword(new ClearPasswordSpec(clearPassword)).castAs(ClearPassword.class); final CredentialSource filtered = getCredentialSource().without(PasswordCredential.class); return finalPassword == null ? useCredentials(filtered) : useCredentials(filtered).useCredential(new PasswordCredential(finalPassword)); }

Target:
public AuthenticationConfiguration useMaskedPassword(MaskedPassword password) throws NoSuchAlgorithmException, InvalidKeySpecException { Assert.assertNotNull(password); final PasswordFactory passwordFactory = PasswordFactory.getInstance(password.getAlgorithm()); final ClearPasswordSpec spec = passwordFactory.getKeySpec(password, ClearPasswordSpec.class); final char[] clearPassword = spec.getEncodedPassword(); PasswordFactory factory = PasswordFactory.getInstance(ClearPassword.ALGORITHM_CLEAR); Password finalPassword = factory.generatePassword(new ClearPasswordSpec(clearPassword)).castAs(ClearPassword.class); final CredentialSource filtered = getCredentialSource().without(PasswordCredential.class); return finalPassword == null ? useCredentials(filtered) : useCredentials(filtered).useCredential(new PasswordCredential(finalPassword)); }
Source:
public void poll() { if (vdsManager.isMonitoringNeeded()) { VmsListFetcher fetcher = getVmsFetcher(); long fetchTime = System.nanoTime(); if (fetcher.fetch()) { processDevices(fetcher); getVmsMonitoring(fetcher, fetchTime).perform(); } else { log.info("Failed to fetch vms info for host '{}' - skipping VMs monitoring.", vdsManager.getVdsName()); } } }

Target:
public void poll() { if (vdsManager.isMonitoringNeeded()) { VmsListFetcher fetcher = getVmsFetcher(); long fetchTime = System.nanoTime(); if (fetcher.fetch()) { getVmsMonitoring(fetcher, fetchTime).perform(); processDevices(fetcher.getVdsmVms().stream().map(VmInternalData::getVmDynamic), fetchTime); } else { log.info("Failed to fetch vms info for host '{}' - skipping VMs monitoring.", vdsManager.getVdsName()); } } }
Source:
private void proxy(Request request, Writer writer, HttpServletResponse response) throws IOException { if (!enabled) { writer.write(""); return; } try { final String data = executor.execute(request).handleResponse(res -> { final StatusLine status = res.getStatusLine(); HttpEntity entity = res.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } response.setStatus(status.getStatusCode()); final InputStreamReader reader = new InputStreamReader(entity.getContent()); return CharStreams.toString(reader); }); response.setContentType("application/json"); writer.write(data); } catch (IOException e) { log.warn("I/O error while calling KairosDB: {}", e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_GATEWAY); } }

Target:
private void proxy(Request request, Writer writer, HttpServletResponse response) throws IOException { if (!enabled) { writer.write(""); return; } try { final String data = executor.execute(request).handleResponse(res -> { final StatusLine status = res.getStatusLine(); HttpEntity entity = res.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } response.setStatus(status.getStatusCode()); Arrays.stream(res.getAllHeaders()).forEach(h -> response.setHeader(h.getName(), h.getValue())); final InputStreamReader reader = new InputStreamReader(entity.getContent()); return CharStreams.toString(reader); }); response.setContentType("application/json"); writer.write(data); } catch (IOException e) { log.warn("I/O error while calling KairosDB: {}", e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_GATEWAY); } }
Source:
private String getMethodName(MethodInvocationTree mit) { if (mit.methodSelect().is(Tree.Kind.MEMBER_SELECT)) { return ((MemberSelectExpressionTree) mit.methodSelect()).identifier().name(); } return ((IdentifierTree) mit.methodSelect()).name(); }

Target:
private String getMethodName(MethodInvocationTree mit) { ExpressionTree methodSelect = mit.methodSelect(); if (methodSelect.is(Tree.Kind.MEMBER_SELECT)) { return ((MemberSelectExpressionTree) methodSelect).identifier().name(); } return ((IdentifierTree) methodSelect).name(); }
Source:
public KafkaTransportProvider(DatastreamTask datastreamTask, List<KafkaProducerWrapper<byte[], byte[]>> producers, Properties props, String metricsNamesPrefix) { org.apache.commons.lang.Validate.notNull(datastreamTask, "null tasks"); org.apache.commons.lang.Validate.notNull(producers, "null producer wrappers"); _producers = producers; _datastreamTask = datastreamTask; LOG.info("Creating kafka transport provider with properties: {}", props); if (!props.containsKey(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) { String errorMessage = "Bootstrap servers are not set"; ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, null); } _preserveSourceEventTimestamp = Boolean.TRUE.toString().equals(datastreamTask.getDatastreams().get(0).getMetadata() .getOrDefault(DatastreamMetadataConstants.PRESERVE_EVENT_SOURCE_TIMESTAMP, Boolean.FALSE.toString())); _dynamicMetricsManager = DynamicMetricsManager.getInstance(); _metricsNamesPrefix = metricsNamesPrefix == null ? CLASS_NAME : metricsNamesPrefix + CLASS_NAME; _eventWriteRate = new Meter(); _eventByteWriteRate = new Meter(); _eventTransportErrorRate = new Meter(); }

Target:
public KafkaTransportProvider(DatastreamTask datastreamTask, List<KafkaProducerWrapper<byte[], byte[]>> producers, Properties props, String metricsNamesPrefix) { org.apache.commons.lang.Validate.notNull(datastreamTask, "null tasks"); org.apache.commons.lang.Validate.notNull(producers, "null producer wrappers"); _producers = producers; _datastreamTask = datastreamTask; LOG.info("Creating kafka transport provider with properties: {}", props); if (!props.containsKey(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG)) { String errorMessage = "Bootstrap servers are not set"; ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, null); } _preserveEventSourceTimestamp = Boolean.parseBoolean(datastreamTask.getDatastreams().get(0).getMetadata() .getOrDefault(DatastreamMetadataConstants.PRESERVE_EVENT_SOURCE_TIMESTAMP, Boolean.FALSE.toString())); _dynamicMetricsManager = DynamicMetricsManager.getInstance(); _metricsNamesPrefix = metricsNamesPrefix == null ? CLASS_NAME : metricsNamesPrefix + CLASS_NAME; _eventWriteRate = new Meter(); _eventByteWriteRate = new Meter(); _eventTransportErrorRate = new Meter(); }
Source:
private static synchronized RealmCache getCache(String realmPath, boolean createIfNotExist) { RealmCache cacheToReturn = null; Iterator<Map.Entry<String, WeakReference<RealmCache>>> it = cachesMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, WeakReference<RealmCache>> entry = it.next(); RealmCache cache = entry.getValue().get(); if (cache == null) { it.remove(); } else if (entry.getKey().equals(realmPath)) { cacheToReturn = cache; } } if (cacheToReturn == null && createIfNotExist) { cacheToReturn = new RealmCache(); cachesMap.put(realmPath, new WeakReference<RealmCache>(cacheToReturn)); } return cacheToReturn; }

Target:
private static RealmCache getCache(String realmPath, boolean createIfNotExist) { RealmCache cacheToReturn = null; synchronized (cachesList) { Iterator<WeakReference<RealmCache>> it = cachesList.iterator(); while (it.hasNext()) { RealmCache cache = it.next().get(); if (cache == null) { it.remove(); } else if (cache.realmPath.equals(realmPath)) { cacheToReturn = cache; } } if (cacheToReturn == null && createIfNotExist) { cacheToReturn = new RealmCache(realmPath); cachesList.add(new WeakReference<RealmCache>(cacheToReturn)); } } return cacheToReturn; }
Source:
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); subscriptions.add(timespanSubject .flatMap(trendingSearch) .map(new SearchResultToRepositoryList()), trendingAdapter); timespanSubject.onNext(timespanAdapter.getItem(timespanView.getSelectedItemPosition())); }

Target:
@Override protected void onAttachedToWindow() { super.onAttachedToWindow(); subscriptions.add(timespanSubject .flatMap(trendingSearch) .map(SearchResultToRepositoryList.instance()), trendingAdapter); timespanSubject.onNext(timespanAdapter.getItem(timespanView.getSelectedItemPosition())); }