auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static List<Map<Variable, Term>> patternMatch(Term subject, Rule rule, TermContext context) { PatternMatcher matcher = new PatternMatcher(rule.containsAttribute("lemma"), context); boolean failed = true; if (rule.isFunction()) { if (subject instanceof KItem) { KItem kItem = (KItem) subject; Term kLabel = kItem.kLabel(); Term kList = kItem.kList(); if (kLabel.equals(rule.definedKLabel())) { failed = !matcher.patternMatch(kList, ((KItem) rule.leftHandSide()).kList()); } } } else { failed = !matcher.patternMatch(subject, rule.leftHandSide()); } if (failed) { return Collections.emptyList(); } return evaluateConditions(rule, getMultiSubstitutions(matcher.fSubstitution, matcher.multiSubstitutions), context); }

Target:
public static List<Map<Variable, Term>> patternMatch(Term subject, Rule rule, TermContext context) { PatternMatcher matcher = new PatternMatcher( rule.containsAttribute(Attribute.LEMMA_KEY), context); boolean failed = true; if (rule.isFunction()) { if (subject instanceof KItem) { KItem kItem = (KItem) subject; Term kLabel = kItem.kLabel(); Term kList = kItem.kList(); if (kLabel.equals(rule.definedKLabel())) { failed = !matcher.patternMatch(kList, ((KItem) rule.leftHandSide()).kList()); } } } else { failed = !matcher.patternMatch(subject, rule.leftHandSide()); } if (failed) { return Collections.emptyList(); } return evaluateConditions(rule, getMultiSubstitutions(matcher.fSubstitution, matcher.multiSubstitutions), context); }
Source:
protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { Response res = new Response(id); if ((flag & FLAG_EVENT) != 0) { res.setEvent(Response.HEARTBEAT_EVENT); } byte status = header[3]; res.setStatus(status); try { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); if (status == Response.OK) { Object data; if (res.isHeartbeat()) { data = decodeHeartbeatData(channel, in); } else if (res.isEvent()) { data = decodeEventData(channel, in); } else { data = decodeResponseData(channel, in, getRequestData(id)); } res.setResult(data); } else { res.setErrorMessage(in.readUTF()); } } catch (Throwable t) { res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); } return res; } else { Request req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); Object data = null; try { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); if (req.isHeartbeat()) { data = decodeHeartbeatData(channel, in); } else if (req.isEvent()) { data = decodeEventData(channel, in); } else { data = decodeRequestData(channel, in); } } catch (Throwable t) { req.setBroken(true); req.setData(t); } if (!req.isBroken()) { if ((flag & FLAG_EVENT) != 0) { if (data != null && data.equals(Request.READONLY_EVENT)) { req.setEvent(Request.READONLY_EVENT); } else { req.setEvent(Request.HEARTBEAT_EVENT); } } req.setData(data); } else { if ((flag & FLAG_EVENT) != 0) { req.setEvent(true); } } return req; } }

Target:
protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); long id = Bytes.bytes2long(header, 4); if ((flag & FLAG_REQUEST) == 0) { Response res = new Response(id); if ((flag & FLAG_EVENT) != 0) { res.setEvent(Response.HEARTBEAT_EVENT); } byte status = header[3]; res.setStatus(status); try { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); if (status == Response.OK) { Object data; if (res.isHeartbeat()) { data = decodeHeartbeatData(channel, in); } else if (res.isEvent()) { data = decodeEventData(channel, in); } else { data = decodeResponseData(channel, in, getRequestData(id)); } res.setResult(data); } else { res.setErrorMessage(in.readUTF()); } } catch (Throwable t) { res.setStatus(Response.CLIENT_ERROR); res.setErrorMessage(StringUtils.toString(t)); } return res; } else { Request req = new Request(id); req.setVersion(Version.getProtocolVersion()); req.setTwoWay((flag & FLAG_TWOWAY) != 0); if ((flag & FLAG_EVENT) != 0) { req.setEvent(true); } try { ObjectInput in = CodecSupport.deserialize(channel.getUrl(), is, proto); Object data; if (req.isHeartbeat()) { data = decodeHeartbeatData(channel, in); } else if (req.isEvent()) { data = decodeEventData(channel, in); } else { data = decodeRequestData(channel, in); } req.setData(data); } catch (Throwable t) { req.setBroken(true); req.setData(t); } return req; } }
Source:
public static ZipExtraField createExtraField(ZipShort headerId) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Class<?> c = implementations.get(headerId); if (c != null) { return (ZipExtraField) c.getDeclaredConstructor().newInstance(); } UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(headerId); return u; }

Target:
public static ZipExtraField createExtraField(ZipShort headerId) throws InstantiationException, IllegalAccessException { Class<?> c = implementations.get(headerId); if (c != null) { try { return (ZipExtraField) c.getDeclaredConstructor().newInstance(); } catch (InvocationTargetException e) { throw (InstantiationException) new InstantiationException().initCause(e.getTargetException()); } catch (NoSuchMethodException e) { throw (InstantiationException) new InstantiationException().initCause(e); } } UnrecognizedExtraField u = new UnrecognizedExtraField(); u.setHeaderId(headerId); return u; }
Source:
void dispatchLoadInitial(@Nullable Integer position, int initialLoadSize, int pageSize, boolean enablePlaceholders, @NonNull Executor mainThreadExecutor, @NonNull PageResult.Receiver<Value> receiver) { final int convertPosition = position == null ? 0 : Math.max(0, position - initialLoadSize / 2); if (position == null) { position = 0; } else { initialLoadSize = (Math.max(initialLoadSize / pageSize, 2)) * pageSize; final int idealStart = position - initialLoadSize / 2; position = Math.max(0, idealStart / pageSize * pageSize); } mSource.dispatchLoadInitial(false, position, initialLoadSize, pageSize, mainThreadExecutor, receiver); }

