auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public BlockBuilder getFieldBlockBuilder(int fieldIndex) { if (currentFieldIndexToWrite != 0) { throw new IllegalStateException("column write mode can only be enabled before any value has been appended"); } fieldWriteMode = true; return fieldBlockBuilders[fieldIndex]; }

Target:
public BlockBuilder getFieldBlockBuilder(int fieldIndex) { if (currentFieldIndexToWrite != 0) { throw new IllegalStateException("field block builder can only be obtained before any sequential write has done"); } fieldBlockBuilderReturned = true; return fieldBlockBuilders[fieldIndex]; }
Source:
private void processChild(TaggedValuePointable tvp, DictionaryBuilder db) throws IOException, SystemException { IMutableValueStorage mvs = new ArrayBackedValueStorage(); if (tvp.getTag() != ValueTag.NODE_TREE_TAG) { enb.addChild(tvp); } else { NodeTreePointable ntp = ppool.takeOne(NodeTreePointable.class); try { tvp.getValue(ntp); TaggedValuePointable innerTvp = ppool.takeOne(TaggedValuePointable.class); try { ntp.getRootNode(innerTvp); byte nTag = innerTvp.getTag(); switch (nTag) { case ValueTag.ATTRIBUTE_NODE_TAG: { throw new SystemException(ErrorCode.XQTY0024); } case ValueTag.ELEMENT_NODE_TAG: { ElementNodePointable enp = ppool.takeOne(ElementNodePointable.class); try { innerTvp.getValue(enp); copyElement(enb, db, ntp, enp); } finally { ppool.giveBack(enp); } break; } case ValueTag.COMMENT_NODE_TAG: copyComment(innerTvp, ntp, mvs); enb.addChild(mvs); break; case ValueTag.PI_NODE_TAG: copyPI(innerTvp, ntp, mvs); enb.addChild(mvs); break; case ValueTag.TEXT_NODE_TAG: { copyText(innerTvp, ntp, mvs); enb.addChild(mvs); break; } case ValueTag.DOCUMENT_NODE_TAG: { DocumentNodePointable dnp = ppool.takeOne(DocumentNodePointable.class); try { innerTvp.getValue(dnp); copyDocument(enb, db, ntp, dnp); } finally { ppool.giveBack(dnp); } break; } } } finally { ppool.giveBack(innerTvp); } } finally { ppool.giveBack(ntp); } } }

Target:
private void processChild(TaggedValuePointable tvp, DictionaryBuilder db) throws IOException, SystemException { if (tvp.getTag() != ValueTag.NODE_TREE_TAG) { enb.addChild(tvp); } else { NodeTreePointable ntp = ppool.takeOne(NodeTreePointable.class); try { tvp.getValue(ntp); TaggedValuePointable innerTvp = ppool.takeOne(TaggedValuePointable.class); try { ntp.getRootNode(innerTvp); byte nTag = innerTvp.getTag(); switch (nTag) { case ValueTag.ATTRIBUTE_NODE_TAG: { throw new SystemException(ErrorCode.XQTY0024); } case ValueTag.ELEMENT_NODE_TAG: { ElementNodePointable enp = ppool.takeOne(ElementNodePointable.class); try { innerTvp.getValue(enp); copyElement(enb, db, ntp, enp); } finally { ppool.giveBack(enp); } break; } case ValueTag.COMMENT_NODE_TAG: abvs.reset(); copyComment(innerTvp, ntp, abvs); enb.addChild(abvs); break; case ValueTag.PI_NODE_TAG: abvs.reset(); copyPI(innerTvp, ntp, abvs); enb.addChild(abvs); break; case ValueTag.TEXT_NODE_TAG: { abvs.reset(); copyText(innerTvp, ntp, abvs); enb.addChild(abvs); break; } case ValueTag.DOCUMENT_NODE_TAG: { DocumentNodePointable dnp = ppool.takeOne(DocumentNodePointable.class); try { innerTvp.getValue(dnp); copyDocument(enb, db, ntp, dnp); } finally { ppool.giveBack(dnp); } break; } } } finally { ppool.giveBack(innerTvp); } } finally { ppool.giveBack(ntp); } } }
Source:
public JsonElement index(@Context HttpServletRequest request, @QueryParam(value = "page") final String pageStr) { int page; try { if (pageStr == null) { page = 0; } else { page = Integer.parseInt(pageStr); } if (page < 0) { page = 0; } } catch (final NumberFormatException e) { throw new WebApplicationException(400); } final SearchMissionsDTO searchMissions = new SearchMissionsDTO(request); final List<Mission> missions = searchMissions.sortedSearch(); final int ipp = 10; int skip = page * ipp; final int total = missions.size(); final int totalPages = (total + ipp - 1) / ipp; if (page >= totalPages && totalPages > 0) { page = totalPages - 1; skip = page * ipp; } final JsonObject json; if (missions.isEmpty()) { json = super.view(missions, "missions", AbbreviatedMissionAdapter.class).getAsJsonObject(); } else { json = super.viewPaginated(missions, "missions", AbbreviatedMissionAdapter.class, skip, ipp).getAsJsonObject(); } json.addProperty("totalPages", totalPages); json.addProperty("currentPage", page); json.addProperty("itemsPerPage", ipp); json.addProperty("sortBy", request.getParameter("sortBy")); return json; }

Target:
public JsonElement index(@Context HttpServletRequest request, @QueryParam(value = "page") final String pageStr) { int page; try { page = (pageStr == null) ? 0 : Integer.parseInt(pageStr); if (page < 0) { page = 0; } } catch (final NumberFormatException e) { throw new WebApplicationException(400); } final SearchMissionsDTO searchMissions = new SearchMissionsDTO(request); final List<Mission> missions = searchMissions.sortedSearch(); final int ipp = 10; int skip = page * ipp; final int total = missions.size(); final int totalPages = (total + ipp - 1) / ipp; if (page >= totalPages && totalPages > 0) { page = totalPages - 1; skip = page * ipp; } final JsonObject json; if (missions.isEmpty()) { json = super.view(missions, "missions", AbbreviatedMissionAdapter.class).getAsJsonObject(); } else { json = super.viewPaginated(missions, "missions", AbbreviatedMissionAdapter.class, skip, ipp).getAsJsonObject(); } json.addProperty("totalPages", totalPages); json.addProperty("currentPage", page); json.addProperty("itemsPerPage", ipp); json.addProperty("sortBy", request.getParameter("sortBy")); return json; }
Source:
public String getUserName() { if (principal == null || principal.isEmpty()) { return System.getProperty("user.name", "<NA>"); } return principal; }