Target:
void dispatchLoadInitial(@Nullable Integer position, int initialLoadSize, int pageSize, boolean enablePlaceholders, @NonNull Executor mainThreadExecutor, @NonNull PageResult.Receiver<Value> receiver) { if (position == null) { position = 0; } else { initialLoadSize = (Math.max(initialLoadSize / pageSize, 2)) * pageSize; final int idealStart = position - initialLoadSize / 2; position = Math.max(0, idealStart / pageSize * pageSize); } mSource.dispatchLoadInitial(false, position, initialLoadSize, pageSize, mainThreadExecutor, receiver); }
Source:
public ActiveFilterItem getActiveFilterFromColumnFilter(ColumnFilter columnFilter) { String lableValue = columnFilter.toString(); if (columnFilter instanceof CoreFunctionFilter) { lableValue = ((CoreFunctionFilter) columnFilter).getLabelValue(); if (lableValue == null || lableValue.length() == 0) { lableValue = columnFilter.toString(); } } return new ActiveFilterItem<>(columnFilter.getColumnId(), lableValue, null, null, v -> removeActiveFilter(columnFilter)); }

Target:
public ActiveFilterItem getActiveFilterFromColumnFilter(ColumnFilter columnFilter) { String labelValue = columnFilter.toString(); if (columnFilter instanceof CoreFunctionFilter) { labelValue = ((CoreFunctionFilter) columnFilter).getLabelValue(); if (labelValue == null || labelValue.isEmpty()) { labelValue = columnFilter.toString(); } } return new ActiveFilterItem<>(columnFilter.getColumnId(), labelValue, null, null, v -> removeActiveFilter(columnFilter)); }
Source:
public void setUp() throws Exception { presenter = new FormEntryPatientListPresenter(view); PowerMockito.mockStatic(StringUtils.class); PowerMockito.mockStatic(FilterUtil.class); patientDAO = Mockito.mock(PatientDAO.class); PowerMockito.whenNew(PatientDAO.class).withNoArguments().thenReturn(patientDAO); }

Target:
public void setUp() { super.setUp(); presenter = new FormEntryPatientListPresenter(view, patientDAO); PowerMockito.mockStatic(StringUtils.class); patientList = new ArrayList<Patient>(); }
Source:
CLITerminalConnection(Terminal terminal) { super(terminal); interceptor = (int[] ints) -> { CliLogger.ROOT_LOGGER.writingCodePoints(Parser.stripAwayAnsiCodes(Parser.fromCodePoints(ints))); CLITerminalConnection.super.stdoutHandler().accept(ints); }; }