Target:
public String getUserName() { if (principal == null || principal.isEmpty()) { return SYSTEM_USER; } return principal; }
Source:
public void testLoadInvalidFlowYamlFiles() { final DirectoryYamlFlowLoader loader = new DirectoryYamlFlowLoader(new Props()); loader.loadProjectFlow(this.project, ExecutionsTestUtil.getFlowDir(INVALID_FLOW_YAML_DIR)); Assert.assertEquals(2, loader.getErrors().size()); Assert.assertEquals(2, loader.getFlowMap().size()); Assert.assertEquals(2, loader.getEdgeMap().size()); Assert.assertTrue(loader.getFlowMap().containsKey(INVALID_FLOW_1)); final Flow flow1 = loader.getFlowMap().get(INVALID_FLOW_1); Assert.assertEquals(3, flow1.getNodes().size()); Assert.assertEquals(1, flow1.getErrors().size()); Assert.assertEquals(3, loader.getEdgeMap().get(INVALID_FLOW_1).size()); Assert.assertEquals(3, flow1.getEdges().size()); for (final Edge edge : loader.getEdgeMap().get(INVALID_FLOW_1)) { this.logger.info(INVALID_FLOW_1 + ".flow has edge: " + edge.getId()); if (edge.getError() != null) { Assert.assertEquals(DEPENDENCY_NOT_FOUND_ERROR, edge.getError()); } } Assert.assertTrue(loader.getFlowMap().containsKey(INVALID_FLOW_2)); final Flow flow2 = loader.getFlowMap().get(INVALID_FLOW_2); Assert.assertEquals(4, flow2.getNodes().size()); Assert.assertEquals(1, flow2.getErrors().size()); Assert.assertEquals(4, loader.getEdgeMap().get(INVALID_FLOW_2).size()); Assert.assertEquals(4, flow2.getEdges().size()); for (final Edge edge : loader.getEdgeMap().get(INVALID_FLOW_2)) { this.logger.info(INVALID_FLOW_2 + ".flow has edge: " + edge.getId()); if (edge.getError() != null) { Assert.assertEquals(CYCLE_FOUND_ERROR, edge.getError()); } } }

Target:
public void testLoadInvalidFlowYamlFiles() { final DirectoryYamlFlowLoader loader = new DirectoryYamlFlowLoader(new Props()); loader.loadProjectFlow(this.project, ExecutionsTestUtil.getFlowDir(INVALID_FLOW_YAML_DIR)); checkFlowLoaderProperties(loader, 2, 2, 2); checkFlowProperties(loader, INVALID_FLOW_1, 1, 3, 3, DEPENDENCY_NOT_FOUND_ERROR); checkFlowProperties(loader, INVALID_FLOW_2, 1, 4, 4, CYCLE_FOUND_ERROR); }
Source:
public void Namespace(String namespace) { this.namespace = namespace; sharedPreferences = context.getSharedPreferences(namespace, Context.MODE_PRIVATE); if (sharedPreferenceChangeListener != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { notifyDataObservers(key, GetValue(key, null)); } }; sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); }

Target:
public void Namespace(String namespace) { this.namespace = namespace; if (sharedPreferences != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } sharedPreferences = context.getSharedPreferences(namespace, Context.MODE_PRIVATE); sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); }
Source:
public static URI appendParameters(URI oldUri, Map<String, String> queryParams) { String newQuery = oldUri.getQuery(); String appendQuery = queryParams.entrySet().stream() .map(param -> param.getKey() + "=" + param.getValue()) .reduce("", (a, b) -> a + "&" + b); if (newQuery == null) { newQuery = StringUtils.removeStart(appendQuery, "&"); } else { newQuery += appendQuery; } try { return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, oldUri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException(e); } }

Target:
public static URI appendParameters(URI oldUri, Map<String, String> queryParams) { MultiValueMap<String, String> localQueryParams = new LinkedMultiValueMap<>(); queryParams.entrySet().forEach(entry -> localQueryParams.add(entry.getKey(), entry.getValue())); return fromUri(oldUri).queryParams(localQueryParams).build().toUri(); }
Source:
private static boolean checkGitIgnore(IResource resource) { IContainer container = resource.getParent(); IFile gitignore = container.getFile(new Path(Constants.GITIGNORE_FILENAME)); return searchForExact("/" + resource.getName(), gitignore); }

Target:
private static boolean checkGitIgnore(IResource resource) { IResource res = resource; boolean isContainer = false; DoubleBool retval = new DoubleBool(false); String name = "/" + resource.getName(); while (!retval.changed && res.getProjectRelativePath() != Path.EMPTY) { res = res.getParent(); System.out.println("Checking file in " + res.getName()); IFile gitignore = ((IContainer) res).getFile( new Path(Constants.GITIGNORE_FILENAME)); if (res instanceof IContainer) isContainer = true; if (!gitignore.exists()) continue; retval = searchForExact(name, gitignore, isContainer); name = "/" + res.getName() + name; } return retval.value; }
Source:
public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto project = componentFinder.getByKey(dbSession, request.mandatoryParam(PARAM_PROJECT)); if (!userSession.hasComponentPermission(UserRole.USER, project) && !userSession.hasComponentPermission(UserRole.ADMIN, project)) { throw insufficientPrivilegesException(); } Optional<OrganizationDto> organization = dbClient.organizationDao().selectByUuid(dbSession, project.getOrganizationUuid()); if (!organization.isPresent()) { throw new NotFoundException(format("Organization [%s] is absent", project.getOrganizationUuid())); } Optional<QualityGateData> data = qualityGateFinder.getQualityGate(dbSession, organization.get(), project.getId()); writeProtobuf(buildResponse(data), request, response); } }

Target:
public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { OrganizationDto organization = wsSupport.getOrganization(dbSession, request); ComponentDto project = componentFinder.getByKey(dbSession, request.mandatoryParam(PARAM_PROJECT)); wsSupport.checkProjectBelongsToOrganization(organization, project); if (!userSession.hasComponentPermission(USER, project) && !userSession.hasComponentPermission(ADMIN, project)) { throw insufficientPrivilegesException(); } QualityGateData data = qualityGateFinder.getQualityGate(dbSession, organization, project.getId()); writeProtobuf(buildResponse(data), request, response); } }
Source:
private void execute() { if (fFinishedLatch.getCount() == 0) { return; } synchronized (syncObj) { if (fStarted) { return; } fStarted = true; } final ITmfTrace trace = fTrace; fJob = new Job(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName())) { @Override protected IStatus run(final IProgressMonitor monitor) { try { monitor.beginTask("", IProgressMonitor.UNKNOWN); broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this)); fAnalysisCancelled = !executeAnalysis(monitor); } catch (TmfAnalysisException e) { Activator.logError("Error executing analysis with trace " + getTrace().getName(), e); } finally { synchronized (syncObj) { monitor.done(); setAnalysisCompleted(); } } if (!fAnalysisCancelled) { TmfTraceManager.refreshSupplementaryFiles(trace); return Status.OK_STATUS; } resetAnalysis(); return Status.CANCEL_STATUS; } @Override protected void canceling() { TmfAbstractAnalysisModule.this.canceling(); TmfTraceManager.refreshSupplementaryFiles(trace); } }; fJob.schedule(); }

Target:
private void execute() { if (fFinishedLatch.getCount() == 0) { return; } synchronized (syncObj) { if (fStarted) { return; } fStarted = true; } final ITmfTrace trace = fTrace; fJob = new Job(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName())) { @Override protected IStatus run(final IProgressMonitor monitor) { try { monitor.beginTask("", IProgressMonitor.UNKNOWN); broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this)); fAnalysisCancelled = !executeAnalysis(monitor); } catch (TmfAnalysisException e) { Activator.logError("Error executing analysis with trace " + getTrace().getName(), e); } finally { synchronized (syncObj) { monitor.done(); setAnalysisCompleted(); } TmfTraceManager.refreshSupplementaryFiles(trace); } if (!fAnalysisCancelled) { return Status.OK_STATUS; } resetAnalysis(); return Status.CANCEL_STATUS; } @Override protected void canceling() { TmfAbstractAnalysisModule.this.canceling(); } }; fJob.schedule(); }
Source:
private List<String> multiLinesIn() { String[] lines = getImage().split("\\R"); List<String> filteredLines = new ArrayList<>(lines.length); for (String rawLine : lines) { String line = rawLine.trim(); Matcher allMatcher = COMMENT_LINE_COMBINED.matcher(line); if (allMatcher.matches()) { filteredLines.add(allMatcher.group(1).trim()); } } return filteredLines; }

Target:
private List<String> multiLinesIn() { String[] lines = NEWLINES_PATTERN.split(getImage()); List<String> filteredLines = new ArrayList<>(lines.length); for (String rawLine : lines) { String line = rawLine.trim(); Matcher allMatcher = COMMENT_LINE_COMBINED.matcher(line); if (allMatcher.matches()) { filteredLines.add(allMatcher.group(1).trim()); } } return filteredLines; }
Source:
private void checkOpenGL() { boolean[] requiredCapabilities = { GLContext.getCapabilities().OpenGL12, GLContext.getCapabilities().OpenGL14, GLContext.getCapabilities().OpenGL15, GLContext.getCapabilities().OpenGL20, GLContext.getCapabilities().OpenGL21, GLContext.getCapabilities().GL_ARB_framebuffer_object, GLContext.getCapabilities().GL_ARB_texture_float, GLContext.getCapabilities().GL_ARB_half_float_pixel}; String[] capabilityNames = {"OpenGL12", "OpenGL14", "OpenGL15", "OpenGL20", "OpenGL21", "OpenGL30", "OpenGL32", "OpenGL33", "GL_ARB_framebuffer_object", "GL_ARB_texture_float", "GL_ARB_half_float_pixel"}; boolean canRunTheGame = true; String missingCapabilitiesMessage = ""; for (int index = 0; index < requiredCapabilities.length; index++) { if (!requiredCapabilities[index]) { missingCapabilitiesMessage += " - " + capabilityNames[index] + "\n"; canRunTheGame = false; } } if (!canRunTheGame) { String completeErrorMessage = completeErrorMessage(missingCapabilitiesMessage); throw new IllegalStateException(completeErrorMessage); } }