Target:
CLITerminalConnection(Terminal terminal) { super(terminal); interceptor = (int[] ints) -> { if (CliLogger.ROOT_LOGGER.isTraceEnabled()) { CliLogger.ROOT_LOGGER.tracef("Writing %s", Parser.stripAwayAnsiCodes(Parser.fromCodePoints(ints))); } CLITerminalConnection.super.stdoutHandler().accept(ints); }; }
Source:
public void beforeStageStarts() { UI.status = new StatusUIStub(); UI.events = new EventDispatcherStub(); Preferences prefs = Preferences.create(TestController.TEST_DIRECTORY, TestController.TEST_SESSION_CONFIG_FILENAME, TestController.TEST_USER_CONFIG_FILENAME); prefs.setLastLoginCredentials("test", "test"); prefs.setLastViewedRepository("test/test"); RepoIO testIO = TestController.createTestingRepoIO(Optional.empty()); testIO.setRepoOpControl(TestUtils.createRepoOpControlWithEmptyModels(testIO)); try { testIO.openRepository("test2/test2").get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }

Target:
public void beforeStageStarts() { UI.status = new StatusUIStub(); UI.events = new EventDispatcherStub(); Preferences prefs = TestController.createTestPreferences(); prefs.setLastLoginCredentials("test", "test"); prefs.setLastViewedRepository("test/test"); RepoIO testIO = TestController.createTestingRepoIO(Optional.empty()); testIO.setRepoOpControl(TestUtils.createRepoOpControlWithEmptyModels(testIO)); try { testIO.openRepository("test2/test2").get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }
Source:
public static Charset parseEncoding(final byte[] b) { final int enc = encoding(b, 0); if (enc < 0) return Constants.CHARSET; final int lf = nextLF(b, enc); String decoded = decode(Constants.CHARSET, b, enc, lf - 1); if ("latin-1".equals(decoded)) { return Charset.forName("ISO-8859-1"); } return Charset.forName(decoded); }

Target:
public static Charset parseEncoding(final byte[] b) { final int enc = encoding(b, 0); if (enc < 0) return Constants.CHARSET; final int lf = nextLF(b, enc); String decoded = decode(Constants.CHARSET, b, enc, lf - 1); try { return Charset.forName(decoded); } catch (IllegalCharsetNameException badName) { Charset aliased = encodingAliases.get(StringUtils .toLowerCase(decoded)); if (aliased != null) return aliased; throw badName; } catch (UnsupportedCharsetException badName) { Charset aliased = encodingAliases.get(StringUtils .toLowerCase(decoded)); if (aliased != null) return aliased; throw badName; } }
Source:
public Transfer getSiblingMeta( final String extension ) { if ( resource.isRoot() ) { return null; } final String generatedPath = provider.getGeneratedPath( resource ); final String named = generatedPath + extension; final Transfer tx = this; logger.debug( "Creating meta-transfer sibling for: {}", String.format( "%s with name: %s (parent: %s)", tx, named, tx.getParent() ) ); return provider.getTransfer( new ConcreteResource( getLocation(), named ) ); }

Target:
public Transfer getSiblingMeta( final String extension ) { if ( resource.isRoot() ) { return null; } final String named = getStoragePath() + extension; final Transfer tx = this; logger.debug( "Creating meta-transfer sibling for: {}", String.format( "%s with name: %s (parent: %s)", tx, named, tx.getParent() ) ); return provider.getTransfer( new ConcreteResource( getLocation(), named ) ); }
Source:
public long getValue(String path) { return distributedAtomicLongCaches.stream() .map(distAtomicLong -> { try { return distAtomicLong.get(path).get().preValue(); } catch (Exception e) { throw new ZookeeperCounterException(path, e); } }) .reduce(0L, (a, b) -> a + b); }

Target:
public long getValue(String path) { return distributedAtomicLongCaches.stream() .map(distAtomicLong -> getValue(distAtomicLong, path)) .reduce(0L, (a, b) -> a + b); }
Source:
protected boolean canDoAction() { if (getParameters().getRngDevice() == null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_RNG_MUST_BE_SPECIFIED); } if (getParameters().getRngDevice().getVmId() == null || cachedEntity == null) { return failCanDoAction(getParameters().isVm() ? VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND : VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); } VDSGroup cluster = getVdsGroup(); if (cluster == null || !FeatureSupported.virtIoRngSupported(cluster.getcompatibility_version())) { return failCanDoAction(VdcBllMessages.ACTION_NOT_SUPPORTED_FOR_CLUSTER_POOL_LEVEL); } if (getParameters().isVm() && getVm() != null && getVm().isRunningOrPaused()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } return true; }

Target:
protected boolean canDoAction() { if (getParameters().getRngDevice().getVmId() == null || cachedEntity == null) { return failCanDoAction(getParameters().isVm() ? VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND : VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); } if (getParameters().isVm() && getVm() != null && getVm().isRunningOrPaused()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } return true; }
Source:
public void testParseSafeCastExpr() { String expr = "this instanceof Person && ((Person)this).name == \"Mark\""; Expression exssion = parseExpression( parser, expr ).getExpr(); }

Target:
public void testParseSafeCastExpr() { String expr = "this instanceof Person && ((Person) this).name == \"Mark\""; Expression expression = parseExpression( parser, expr ).getExpr(); assertEquals(expr, printConstraint(expression)); }
Source:
public void setComment(String newComment) { if (newComment == null) { this.comment = null; return; } Exception iae = new IllegalArgumentException( MessageFormat.format( JGitText.get().argumentIsNotAValidCommentString, newComment)); if (newComment.contains("\n") || newComment.contains("\r")) { throw new JGitInternalException(iae.getMessage(), iae); } if (newComment.trim().length() == 0 || newComment.startsWith("#")) { this.comment = newComment; return; } throw new JGitInternalException(iae.getMessage(), iae); }

Target:
public void setComment(String newComment) { if (newComment == null) { this.comment = null; return; } if (newComment.contains("\n") || newComment.contains("\r")) throw createInvalidCommentException(newComment); if (newComment.trim().length() == 0 || newComment.startsWith("#")) { this.comment = newComment; return; } throw createInvalidCommentException(newComment); }
Source:
protected void onError(HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException { resp.getWriter().print( "<h3>É preciso autorizar o uso do Google+ para ter acesso ao Tech Gallery</h3>"); resp.setStatus(200); resp.addHeader("Content-Type", "text/html"); }

Target:
protected void onError(HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException { resp.getWriter().print( "<h3>É preciso autorizar o uso do Google+ para ter acesso ao Tech Gallery</h3>"); resp.setStatus(403); resp.addHeader("Content-Type", "text/html"); }
Source:
void dispatchDestroy() { mDestroyed = true; execPendingActions(true); dispatchStateChange(Fragment.INITIALIZING); mHost = null; mContainer = null; mParent = null; if (mOnBackPressedDispatcher != null) { mOnBackPressedCallback.remove(); mOnBackPressedDispatcher = null; } if (!mExitAnimationCancellationSignals.isEmpty()) { for (Fragment fragment: mExitAnimationCancellationSignals.keySet()) { cancelExitAnimation(fragment); } } }

Target:
void dispatchDestroy() { mDestroyed = true; execPendingActions(true); endAnimatingAwayFragments(); dispatchStateChange(Fragment.INITIALIZING); mHost = null; mContainer = null; mParent = null; if (mOnBackPressedDispatcher != null) { mOnBackPressedCallback.remove(); mOnBackPressedDispatcher = null; } }
Source:
private AbstractReplyProducingMessageHandler configureHandler(ServiceActivatingHandler handler) { postProcessReplyProducer(handler); return handler; }

Target:
private MessageHandler configureHandler(ServiceActivatingHandler handler) { postProcessReplyProducer(handler); return handler; }
Source:
public void destroy() throws Exception { AuthorityServiceFactory.getInstance().getAuthorityIndexingService().cleanIndex(); configurationService.setProperty("plugin.named.org.dspace.content.authority.ChoiceAuthority", null); configurationService.setProperty("solr.authority.server", null); configurationService.setProperty("choices.plugin.dc.contributor.author", null); configurationService.setProperty("choices.presentation.dc.contributor.author", null); configurationService.setProperty("authority.controlled.dc.contributor.author", null); configurationService.setProperty("authority.author.indexer.field.1", null); super.destroy(); }

Target:
public void destroy() throws Exception { AuthorityServiceFactory.getInstance().getAuthorityIndexingService().cleanIndex(); super.destroy(); }
Source:
private void replaceSearchResult(List<MapBean> maps, Pane pane) { JavaFxUtil.assertBackgroundThread(); Platform.runLater(() -> { pane.getChildren().clear(); }); ObservableList<Node> children = pane.getChildren(); List<MapCardController> controllers = maps.parallelStream() .map(map -> { MapCardController controller = uiService.loadFxml("theme/vault/map/map_card.fxml"); controller.setMap(map); controller.setOnOpenDetailListener(this::onShowMapDetail); return controller; }).collect(Collectors.toList()); Iterators.partition(controllers.iterator(), BATCH_SIZE).forEachRemaining(mapCardControllers -> Platform.runLater(() -> { for (MapCardController mapCardController : mapCardControllers) { children.add(mapCardController.getRoot()); } })); }

Target:
private void replaceSearchResult(List<MapBean> maps, Pane pane) { List<MapCardController> controllers = maps.parallelStream() .map(map -> { MapCardController controller = uiService.loadFxml("theme/vault/map/map_card.fxml"); controller.setMap(map); controller.setOnOpenDetailListener(this::onShowMapDetail); return controller; }).collect(Collectors.toList()); Platform.runLater(() -> { pane.getChildren().clear(); }); JavaFxUtil.assertBackgroundThread(); Iterators.partition(controllers.iterator(), BATCH_SIZE).forEachRemaining(mapCardControllers -> Platform.runLater(() -> { for (MapCardController mapCardController : mapCardControllers) { pane.getChildren().add(mapCardController.getRoot()); } })); }
Source:
public static boolean isMatching(final String filterText, IResource resource) { if (StringUtils.isBlank(filterText)) { return true; } final Set<String> items = new HashSet<>(Arrays.asList( filterText.replaceAll(",", " ").toLowerCase().split(" "))); if (containsAll(resource.getName(), items)) { return true; } return resource.accept(new CapabilityVisitor<ITags, Boolean>() { @Override public Boolean visit(ITags capability) { for (String item : items) { if (!inCollection(item, capability.getTags())) { return false; } } return true; } }, Boolean.FALSE); }

Target:
public static boolean isMatching(final String filterText, IResource resource) { if(resource == null) { return true; } return resource.accept(new CapabilityVisitor<ITags, Boolean>() { @Override public Boolean visit(ITags capability) { return isMatching(filterText, resource.getName(), capability.getTags()); } }, Boolean.FALSE); }
Source:
Optional<Route> findRouteByCost(final Territory start, final Territory end) { Preconditions.checkNotNull(start); Preconditions.checkNotNull(end); if (start.equals(end)) { return Optional.of(new Route(start)); } final Map<Territory, Territory> previous = new HashMap<>(); previous.put(start, null); final Queue<Territory> toVisit = new ArrayDeque<>(); toVisit.add(start); final Map<Territory, BigDecimal> routeCosts = new HashMap<>(); routeCosts.put(start, BigDecimal.ZERO); BigDecimal minCost = new BigDecimal(Integer.MAX_VALUE); while (!toVisit.isEmpty()) { final Territory currentTerritory = toVisit.remove(); if (routeCosts.get(currentTerritory).compareTo(minCost) >= 0) { continue; } for (final Territory neighbor : map.getNeighborsValidatingCanals(currentTerritory, condition, units, player)) { final BigDecimal routeCost = routeCosts.get(currentTerritory).add(getMaxMovementCost(neighbor)); if (!previous.containsKey(neighbor) || routeCost.compareTo(routeCosts.get(neighbor)) < 0) { previous.put(neighbor, currentTerritory); routeCosts.put(neighbor, routeCost); if (neighbor.equals(end) && routeCost.compareTo(minCost) < 0) { minCost = routeCost; break; } toVisit.add(neighbor); } } } return (minCost.compareTo(new BigDecimal(Integer.MAX_VALUE)) == 0) ? Optional.empty() : Optional.of(getRoute(start, end, previous)); }

Target:
Optional<Route> findRouteByCost(final Territory start, final Territory end) { return findRouteByCost(start, end, this::getMaxMovementCost); }
Source:
public ValueMatcher makeValueMatcher(final FloatColumnSelector selector, final String value) { final float matchVal = DimensionHandlerUtils.convertObjectToFloat(value); return new ValueMatcher() { @Override public boolean matches() { return selector.get() == matchVal; } }; }

Target:
public ValueMatcher makeValueMatcher(final FloatColumnSelector selector, final String value) { final Float matchVal = DimensionHandlerUtils.convertObjectToFloat(value); if (matchVal == null) { return BooleanValueMatcher.of(false); } final int matchValIntBits = Float.floatToIntBits(matchVal); return new ValueMatcher() { @Override public boolean matches() { return Float.floatToIntBits(selector.get()) == matchValIntBits; } }; }
Source:
public void showDuplicatePicturePopup() { String uploadTitleFormat = getString(R.string.upload_title_duplicate); DialogUtil.showAlertDialog(getActivity(), getString(R.string.warning), String.format(Locale.getDefault(), uploadTitleFormat, uploadItem.getFileName()), getString(R.string.cancel), getString(R.string.upload_image), () -> { }, () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); }); }

Target:
public void showDuplicatePicturePopup() { String uploadTitleFormat = getString(R.string.upload_title_duplicate); DialogUtil.showAlertDialog(getActivity(), getString(R.string.duplicate_image_found), String.format(Locale.getDefault(), uploadTitleFormat, uploadItem.getFileName()), getString(R.string.upload), getString(R.string.cancel), () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); }, null); }
Source:
public Request authenticate(Route route, final Response response) throws IOException { logger.warn(response.toString()); final AuthResponse currentAuth = loginPrefs.getCurrentAuth(); if (null == currentAuth || null == currentAuth.refresh_token) { return null; } String response_body = response.peekBody(200).string(); switch (getErrorCode(response_body)) { case TOKEN_EXPIRED_ERROR_MESSAGE: break; case TOKEN_NONEXISTENT_ERROR_MESSAGE: case TOKEN_INVALID_GRANT_ERROR_MESSAGE: if (!response.request().headers().get("Authorization").split(" ")[1].equals(currentAuth.access_token)) { return response.request().newBuilder() .header("Authorization", currentAuth.token_type + " " + currentAuth.access_token) .build(); } default: return null; } final AuthResponse refreshedAuth; try { refreshedAuth = refreshAccessToken(currentAuth); } catch (HttpResponseStatusException e) { return null; } return response.request().newBuilder() .header("Authorization", refreshedAuth.token_type + " " + refreshedAuth.access_token) .build(); }