Target:
private void checkOpenGL() { boolean[] requiredCapabilities = { GLContext.getCapabilities().OpenGL12, GLContext.getCapabilities().OpenGL14, GLContext.getCapabilities().OpenGL15, GLContext.getCapabilities().OpenGL20, GLContext.getCapabilities().OpenGL21, GLContext.getCapabilities().GL_ARB_framebuffer_object, GLContext.getCapabilities().GL_ARB_texture_float, GLContext.getCapabilities().GL_ARB_half_float_pixel}; String[] capabilityNames = {"OpenGL12", "OpenGL14", "OpenGL15", "OpenGL20", "OpenGL21", "GL_ARB_framebuffer_object", "GL_ARB_texture_float", "GL_ARB_half_float_pixel"}; boolean canRunTheGame = true; String missingCapabilitiesMessage = ""; for (int index = 0; index < requiredCapabilities.length; index++) { if (!requiredCapabilities[index]) { missingCapabilitiesMessage += " - " + capabilityNames[index] + "\n"; canRunTheGame = false; } } if (!canRunTheGame) { String completeErrorMessage = completeErrorMessage(missingCapabilitiesMessage); throw new IllegalStateException(completeErrorMessage); } }
Source:
public CharSequence format(Coin coin) { int maxDecimals = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) maxDecimals += group; checkState(maxDecimals <= 8); long satoshis = Math.abs(coin.value); long precisionDivisor = checkedPow(10, 8 - shift - maxDecimals); satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor); long shiftDivisor = checkedPow(10, 8 - shift); long numbers = satoshis / shiftDivisor; long decimals = satoshis % shiftDivisor; String decimalsStr = String.format(Locale.US, "%0" + (8 - shift) + "d", decimals); StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); int i = minDecimals; if (decimalGroups != null) { for (int group : decimalGroups) { if (str.length() > i && str.length() < i + group) { while (str.length() < i + group) str.append('0'); break; } i += group; } } if (str.length() > 0) str.insert(0, decimalMark); str.insert(0, numbers); if (coin.value < 0) str.insert(0, negativeSign); else if (positiveSign != 0) str.insert(0, positiveSign); return str; }

Target:
public CharSequence format(Coin coin) { int maxDecimals = minDecimals; if (decimalGroups != null) for (int group : decimalGroups) maxDecimals += group; checkState(maxDecimals <= Coin.NUM_COIN_DECIMALS); long satoshis = Math.abs(coin.value); long precisionDivisor = checkedPow(10, Coin.NUM_COIN_DECIMALS - shift - maxDecimals); satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor); long shiftDivisor = checkedPow(10, Coin.NUM_COIN_DECIMALS - shift); long numbers = satoshis / shiftDivisor; long decimals = satoshis % shiftDivisor; String decimalsStr = String.format(Locale.US, "%0" + (Coin.NUM_COIN_DECIMALS - shift) + "d", decimals); StringBuilder str = new StringBuilder(decimalsStr); while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0') str.setLength(str.length() - 1); int i = minDecimals; if (decimalGroups != null) { for (int group : decimalGroups) { if (str.length() > i && str.length() < i + group) { while (str.length() < i + group) str.append('0'); break; } i += group; } } if (str.length() > 0) str.insert(0, decimalMark); str.insert(0, numbers); if (coin.value < 0) str.insert(0, negativeSign); else if (positiveSign != 0) str.insert(0, positiveSign); return str; }
Source:
public Identifier save(Identifier delegate) { throw new UnsupportedOperationException(); }

Target:
public Identifier save(Identifier delegate) { throw new ResourceDoesNotSupportOperationException(); }
Source:
public Builder withAppProfileId(ValueProvider<String> appProfileId) { return withConfiguration(BigtableOptionsFactory.APP_PROFILE_ID_KEY, appProfileId); }

Target:
Builder withAppProfileId(ValueProvider<String> appProfileId) { return withConfiguration(BigtableOptionsFactory.APP_PROFILE_ID_KEY, appProfileId); }
Source:
public static String lastModifiedDateFormat( final Date date ) { return LAST_MODIFIED_DATE_FORMAT.format(date); }

Target:
public static String lastModifiedDateFormat( final Date date ) { return LAST_MODIFIED_DATE_FORMAT.format(date.toInstant()); }
Source:
public void sendReminderNotification() { String NOTIFICATION_TITLE = "\u23f0"; String NOTIFICATION_TEXT = context.getString(R.string.reminders_notification_text); String NOTIFICATION_ACTION = context.getString(R.string.reminders_notification_action); Intent intent = new Intent(context, AddGlucoseActivity.class); intent.putExtra("glucose_reminder_notification", true); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { notification = new Notification.Builder(context) .setContentTitle(NOTIFICATION_TITLE) .setContentText(NOTIFICATION_TEXT) .setAutoCancel(true) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setVibrate(new long[]{1000, 1000}) .setColor(context.getColor(R.color.glucosio_pink)) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.ic_stat_glucosio) .build(); } else { notification = new Notification.Builder(context) .setContentTitle(NOTIFICATION_TITLE) .setContentText(NOTIFICATION_TEXT) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setVibrate(new long[]{1000, 1000}) .setAutoCancel(true) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.ic_stat_glucosio) .build(); } NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context); notificationManagerCompat.notify(NOTIFICATION_ID, notification); }

Target:
public void sendReminderNotification() { String NOTIFICATION_TITLE = "\u23f0"; String NOTIFICATION_TEXT = context.getString(R.string.reminders_notification_text); Intent intent = new Intent(context, AddGlucoseActivity.class); intent.putExtra("glucose_reminder_notification", true); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder notificationBuilder; notificationBuilder = new Notification.Builder(context) .setContentTitle(NOTIFICATION_TITLE) .setContentText(NOTIFICATION_TEXT) .setAutoCancel(true) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setVibrate(new long[]{1000, 1000}) .setContentIntent(pendingIntent) .setSmallIcon(R.drawable.ic_stat_glucosio); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { notificationBuilder.setColor(context.getColor(R.color.glucosio_pink)); } Notification notification = notificationBuilder.build(); NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context); notificationManagerCompat.notify(NOTIFICATION_ID, notification); }
Source:
private Map<String, DataRight> getClassificationToDataRights(QueryBuilder query) { Map<String, DataRight> toReturn = new HashMap<String, DataRight>(); @SuppressWarnings("unchecked") ArtifactReadable footerMappingArt = query.andIds(MAPPING_ARTIFACT).getResults().getOneOrNull(); List<String> footers = new ArrayList<String>(); if (footerMappingArt != null) { footers = footerMappingArt.getAttributeValues(CoreAttributeTypes.GeneralStringData); for (String footer : footers) { String[] enumToFooter = footer.split("\\n", 2); if (enumToFooter.length == 2) { DataRightId id = new DataRightId(); id.setId(GUID.create()); DataRight dataRight = new DataRight(); dataRight.setId(id); dataRight.setContent(enumToFooter[1].trim()); toReturn.put(enumToFooter[0].trim(), dataRight); } } } return toReturn; }

Target:
private Map<String, DataRight> getClassificationToDataRights(QueryBuilder query) { Map<String, DataRight> toReturn = new HashMap<String, DataRight>(); @SuppressWarnings("unchecked") ArtifactReadable footerMappingArt = query.andIds(MAPPING_ARTIFACT).getResults().getOneOrNull(); if (footerMappingArt != null) { List<String> footers = new ArrayList<String>(); footers = footerMappingArt.getAttributeValues(CoreAttributeTypes.GeneralStringData); for (String footer : footers) { String[] enumToFooter = footer.split("\\n", 2); if (enumToFooter.length == 2) { DataRightId id = new DataRightId(); id.setId(GUID.create()); DataRight dataRight = new DataRight(); dataRight.setId(id); dataRight.setContent(enumToFooter[1].trim()); toReturn.put(enumToFooter[0].trim(), dataRight); } } } return toReturn; }
Source:
@Override public void close() throws Exception { log.info("Pipeline task is starting shutdown"); int size = phaseComplete.size(); for (int i = (size - 1); i >= 0; i--) { phaseComplete.get(i).cancel(false); } for (int i = (size - 1); i >= 0; i--) { try { if (!phaseComplete.get(i).isCancelled()) { phaseNext.get(i).join(); } } catch (CompletionException ex) { log.error("Phase phaseNext future encountered an exception while starting phase {}: ", i + 1, i + 2, ex); throw ex; } catch (CancellationException ex) { log.error("Race condition: Phase phaseNext future was cancelled by another thread: ", i + 1, ex); throw ex; } } if (currentPhase != null) { currentPhase.close(); } }

Target:
@Override public void close() throws Exception { log.info("Pipeline task is starting shutdown"); int size = phaseComplete.size(); boolean cancel[] = new boolean[size]; for (int i = (size - 1); i >= 0; i--) { cancel[i] = phaseComplete.get(i).cancel(false); } for (int i = (size - 1); i >= 0; i--) { try { if (!cancel[i]) { phaseNext.get(i).join(); } } catch (CompletionException ex) { String msg = "Phase " + (i + 1) + " phaseNext future encountered an " + "exception while starting phase " + (i + 2); throw new IOException(msg, ex); } catch (CancellationException ex) { String msg = "Race condition: Phase " + (i + 1) + " phaseNext " + "future was cancelled by another thread"; throw new IOException(msg, ex); } } if (currentPhase != null) { currentPhase.close(); } }
Source:
public boolean matchesSuffixOnly(@Nullable final String s) { if (suffixStyle == SuffixStyle.MATCH_ANY) { return true; } else if (suffixStyle == SuffixStyle.MATCH_EMPTY) { return s == null || s.length() == prefix.length(); } else { return suffixPattern.matcher(Strings.nullToEmpty(s).substring(prefix.length())).matches(); } }

Target:
public boolean matchesSuffixOnly(@Nullable final String s) { if (suffixMatch == SuffixMatch.MATCH_ANY) { return true; } else if (suffixMatch == SuffixMatch.MATCH_EMPTY) { return (s == null ? 0 : s.length()) == prefix.length(); } else { return matches(s); } }
Source:
private static Map<Integer, String> getExecutableNames(ITmfTrace trace) { Map<Integer, String> executableNames = new HashMap<>(); KernelAnalysisModule kernelAnlysis = TmfTraceUtils.getAnalysisModuleOfClass(trace, KernelAnalysisModule.class, KernelAnalysisModule.ID); if (kernelAnlysis == null) { return Collections.emptyMap(); } Collection<Integer> collection = KernelThreadInformationProvider.getThreadIds(kernelAnlysis); if (!collection.equals(Collections.emptySet())) { for (Integer TID : collection) { String execName = KernelThreadInformationProvider.getExecutableName(kernelAnlysis, TID); if (execName != null) { executableNames.put(TID, execName); } } } return executableNames; }

Target:
private static Map<Integer, String> getExecutableNames(ITmfTrace trace) { Map<Integer, String> executableNames = new HashMap<>(); KernelAnalysisModule kernelAnlysis = TmfTraceUtils.getAnalysisModuleOfClass(trace, KernelAnalysisModule.class, KernelAnalysisModule.ID); if (kernelAnlysis == null) { return Collections.emptyMap(); } Collection<Integer> threadIds = KernelThreadInformationProvider.getThreadIds(kernelAnlysis); if (!threadIds.isEmpty()) { for (Integer tid : threadIds) { String execName = KernelThreadInformationProvider.getExecutableName(kernelAnlysis, tid); if (execName != null) { executableNames.put(tid, execName); } } } return executableNames; }
Source:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateConditionalEvent emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptySubprocessEvent.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, CANCELLING, ""); }

Target:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateConditionalEvent emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptySubprocessEvent.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, CANCELLING, EMPTY_VALUE); }
Source:
public void saveLastVitalsEncounter(Encounter encounter, String patientUUID) { if (null != encounter) { encounter.setPatientUUID(patientUUID); long oldLastVitalsEncounterID = getLastVitalsEncounterID(patientUUID); if (0 != oldLastVitalsEncounterID) { for (Observation obs: new ObservationDAO().findObservationByEncounterID(oldLastVitalsEncounterID)) { new ObservationTable().delete(obs.getId()); } new EncounterTable().delete(oldLastVitalsEncounterID); } ObservationDAO observationDAO = new ObservationDAO(); long encounterID = saveEncounter(encounter, null); for (Observation obs : encounter.getObservations()) { observationDAO.saveObservation(obs, encounterID) .observeOn(AndroidSchedulers.mainThread()) .subscribe(); } } }