Target:
public synchronized Request authenticate(Route route, final Response response) throws IOException { logger.warn(response.toString()); final AuthResponse currentAuth = loginPrefs.getCurrentAuth(); if (null == currentAuth || null == currentAuth.refresh_token) { return null; } String errorCode = getErrorCode(response.peekBody(200).string()); if (errorCode != null) { switch (errorCode) { case TOKEN_EXPIRED_ERROR_MESSAGE: final AuthResponse refreshedAuth; try { refreshedAuth = refreshAccessToken(currentAuth); } catch (HttpResponseStatusException e) { return null; } return response.request().newBuilder() .header("Authorization", refreshedAuth.token_type + " " + refreshedAuth.access_token) .build(); case TOKEN_NONEXISTENT_ERROR_MESSAGE: case TOKEN_INVALID_GRANT_ERROR_MESSAGE: if (!response.request().headers().get("Authorization").split(" ")[1].equals(currentAuth.access_token)) { return response.request().newBuilder() .header("Authorization", currentAuth.token_type + " " + currentAuth.access_token) .build(); } } } return null; }
Source:
public void parse() { URI workingDirURI = null; try { workingDirURI = new URI(workingDir.toPortableString()); } catch (URISyntaxException e) { e.printStackTrace(); } String cmd = getCommand(workingDirURI.getPath()); performCommand(cmd, 1); }

Target:
public void parse() { URI workingDirURI = null; try { workingDirURI = new URI(workingDir.toPortableString()); } catch (URISyntaxException e) { MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.MsgProxyError, Messages.MsgProxyError); } String cmd = getCommand(workingDirURI.getPath()); performCommand(cmd, 1); }
Source:
public void setNumThreads(final Integer numThreads) { m_threads = ConfigUtils.assertNotNull(numThreads, "threads"); }

Target:
public void setNumThreads(final Integer numThreads) { m_threads = numThreads; }
Source:
public static void killAllSpawnedHadoopJobs(String logFilePath, Logger log) { Set<String> allSpawnedJobs = findApplicationIdFromLog(logFilePath, log); log.info("applicationIds to kill: " + allSpawnedJobs); for (String appId : allSpawnedJobs) { try { killJobOnCluster(appId, log); } catch (Throwable t) { log.warn("something happened while trying to kill this job: " + appId, t); } } }

Target:
public static Set<String> killAllSpawnedHadoopJobs(String logFilePath, Logger log) { Set<String> allSpawnedJobs = findApplicationIdFromLog(logFilePath, log); log.info("applicationIds to kill: " + allSpawnedJobs); for (String appId : allSpawnedJobs) { try { killJobOnCluster(appId, log); } catch (Throwable t) { log.warn("something happened while trying to kill this job: " + appId, t); } } return allSpawnedJobs; }
Source:
public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT); RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); cacheManager.administration() .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache("people-multimap", "org.infinispan.DIST_SYNC"); MultimapCacheManager multimapCacheManager = RemoteMultimapCacheManagerFactory.from(cacheManager); RemoteMultimapCache<Integer, String> people = multimapCacheManager.get("people"); people.put(2016, "Alberto"); people.put(2016, "Oihana"); people.put(2016, "Roman"); people.put(2016, "Ane"); people.put(2017, "Paula"); people.put(2017, "Aimar"); people.put(2018, "Elaia"); people.get(2016).whenComplete((v, ex) -> { System.out.println(v); }).join(); cacheManager.stop(); }

Target:
public static void main(String[] args) throws Exception { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("127.0.0.1") .port(ConfigurationProperties.DEFAULT_HOTROD_PORT); RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build()); cacheManager.administration() .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE) .getOrCreateCache(PEOPLE_MULTIMAP, "org.infinispan.DIST_SYNC"); MultimapCacheManager multimapCacheManager = RemoteMultimapCacheManagerFactory.from(cacheManager); RemoteMultimapCache<Integer, String> people = multimapCacheManager.get(PEOPLE_MULTIMAP); people.put(2016, "Alberto"); people.put(2016, "Oihana"); people.put(2016, "Roman"); people.put(2016, "Ane"); people.put(2017, "Paula"); people.put(2017, "Aimar"); people.put(2018, "Elaia"); people.get(2016).whenComplete((v, ex) -> { System.out.println(v); }).join(); cacheManager.stop(); }
Source:
public int countIssuesShown() throws InterruptedException, ExecutionException { FutureTask countIssues = new FutureTask(((ListPanel) TestController.getUI().getPanelControl().getPanel(0))::getIssueCount); PlatformEx.runAndWait(countIssues); return (int) countIssues.get(); }

Target:
public int countIssuesShown() throws InterruptedException, ExecutionException { FutureTask<Integer> countIssues = new FutureTask<Integer>(((ListPanel) TestController.getUI().getPanelControl().getPanel(0))::getIssueCount); PlatformEx.runAndWait(countIssues); return (int) countIssues.get(); }
Source:
public void pushAdd(CollectorRegistry registry, String job, Map<String, String> groupingKey) throws IOException { HttpPost request = new HttpPost(); request.setEntity(createOutputEntity(registry)); doRequest(registry, job, groupingKey, request); }

Target:
public void pushAdd(CollectorRegistry registry, String job, Map<String, String> groupingKey) throws IOException { HttpPost request = new HttpPost(); request.setEntity(createOutputEntity(registry)); doRequest(job, groupingKey, request); }
Source:
public void testGetOrComputeIfAbsentContention() throws InterruptedException { final OnHeapStore<Long, String> store = newStore(); int threads = 5; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threads); Runnable runnable = new Runnable() { @Override public void run() { try { startLatch.await(); } catch (InterruptedException e) { fail("Got an exception waiting to start thread " + e); } try { ValueHolder<String> result = store.getOrComputeIfAbsent(42L, new Function<Long, ValueHolder<String>>() { @Override public ValueHolder<String> apply(Long aLong) { return new CopiedOnHeapValueHolder<String>("theAnswer!", System.currentTimeMillis(), -1, new IdentityCopier<String>()); } }); assertThat(result.value(), is("theAnswer!")); endLatch.countDown(); } catch (Exception e) { e.printStackTrace(); fail("Got an exception " + e); } } }; for (int i = 0; i < threads; i++) { new Thread(runnable).start(); } startLatch.countDown(); boolean result = endLatch.await(2, TimeUnit.SECONDS); if (!result) { fail("Wait expired before completion, logs should have exceptions"); } }