Target:
public void saveLastVitalsEncounter(Encounter encounter, String patientUUID) { if (null != encounter) { encounter.setPatientUUID(patientUUID); long oldLastVitalsEncounterID = getLastVitalsEncounterID(patientUUID); if (0 != oldLastVitalsEncounterID) { for (Observation obs: new ObservationDAO().findObservationByEncounterID(oldLastVitalsEncounterID)) { new ObservationTable().delete(obs.getId()); } new EncounterTable().delete(oldLastVitalsEncounterID); } ObservationDAO observationDAO = new ObservationDAO(); long encounterID = saveEncounter(encounter, null); for (Observation obs : encounter.getObservations()) { observationDAO.saveObservation(obs, encounterID) .observeOn(Schedulers.io()) .subscribe(); } } }
Source:
protected void handleRemoteBrowseSelected() { IRemoteConnection currentConnectionSelected = getCurrentConnection(); RemoteResourceBrowser b = new RemoteResourceBrowser(getControl().getShell(), SWT.RESIZE); b.setConnection(currentConnectionSelected); b.setTitle(Messages.RemoteCMainTab_Remote_Path_Browse_Button_Title); b.setType(RemoteResourceBrowser.FILE_BROWSER); int returnCode = b.open(); if (returnCode == Window.CANCEL) { return; } IFileStore selectedFile = b.getResource(); if (selectedFile != null) { String absPath = selectedFile.toURI().getPath(); if (selectedFile.fetchInfo().isDirectory()) { IPath appPath = new Path(fProgText.getText().trim()); String lastSegment = appPath.lastSegment(); if (lastSegment != null && lastSegment.trim().length() > 0) { IPath remotePath = new Path(absPath).append(lastSegment.trim()); absPath = remotePath.toPortableString(); } } remoteProgText.setText(absPath); } }

Target:
protected void handleRemoteBrowseSelected() { IRemoteConnection currentConnectionSelected = getCurrentConnection(); RemoteResourceBrowser b = new RemoteResourceBrowser(getControl().getShell(), SWT.NONE); b.setConnection(currentConnectionSelected); b.setTitle(Messages.RemoteCMainTab_Remote_Path_Browse_Button_Title); int returnCode = b.open(); if (returnCode == Window.CANCEL) { return; } IFileStore selectedFile = b.getResource(); if (selectedFile != null) { String absPath = selectedFile.toURI().getPath(); if (selectedFile.fetchInfo().isDirectory()) { IPath appPath = new Path(fProgText.getText().trim()); String lastSegment = appPath.lastSegment(); if (lastSegment != null && lastSegment.trim().length() > 0) { IPath remotePath = new Path(absPath).append(lastSegment.trim()); absPath = remotePath.toPortableString(); } } remoteProgText.setText(absPath); } }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final MessageMetadata other = (MessageMetadata) obj; return Objects.equals(this.id, other.id) && Objects.equals(this.timestamp, other.timestamp) && Objects.equals(this.traceId, other.traceId); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final MessageMetadata other = (MessageMetadata) obj; return Objects.equals(this.id, other.id) && Objects.equals(this.timestamp, other.timestamp); }
Source:
public StatementPatternMetadata readStatementPatternMetadata(SnapshotBase tx, String nodeId) { Optional<NodeType> type = NodeType.fromNodeId(nodeId); try { checkArgument(type.isPresent() && type.get() == NodeType.STATEMENT_PATTERN); LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (StatementPatternMetadata) commonNodeMetadataCache.get(nodeId, new Callable<CommonNodeMetadata>() { @Override public CommonNodeMetadata call() throws Exception { LOG.debug("Seeking Metadata from Fluo Table: {}", nodeId); return dao.readStatementPatternMetadata(tx, nodeId); } }); } catch (Exception e) { throw new RuntimeException("Unable to access StatementPatternMetadata for nodeId: " + nodeId, e); } }

Target:
public StatementPatternMetadata readStatementPatternMetadata(SnapshotBase tx, String nodeId) { checkNotNull(nodeId); checkNotNull(tx); Optional<NodeType> type = NodeType.fromNodeId(nodeId); checkArgument(type.isPresent() && type.get() == NodeType.STATEMENT_PATTERN); try { LOG.debug("Retrieving Metadata from Cache: {}", nodeId); return (StatementPatternMetadata) commonNodeMetadataCache.get(nodeId, () -> { LOG.debug("Seeking Metadata from Fluo Table: {}", nodeId); return dao.readStatementPatternMetadata(tx, nodeId); }); } catch (Exception e) { throw new RuntimeException("Unable to access StatementPatternMetadata for nodeId: " + nodeId, e); } }
Source:
public AtmosphereResource initialize(AtmosphereConfig config, Broadcaster broadcaster, AtmosphereRequest req, AtmosphereResponse response, AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) { this.req = req; this.response = response; this.config = config; this.asyncSupport = asyncSupport; this.atmosphereHandler = atmosphereHandler; this.event = new AtmosphereResourceEventImpl(this); this.broadcaster = broadcaster; uniqueBroadcaster(broadcaster); String s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID); if (s == null) { s = response.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); if (s == null && req != null) { String tmp = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); s = tmp != null && !tmp.equalsIgnoreCase("0") ? tmp : null; } } this.setUUID( s == null ? config.uuidProvider().generateUuid() : s ); if (config.isSupportSession()) { try { session = req.getSession(config.getInitParameter(PROPERTY_SESSION_CREATE, true)); } catch (NullPointerException ex) { logger.trace("<LINK_0>", ex); } } transport = configureTransport(); closeOnCancel = config.getInitParameter(ApplicationConfig.CLOSE_STREAM_ON_CANCEL, false); return this; }