Target:
public void testGetOrComputeIfAbsentContention() throws InterruptedException { final OnHeapStore<Long, String> store = newStore(); int threads = 10; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threads); Runnable runnable = new Runnable() { @Override public void run() { try { startLatch.await(); } catch (InterruptedException e) { fail("Got an exception waiting to start thread " + e); } try { ValueHolder<String> result = store.getOrComputeIfAbsent(42L, new Function<Long, ValueHolder<String>>() { @Override public ValueHolder<String> apply(Long aLong) { return new CopiedOnHeapValueHolder<String>("theAnswer!", System.currentTimeMillis(), -1, new IdentityCopier<String>()); } }); assertThat(result.value(), is("theAnswer!")); endLatch.countDown(); } catch (Exception e) { e.printStackTrace(); fail("Got an exception " + e); } } }; for (int i = 0; i < threads; i++) { new Thread(runnable).start(); } startLatch.countDown(); boolean result = endLatch.await(2, TimeUnit.SECONDS); if (!result) { fail("Wait expired before completion, logs should have exceptions"); } }
Source:
public void terminate() { for (PHPCheck check : checks) { check.terminate(); } }

Target:
public void terminate() { for (PHPCheck check : checks) { try { check.terminate(); } catch (Exception e) { LOG.warn("An error occurred while trying to terminate checks:", e); } } }
Source:
public IMap throttleSubmissionMap() { final HazelcastTicketRegistryProperties hz = casProperties.getTicket().getRegistry().getHazelcast(); final int timeout = Duration.parse(casProperties.getAuthn().getThrottle().getSchedule().getRepeatInterval()).toStandardSeconds().getSeconds(); final HazelcastConfigurationFactory factory = new HazelcastConfigurationFactory(); LOGGER.debug("Creating to record failed logins for throttling with timeout set to [{}]", MAP_KEY, timeout); final MapConfig ipMapConfig = factory.buildMapConfig(hz, MAP_KEY, timeout); hazelcastInstance.getConfig().addMapConfig(ipMapConfig); return hazelcastInstance.getMap(MAP_KEY); }

Target:
public IMap throttleSubmissionMap() { final HazelcastTicketRegistryProperties hz = casProperties.getTicket().getRegistry().getHazelcast(); final long timeout = Beans.newDuration(casProperties.getAuthn().getThrottle().getSchedule().getRepeatInterval()).getSeconds(); final HazelcastConfigurationFactory factory = new HazelcastConfigurationFactory(); LOGGER.debug("Creating to record failed logins for throttling with timeout set to [{}]", MAP_KEY, timeout); final MapConfig ipMapConfig = factory.buildMapConfig(hz, MAP_KEY, timeout); hazelcastInstance.getConfig().addMapConfig(ipMapConfig); return hazelcastInstance.getMap(MAP_KEY); }
Source:
public void endBucket(ComputationContext context, int bucketSize) { String commandId = getCurrentCommand().getId(); try { String csv = out.toString(UTF_8.toString()); String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); String header = csv.substring(0, csv.indexOf(recordSeparator)); String data = csv.substring(csv.indexOf(recordSeparator) + recordSeparator.length()); DataBucket dataBucket = new DataBucket(commandId, bucketSize, data.getBytes(UTF_8), header.getBytes(UTF_8), new byte[] {}); Record record = Record.of(commandId, BulkCodecs.getDataBucketCodec().encode(dataBucket)); context.produceRecord(OUTPUT_1, record); out = null; } catch (UnsupportedEncodingException e) { getLog().error(e, e); } }

Target:
public void endBucket(ComputationContext context, int bucketSize) { String commandId = getCurrentCommand().getId(); try { String csv = out.toString(UTF_8.name()); String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); String header = getHeader(csv, recordSeparator); String data = getData(csv, recordSeparator); DataBucket dataBucket = new DataBucket(commandId, bucketSize, data.getBytes(UTF_8), header.getBytes(UTF_8), new byte[0]); Record record = Record.of(commandId, BulkCodecs.getDataBucketCodec().encode(dataBucket)); context.produceRecord(OUTPUT_1, record); out = null; } catch (UnsupportedEncodingException e) { getLog().error(e, e); } }
Source:
public void migrateHomeWorkParkingToFavorites() { FavouritesDbHelper favorites = ctx.getFavorites(); favorites.addFavoritePersonal(getHomePoint(),FavouritesDbHelper.HOME,getHomePointDescription().getName()); favorites.addFavoritePersonal(getWorkPoint(),FavouritesDbHelper.WORK,getWorkPointDescription().getName()); if (OsmandPlugin.getEnabledPlugin(ParkingPositionPlugin.class) != null) { ParkingPositionPlugin parkingPositionPlugin = OsmandPlugin.getEnabledPlugin(ParkingPositionPlugin.class); if(parkingPositionPlugin != null) { favorites.addFavoritePersonal(parkingPositionPlugin.constructParkingPosition(), FavouritesDbHelper.PARKING, ""); } } }

Target:
public void migrateHomeWorkParkingToFavorites() { FavouritesDbHelper favorites = ctx.getFavorites(); if (getHomePoint() != null) { favorites.setHomePoint(getHomePoint(), getHomePointDescription()); } if (getWorkPoint() != null) { favorites.setWorkPoint(getWorkPoint(), getWorkPointDescription()); } }
Source:
public void onDisplay(NavigateEvent navigateEvent) { if (!tournamentListPane.getChildren().isEmpty()) { return; } tournamentDetailWebView.setContextMenuEnabled(false); webViewConfigurer.configureWebView(tournamentDetailWebView); tournamentService.getAllTournaments() .thenAccept(tournaments -> { boolean firstItemSelected = false; tournaments.sort((o1, o2) -> -o1.getCreatedAt().compareTo(o2.getCreatedAt())); for (TournamentBean tournamentBean : tournaments) { TournamentListItemController tournamentListItemController = createAndAddTournamentItem(tournamentBean); if (!firstItemSelected) { tournamentListItemController.onMouseClicked(); firstItemSelected = true; } } }); }

Target:
public void onDisplay(NavigateEvent navigateEvent) { if (!tournamentListPane.getChildren().isEmpty()) { return; } tournamentDetailWebView.setContextMenuEnabled(false); webViewConfigurer.configureWebView(tournamentDetailWebView); tournamentService.getAllTournaments() .thenAccept(tournaments -> { Platform.runLater(() -> { boolean firstItemSelected = false; tournaments.sort((o1, o2) -> -o1.getCreatedAt().compareTo(o2.getCreatedAt())); for (TournamentBean tournamentBean : tournaments) { TournamentListItemController tournamentListItemController = createAndAddTournamentItem(tournamentBean); if (!firstItemSelected) { tournamentListItemController.onMouseClicked(); firstItemSelected = true; } } }); }).exceptionally(throwable -> { log.error("Tournaments could not be loaded", throwable); return null; }); }
Source:
public String getText(final Object element) { if (element instanceof FieldToContractInputMapping) { final FieldToContractInputMapping mapping = (FieldToContractInputMapping) element; return new Boolean(!mapping.getField().isNullable()).toString(); } return super.getText(element); }

Target:
public String getText(final Object element) { if (element instanceof FieldToContractInputMapping) { final FieldToContractInputMapping mapping = (FieldToContractInputMapping) element; return Boolean.valueOf(!mapping.getField().isNullable()).toString(); } return super.getText(element); }
Source:
public <T> Optional<T> get(EventContextKey<T> key) { checkNotNull(key, "EventContextKey cannot be null"); return Optional.ofNullable((T) this.entries.get(key.getId())); }

Target:
public <T> Optional<T> get(EventContextKey<T> key) { checkNotNull(key, "EventContextKey cannot be null"); return Optional.ofNullable((T) this.entries.get(key)); }
Source:
public BVDesignTrialInstance(final Integer instanceNumber, final List<Map<String, String>> rows) { super(); this.instanceNumber = instanceNumber; this.rows = rows; }

Target:
public BVDesignTrialInstance(final Integer instanceNumber, final List<Map<String, String>> rows) { this.instanceNumber = instanceNumber; this.rows = rows; }
Source:
private static File getNativeLibraryFile(String libname) { String pathFormat = "/org/voltdb/native/%s/x86_64"; String libPath = null; if (System.getProperty("os.name").toLowerCase().contains("mac")) { libPath = String.format(pathFormat, "Mac"); } else { libPath = String.format(pathFormat, "Linux"); } String libFileName = System.mapLibraryName(libname); if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { if (System.getProperty("os.name").toLowerCase().contains("mac")) { libFileName = "lib" + libname + ".jnilib"; } if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { String msg = "Could not find library resource using path: " + libPath + "/" + libFileName; s_hostLog.warn(msg); throw new RuntimeException(msg); } } File tmpFilePath = new File(System.getProperty(VOLT_TMP_DIR, System.getProperty("java.io.tmpdir"))); if (s_hostLog.isDebugEnabled()) { s_hostLog.debug("Temp directory to which shared libs are extracted is: " + tmpFilePath.getAbsolutePath()); } try { return loadLibraryFile(libPath, libFileName, tmpFilePath.getAbsolutePath()); } catch(IOException e) { s_hostLog.error("Error loading Volt library file from jar", e); throw new RuntimeException(e); } }

Target:
private static File getNativeLibraryFile(String libname) { String pathFormat = "/org/voltdb/native/%s/x86_64"; String libPath = null; String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("mac")) { libPath = String.format(pathFormat, "Mac"); } else if (osName.contains("linux")) { libPath = String.format(pathFormat, "Linux"); } else { throw new RuntimeException("Unsupported system: " + osName); } String libFileName = System.mapLibraryName(libname); if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { if (osName.contains("mac")) { libFileName = "lib" + libname + ".jnilib"; } if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { String msg = "Could not find library resource using path: " + libPath + "/" + libFileName; s_hostLog.warn(msg); throw new RuntimeException(msg); } } File tmpFilePath = new File(System.getProperty(VOLT_TMP_DIR, System.getProperty("java.io.tmpdir"))); if (s_hostLog.isDebugEnabled()) { s_hostLog.debug("Temp directory to which shared libs are extracted is: " + tmpFilePath.getAbsolutePath()); } try { return loadLibraryFile(libPath, libFileName, tmpFilePath.getAbsolutePath()); } catch(IOException e) { s_hostLog.error("Error loading Volt library file from jar", e); throw new RuntimeException(e); } }
Source:
public void clearPrivateMessageFields() { this.toField.clear(); this.titleField.clear(); this.messageField.clear(); }