Target:
public AtmosphereResource initialize(AtmosphereConfig config, Broadcaster broadcaster, AtmosphereRequest req, AtmosphereResponse response, AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) { this.req = req; this.response = response; this.config = config; this.asyncSupport = asyncSupport; this.atmosphereHandler = atmosphereHandler; this.event = new AtmosphereResourceEventImpl(this); this.broadcaster = broadcaster; uniqueBroadcaster(broadcaster); String s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID); if (s == null) { s = response.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); if (s == null && req != null) { String tmp = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); s = tmp != null && !tmp.equalsIgnoreCase("0") ? tmp : null; } } setUUID(s == null ? config.uuidProvider().generateUuid() : s); if (config.isSupportSession()) { try { session = req.getSession(config.getInitParameter(PROPERTY_SESSION_CREATE, true)); } catch (NullPointerException ex) { logger.trace("<LINK_0>", ex); } } transport = configureTransport(); closeOnCancel = config.getInitParameter(ApplicationConfig.CLOSE_STREAM_ON_CANCEL, false); return this; }
Source:
public IValue getInitialValue() { Set<CPPVariable> recursionProtectionSet = fInitialValueInProgress.get(); if (!recursionProtectionSet.add(this)) { return IntegralValue.UNKNOWN; } try { final IValue initialValue = VariableHelpers.getInitialValue(fDefinition, fDeclarations, getType()); final IType nestedType = SemanticUtil.getNestedType(getType(), TDEF | REF | CVTYPE); if(nestedType instanceof ICPPClassType || initialValue == IntegralValue.UNKNOWN) { ICPPEvaluation initEval = getInitializerEvaluation(); if(initEval == null) { return null; } return IntegralValue.create(initEval); } return initialValue; } finally { recursionProtectionSet.remove(this); } }

Target:
public IValue getInitialValue() { Set<CPPVariable> recursionProtectionSet = fInitialValueInProgress.get(); if (!recursionProtectionSet.add(this)) { return IntegralValue.UNKNOWN; } try { IValue initialValue = null; final IType nestedType = SemanticUtil.getNestedType(getType(), TDEF | REF | CVTYPE); if(nestedType instanceof ICPPClassType || (initialValue = VariableHelpers.getInitialValue(fDefinition, fDeclarations, getType())) == IntegralValue.UNKNOWN) { ICPPEvaluation initEval = getInitializerEvaluation(); if(initEval == null) { return null; } return IntegralValue.create(initEval); } return initialValue; } finally { recursionProtectionSet.remove(this); } }
Source:
public double calculateEntropy() { double sum = 0; for (FixedDoubleHistogram.Bucket bucket : histogram) { sum += bucket.getWeight(); } if (sum == 0.0) { return Double.NaN; } double rawEntropy = 0; for (FixedDoubleHistogram.Bucket bucket : histogram) { final double prob = bucket.getWeight() / sum; rawEntropy -= getXLogX(prob); } return (rawEntropy + Math.log(histogram.getWidth())) / Math.log(2); }

Target:
public double calculateEntropy() { double sum = 0; for (FixedDoubleHistogram.Bucket bucket : histogram) { sum += bucket.getWeight(); } if (sum == 0.0) { return Double.NaN; } double rawEntropy = 0; for (FixedDoubleHistogram.Bucket bucket : histogram) { rawEntropy -= getXLogX(bucket.getWeight() / sum); } return (rawEntropy + Math.log(histogram.getWidth())) / Math.log(2); }
Source:
public Response getUser(@Auth Key key, @QueryParam("username") String username) { StormUser stormUser = thunderClient.getUser(username); FacebookUser facebookUser = new FacebookProvider(stormUser, auth).getFacebookUser(); return Response.ok(facebookUser).build(); }

Target:
public Response getUser(@Auth Key key, @QueryParam("username") String username) { if (username == null) { return Response.status(Response.Status.BAD_REQUEST) .entity("'username' query parameter is required for getUser").build(); } StormUser stormUser = thunderClient.getUser(username); FacebookUser facebookUser = null; try { facebookUser = new FacebookProvider(stormUser.getFacebookAccessToken(), applicationKey).getFacebookUser(); } catch (FacebookOAuthException e) { LOG.error("Bad Facebook OAuth Token", e); return Response.status(Response.Status.NOT_FOUND) .entity("Request rejected due to bad OAuth token").build(); } return Response.status(Response.Status.ACCEPTED).entity(facebookUser).build(); }
Source:
public SmudgeFilter(Repository db, InputStream in, OutputStream out) throws IOException { super(in, out); lfs = new Lfs(db); LfsPointer res = LfsPointer.parseLfsPointer(in); if (res != null) { AnyLongObjectId oid = res.getOid(); Path mediaFile = lfs.getMediaFile(oid); if (!Files.exists(mediaFile)) { downloadLfsResource(lfs, db, res); } this.in = Files.newInputStream(mediaFile); } }

Target:
public SmudgeFilter(Repository db, InputStream in, OutputStream out) throws IOException { super(in, out); Lfs lfs = new Lfs(db); LfsPointer res = LfsPointer.parseLfsPointer(in); if (res != null) { AnyLongObjectId oid = res.getOid(); Path mediaFile = lfs.getMediaFile(oid); if (!Files.exists(mediaFile)) { downloadLfsResource(lfs, db, res); } this.in = Files.newInputStream(mediaFile); } }
Source:
public void run() { long iteration = 0; while (!testContext.isStopped()) { int key = randomKey(); int value = randomValue(); switch (selector.select()) { case PUT: putLatency.started(); map.put(key, value); putLatency.done(); break; case SET: putLatency.started(); map.put(key, value); putLatency.done(); break; case GET: getLatency.started(); map.put(key, value); getLatency.done(); break; default: throw new UnsupportedOperationException(); } if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } if (iteration % performanceUpdateFrequency == 0) { operations.addAndGet(performanceUpdateFrequency); } iteration++; throughput.done(); } operations.addAndGet(iteration % performanceUpdateFrequency); }