Target:
public void clearPrivateMessageFields() { info("Clearing all message fields."); this.toField.clear(); this.titleField.clear(); this.messageField.clear(); }
Source:
public Response updateAssetRecord(@PathParam("nodeCriteria") final String nodeCriteria, final MultivaluedMapImpl params) { OnmsNode node = m_nodeDao.get(nodeCriteria); if (node == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Can't find node " + nodeCriteria); } OnmsAssetRecord assetRecord = getAssetRecord(node); if (assetRecord == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Node " + node + " could not update "); } if (assetRecord.getGeolocation() == null) { assetRecord.setGeolocation(new OnmsGeolocation()); } LOG.debug("updateAssetRecord: updating asset {}", assetRecord); boolean modified = false; BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(assetRecord); wrapper.registerCustomEditor(Date.class, new ISO8601DateEditor()); for(String key : params.keySet()) { if (wrapper.isWritableProperty(key)) { String stringValue = params.getFirst(key); Object value = wrapper.convertIfNecessary(stringValue, (Class<?>)wrapper.getPropertyType(key)); wrapper.setPropertyValue(key, value); modified = true; } } if (modified) { LOG.debug("updateAssetRecord: assetRecord updated", assetRecord); m_assetRecordDao.update(assetRecord); try { sendEvent(EventConstants.ASSET_INFO_CHANGED_EVENT_UEI, node.getId()); } catch (EventProxyException e) { throw getException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } return Response.noContent().build(); } return Response.notModified().build(); }

Target:
public Response updateAssetRecord(@PathParam("nodeCriteria") final String nodeCriteria, final MultivaluedMapImpl params) { OnmsNode node = m_nodeDao.get(nodeCriteria); if (node == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Can't find node " + nodeCriteria); } OnmsAssetRecord assetRecord = getAssetRecord(node); if (assetRecord == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Node " + node + " could not update "); } if (assetRecord.getGeolocation() == null) { assetRecord.setGeolocation(new OnmsGeolocation()); } LOG.debug("updateAssetRecord: updating asset {}", assetRecord); boolean modified = false; BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(assetRecord); wrapper.registerCustomEditor(Date.class, new ISO8601DateEditor()); for(String key : params.keySet()) { if (wrapper.isWritableProperty(key)) { String stringValue = params.getFirst(key); Object value = wrapper.convertIfNecessary(stringValue, (Class<?>)wrapper.getPropertyType(key)); wrapper.setPropertyValue(key, value); modified = true; } } if (modified) { LOG.debug("updateAssetRecord: assetRecord updated", assetRecord); m_assetRecordDao.saveOrUpdate(assetRecord); try { sendEvent(EventConstants.ASSET_INFO_CHANGED_EVENT_UEI, node.getId()); } catch (EventProxyException e) { throw getException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } return Response.noContent().build(); } return Response.notModified().build(); }
Source:
private void convert(JCas aJCas, PrintWriter aOut) { int i = 30; Type neType = JCasUtil.getType(aJCas, NamedEntity.class); Feature neValue = neType.getFeatureByBaseName("value"); IobEncoder neEncoder = new IobEncoder(aJCas.getCas(), neType, neValue, false); Map<Sentence, Collection<NamedEntity>> idx = JCasUtil.indexCovered(aJCas, Sentence.class, NamedEntity.class); Collection<NamedEntity> coveredNEs; for (Sentence sentence : select(aJCas, Sentence.class)) { if (i < 0) { break; } coveredNEs = idx.get(sentence); if (coveredNEs.isEmpty()) { continue; } HashMap<Token, Row> ctokens = new LinkedHashMap<>(); List<Token> tokens = selectCovered(Token.class, sentence); for (Token token : tokens) { Row row = new Row(); row.token = token; row.ne = neEncoder.encode(token); ctokens.put(row.token, row); } for (Row row : ctokens.values()) { aOut.printf("%s\t%s%n", row.token.getCoveredText(), row.ne); } aOut.println(); i--; } }

Target:
private void convert(JCas aJCas, PrintWriter aOut) { Type neType = JCasUtil.getType(aJCas, NamedEntity.class); Feature neValue = neType.getFeatureByBaseName("value"); IobEncoder neEncoder = new IobEncoder(aJCas.getCas(), neType, neValue, false); Map<Sentence, Collection<NamedEntity>> idx = JCasUtil.indexCovered(aJCas, Sentence.class, NamedEntity.class); Collection<NamedEntity> coveredNEs; for (Sentence sentence : select(aJCas, Sentence.class)) { coveredNEs = idx.get(sentence); if (coveredNEs.isEmpty()) { continue; } HashMap<Token, Row> ctokens = new LinkedHashMap<>(); List<Token> tokens = selectCovered(Token.class, sentence); for (Token token : tokens) { Row row = new Row(); row.token = token; row.ne = neEncoder.encode(token); ctokens.put(row.token, row); } for (Row row : ctokens.values()) { aOut.printf("%s\t%s%n", row.token.getCoveredText(), row.ne); } aOut.println(); } }
Source:
private DeviceKeyStoreRecord getRecordRemotely(final String deviceId) { if(DEFAULT_FACTORY_DEVICE_ID.equals(deviceId)) { LOGGER.warn("Device not properly provisioned, got as a deviceId", deviceId); throw new WebApplicationException(Response.Status.NOT_FOUND); } final HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(DEVICE_ID_ATTRIBUTE_NAME, new AttributeValue().withS(deviceId)); final GetItemRequest getItemRequest = new GetItemRequest() .withTableName(keyStoreTableName) .withKey(key); final GetItemResult getItemResult = dynamoDBClient.getItem(getItemRequest); LOGGER.info("getItemResult = {}", getItemResult.toString()); if(getItemResult.getItem() == null || !getItemResult.getItem().containsKey(AES_KEY_ATTRIBUTE_NAME)) { LOGGER.warn("Did not find anything for device_id = {}", deviceId); throw new WebApplicationException(Response.Status.NOT_FOUND); } final String aesKey = getItemResult.getItem().get(AES_KEY_ATTRIBUTE_NAME).getS(); final String metadata = getItemResult.getItem().get(METADATA).getS(); return new DeviceKeyStoreRecord(censorKey(aesKey), metadata); }

Target:
private Optional<DeviceKeyStoreRecord> getRecordRemotely(final String deviceId) { if(DEFAULT_FACTORY_DEVICE_ID.equals(deviceId)) { LOGGER.warn("Device not properly provisioned, got as a deviceId", deviceId); return Optional.absent(); } final HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(DEVICE_ID_ATTRIBUTE_NAME, new AttributeValue().withS(deviceId)); final GetItemRequest getItemRequest = new GetItemRequest() .withTableName(keyStoreTableName) .withKey(key); final GetItemResult getItemResult = dynamoDBClient.getItem(getItemRequest); LOGGER.info("getItemResult = {}", getItemResult.toString()); if(getItemResult.getItem() == null || !getItemResult.getItem().containsKey(AES_KEY_ATTRIBUTE_NAME)) { LOGGER.warn("Did not find anything for device_id = {}", deviceId); return Optional.absent(); } final String aesKey = getItemResult.getItem().get(AES_KEY_ATTRIBUTE_NAME).getS(); final String metadata = getItemResult.getItem().get(METADATA).getS(); return Optional.of(new DeviceKeyStoreRecord(censorKey(aesKey), metadata)); }
Source:
public void mainTest() { String baseUrl = "localhost:8080/openmrs/ws/rest"; String str = new SwaggerSpecificationCreator(baseUrl).BuildJSON(); assertNotNull(str); }

Target:
public void mainTest() { String baseUrl = "host/openmrs/ws/rest"; String str = new SwaggerSpecificationCreator(baseUrl).BuildJSON(); assertNotNull(str); }
Source:
public void disconnect() { fControl.setState(TerminalState.CLOSED); }

Target:
public void disconnect() { if (fControl != null) { fControl.setState(TerminalState.CLOSED); } }