Target:
public void run() { long iteration = 0; while (!testContext.isStopped()) { int key = randomKey(); int value = randomValue(); switch (selector.select()) { case PUT: putLatency.started(); if (useSet) { map.set(key, value); } else { map.put(key, value); } putLatency.done(); break; case GET: getLatency.started(); map.put(key, value); getLatency.done(); break; default: throw new UnsupportedOperationException(); } iteration++; if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } if (iteration % performanceUpdateFrequency == 0) { operations.addAndGet(performanceUpdateFrequency); } throughput.done(); } operations.addAndGet(iteration % performanceUpdateFrequency); }
Source:
private void writeNotification(AttributeChangeNotification notification, Path path) { try (BufferedWriter in = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { in.write(String.format("%s %s %s %s", notification.getType(), notification.getSequenceNumber(), notification.getSource().toString(), notification.getMessage())); in.newLine(); in.flush(); } catch (ClosedByInterruptException cbie) { Thread.interrupted(); Logger.getLogger(ControlledStateNotificationListener.class).error("We were interrupted and couldn't write into file, try again", cbie); try (BufferedWriter in = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { in.write(String.format("%s %s %s %s", notification.getType(), notification.getSequenceNumber(), notification.getSource().toString(), notification.getMessage())); in.newLine(); in.flush(); } catch(IOException ex2) { Logger.getLogger(ControlledStateNotificationListener.class).error("No success on second attempt either", ex2); } } catch (IOException ex) { Logger.getLogger(ControlledStateNotificationListener.class).error("Problem handling JMX Notification", ex); } }

Target:
private void writeNotification(AttributeChangeNotification notification, Path path) { try (BufferedWriter in = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { in.write(String.format("%s %s %s %s", notification.getType(), notification.getSequenceNumber(), notification.getSource().toString(), notification.getMessage())); in.newLine(); in.flush(); } catch (ClosedByInterruptException cbie) { boolean wasInterrupted = Thread.interrupted(); try { Logger.getLogger(ControlledStateNotificationListener.class) .error("We were interrupted and couldn't write into file, try again", cbie); try (BufferedWriter in = Files .newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) { in.write(String.format("%s %s %s %s", notification.getType(), notification.getSequenceNumber(), notification.getSource().toString(), notification.getMessage())); in.newLine(); in.flush(); } catch (IOException ex2) { Logger.getLogger(ControlledStateNotificationListener.class) .error("No success on second attempt either", ex2); } } finally { if(wasInterrupted) Thread.currentThread().interrupt(); } } catch (IOException ex) { Logger.getLogger(ControlledStateNotificationListener.class).error("Problem handling JMX Notification", ex); } }
Source:
private void downloadFileAndRenderPdf() { mFileDownloader.downloadFile(mItem.getUrl(), PDF_MIME_TYPE, new FileDownloader.FileDownloaderCallback() { @Override public void onFailure(IOException e) { } @Override public void onSuccess(String filePath) { reloadUrl(PDF_LOADER_URL, filePath); } }); }

Target:
private void downloadFileAndRenderPdf() { mFileDownloader.downloadFile(mItem.getUrl(), PDF_MIME_TYPE, new FileDownloader.FileDownloaderCallback() { @Override public void onFailure(Call call, IOException e) { offerExternalApp(); } @Override public void onSuccess(String filePath) { reloadUrl(PDF_LOADER_URL, filePath); } }); }
Source:
@Override protected SqlParserImplFactory parserImplFactory() { return null; }

Target:
@Override protected SqlParserImplFactory parserImplFactory() { return ExtensionSqlParserImpl.FACTORY; }
Source:
private void startLookups(final List<LookupBean> lookupBeanList) { ImmutableMap.Builder<String, LookupExtractorFactoryContainer> builder = ImmutableMap.builder(); ExecutorService executorService = Execs.multiThreaded( lookupConfig.getNumLookupLoadingThreads(), "LookupReferencesManager-Startup-%s" ); CompletionService<Map.Entry<String, LookupExtractorFactoryContainer>> completionService = new ExecutorCompletionService<>(executorService); try { LOG.info("Starting lookup loading process"); List<LookupBean> remainingLookups = lookupBeanList; for (int i = 0; i < lookupConfig.getLookupStartRetries(); i++) { LOG.info("Round of attempts #%d, [%d] lookups", i + 1, remainingLookups.size()); Map<String, LookupExtractorFactoryContainer> successfulLookups = startLookups(remainingLookups, completionService); builder.putAll(successfulLookups); List<LookupBean> failedLookups = remainingLookups .stream() .filter(l -> !successfulLookups.containsKey(l.getName())) .collect(Collectors.toList()); if (failedLookups.isEmpty()) { break; } else { remainingLookups = failedLookups; } } stateRef.set(new LookupUpdateState(builder.build(), ImmutableList.of(), ImmutableList.of())); } catch (InterruptedException | RuntimeException e) { LOG.error(e, "Failed to finish lookup load process."); } finally { executorService.shutdownNow(); } }

Target:
private void startLookups(final List<LookupBean> lookupBeanList) { ImmutableMap.Builder<String, LookupExtractorFactoryContainer> builder = ImmutableMap.builder(); ExecutorService executorService = Execs.multiThreaded( lookupConfig.getNumLookupLoadingThreads(), "LookupReferencesManager-Startup-%s" ); CompletionService<Map.Entry<String, LookupExtractorFactoryContainer>> completionService = new ExecutorCompletionService<>(executorService); try { LOG.info("Starting lookup loading process"); List<LookupBean> remainingLookups = lookupBeanList; for (int i = 0; i < lookupConfig.getLookupStartRetries(); i++) { LOG.info("Round of attempts #%d, [%d] lookups", i + 1, remainingLookups.size()); Map<String, LookupExtractorFactoryContainer> successfulLookups = startLookups(remainingLookups, completionService); builder.putAll(successfulLookups); List<LookupBean> failedLookups = remainingLookups .stream() .filter(l -> !successfulLookups.containsKey(l.getName())) .collect(Collectors.toList()); if (failedLookups.isEmpty()) { break; } else { remainingLookups = failedLookups; } } LOG.info( "Failed to start the following lookups after [%d] attempts: [%s]", lookupConfig.getLookupStartRetries(), remainingLookups ); stateRef.set(new LookupUpdateState(builder.build(), ImmutableList.of(), ImmutableList.of())); } catch (InterruptedException | RuntimeException e) { LOG.error(e, "Failed to finish lookup load process."); } finally { executorService.shutdownNow(); } }