auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public QuotaInfo apply(ProjectResource rsrc) throws ExecutionException { QuotaInfo qi = new QuotaInfo(); Project.NameKey n = rsrc.getNameKey(); qi.used = repoSizeCache.get(n).get(); QuotaSection qs = quotaFinder.firstMatching(n); if (qs == null) { return qi; } <START> Long maxRepoSize = qs.getMaxRepoSize(); if (maxRepoSize != null) { qi.maxRepoSize = maxRepoSize; } <END> qi.namespace = new NamespaceInfo(); qi.namespace.name = qs.getNamespace(); Long maxTotalSize = qs.getMaxTotalSize(); if (maxTotalSize != null) { qi.namespace.maxTotalSize = maxTotalSize; } return qi; }</code><technical_language>Unnecessary if check. just: qi.maxRepoSize = qs.getMaxRepoSize();</technical_language>

Target:
public QuotaInfo apply(ProjectResource rsrc) throws ExecutionException { QuotaInfo qi = new QuotaInfo(); Project.NameKey n = rsrc.getNameKey(); qi.repoSize = repoSizeCache.get(n).get(); QuotaSection qs = quotaFinder.firstMatching(n); if (qs == null) { return qi; } qi.maxRepoSize = qs.getMaxRepoSize(); qi.namespace = new NamespaceInfo(); qi.namespace.name = qs.getNamespace(); qi.namespace.maxTotalSize = qs.getMaxTotalSize(); return qi; }
Source:
<code>public <T> void removeTask( ScheduledTask<T> task ) { synchronized ( applicationConfiguration ) { List<CScheduledTask> tasks = getCurrentConfiguration( true ); CScheduledTask foundTask = findTask( task.getId(), tasks ); if ( foundTask != null ) { tasks.remove( foundTask ); <START> } <END> if ( NXCM4979DEBUG ) { logger.info( "Task with ID={} removed, config modified.", task.getId(), foundTask != null ? "IS" : "is NOT", new Exception( "This is an exception only to provide caller backtrace" ) ); } try { applicationConfiguration.saveConfiguration(); } catch ( IOException e ) { logger.warn( "Could not save task changes!", e ); } } }</code><technical_language>relevant non-logging code change ^^^</technical_language>

Target:
public <T> void removeTask( ScheduledTask<T> task ) { synchronized ( applicationConfiguration ) { List<CScheduledTask> tasks = getCurrentConfiguration( true ); CScheduledTask foundTask = findTask( task.getId(), tasks ); if ( foundTask != null ) { tasks.remove( foundTask ); } if ( logger.isTraceEnabled() ) { logger.trace( "Task with ID={} removed, config modified.", task.getId(), foundTask != null ? "IS" : "is NOT", new Exception( "This is an exception only to provide caller backtrace" ) ); } try { applicationConfiguration.saveConfiguration(); } catch ( IOException e ) { logger.warn( "Could not save task changes!", e ); } } }
Source:
<code>public static synchronized void refreshAuthz(PerunSession sess) throws InternalErrorException { Utils.checkPerunSession(sess); log.debug("Refreshing authz roles for session {}.", sess); <START> sess.getPerunPrincipal().setRoles(AuthzResolverBlImpl.getRoles(sess)); <END> prepareServiceRoles(sess); if (sess.getPerunPrincipal().getUser() != null) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.SELF, sess.getPerunPrincipal().getUser()); if (sess.getPerunPrincipal().getUser().isServiceUser()) { sess.getPerunPrincipal().getRoles().putAuthzRole(Role.SERVICEUSER); } } if(sess.getPerunClient().getType() == PerunClient.Type.OAUTH) { sess.getPerunPrincipal().getRoles().remove(Role.PERUNADMIN); } sess.getPerunPrincipal().setAuthzInitialized(true); }</code><technical_language>This be: java // Prepare users rights subgroups of groups user is GroupAdmin add AuthzRoles of user AuthzRoles authzRoles = addAllSubgroupsToAuthzRoles(sess, authzResolverImpl.getRoles(sess.getPerunPrincipal().getUser())); in init(sess) method</technical_language>

Target:
public static synchronized void refreshAuthz(PerunSession sess) throws InternalErrorException { Utils.checkPerunSession(sess); log.trace("Refreshing authz roles for session {}.", sess); sess.getPerunPrincipal().setRoles(new AuthzRoles()); prepareServiceRoles(sess); if (sess.getPerunPrincipal().getRoles().isEmpty()) { User user = sess.getPerunPrincipal().getUser(); AuthzRoles roles; if (user == null) { roles = new AuthzRoles(); } else { roles = addAllSubgroupsToAuthzRoles(sess, authzResolverImpl.getRoles(user)); roles.putAuthzRole(Role.SELF, user); if (user.isServiceUser()) { roles.putAuthzRole(Role.SERVICEUSER); } } sess.getPerunPrincipal().setRoles(roles); } if (sess.getPerunClient().getType() == PerunClient.Type.OAUTH) { List<String> oauthScopes = sess.getPerunClient().getScopes(); if(!oauthScopes.contains(PerunClient.PERUN_ADMIN_SCOPE)) { log.debug("removing PERUNADMIN role from session of user {}",sess.getPerunPrincipal().getUserId()); sess.getPerunPrincipal().getRoles().remove(Role.PERUNADMIN); } if(!oauthScopes.contains(PerunClient.PERUN_API_SCOPE)) { log.warn("removing all roles from session {}",sess); sess.getPerunPrincipal().getRoles().clear(); } } log.trace("Refreshed roles: {}", sess.getPerunPrincipal().getRoles()); sess.getPerunPrincipal().setAuthzInitialized(true); }
Source:
<code>public boolean advanceNextPosition() { if (!searchHits.hasNext()) { return false; } SearchHit hit = searchHits.next(); fields = new ArrayList(Collections.nCopies(columnHandles.size(), null)); setFieldIfExists("_id", hit.getId()); setFieldIfExists("_index", hit.getIndex()); <START> extractFromSource(hit); <END> totalBytes += fields.size(); return true; }</code><technical_language>fields = Collections.nCopies(columnHandles.size(), null);</technical_language>

Target:
public boolean advanceNextPosition() { if (!searchHits.hasNext()) { return false; } SearchHit hit = searchHits.next(); fields = new ArrayList<>(Collections.nCopies(columnHandles.size(), null)); setFieldIfExists("_id", hit.getId()); setFieldIfExists("_index", hit.getIndex()); extractFromSource(hit); if (hit.getSourceRef() != null) { totalBytes += hit.getSourceRef().length(); } return true; }
Source:
<code>private Object stateToObject(State state) { Object value; if (state instanceof DecimalType) { value = convertBigDecimalToNum(((DecimalType) state).toBigDecimal()); <START> } else if (state instanceof PercentType) { <END> value = convertBigDecimalToNum(((PercentType) state).toBigDecimal()); } else if (state instanceof OnOffType) { value = (OnOffType) state == OnOffType.ON ? 1 : 0; } else if (state instanceof OpenClosedType) { value = (OpenClosedType) state == OpenClosedType.OPEN ? 1 : 0; } else if (state instanceof HSBType) { value = ((HSBType) state).getConstituents(); } else if (state instanceof DateTimeType) { value = ((DateTimeType) state).getCalendar().getTime().getTime(); } else if (state instanceof PointType) { value = ((PointType) state).getConstituents(); } else { value = state.toString(); } return value; }</code><technical_language>Remove handling of PercentType is a subtype of DecimalType converted in way</technical_language>

Target:
private Object stateToObject(State state) { Object value; if (state instanceof DecimalType) { value = convertBigDecimalToNum(((DecimalType) state).toBigDecimal()); } else if (state instanceof OnOffType) { value = (OnOffType) state == OnOffType.ON ? 1 : 0; } else if (state instanceof OpenClosedType) { value = (OpenClosedType) state == OpenClosedType.OPEN ? 1 : 0; } else if (state instanceof HSBType) { value = ((HSBType) state).toString(); } else if (state instanceof DateTimeType) { value = ((DateTimeType) state).toString(); } else { value = state.toString(); } return value; }
Source:
<code>public void resolveHostname(String hostname, Handler<AsyncResult<InetAddress>> resultHandler) { ContextInternal callback = (ContextInternal) vertx.getOrCreateContext(); io.netty.resolver.AddressResolver<InetSocketAddress> resolver = resolverGroup.getResolver(callback.nettyEventLoop()); io.netty.util.concurrent.Future<InetSocketAddress> fut = resolver.resolve(InetSocketAddress.createUnresolved(hostname, 0)); fut.addListener(a -> { callback.runOnContext(v -> { if (a.isSuccess()) { InetSocketAddress address = fut.getNow(); resultHandler.handle(Future.succeededFuture(address.getAddress())); } else { <START> if (Utils.isWindows() && hostname.equals("localhost")) { <END> resultHandler.handle(Future.succeededFuture(LOOPBACK_ADDRESS)); } else { resultHandler.handle(Future.failedFuture(a.cause())); } } }); }); }</code><technical_language>hostname resolution is case-insensitive LOCALHOST is a valid hostname for 127.0.0.1 (had issue in netty hosts file resolver) hostname.toLowerCase(Locale.ENGLISH).equals("localhost");</technical_language>

Target:
public void resolveHostname(String hostname, Handler<AsyncResult<InetAddress>> resultHandler) { ContextInternal callback = (ContextInternal) vertx.getOrCreateContext(); io.netty.resolver.AddressResolver<InetSocketAddress> resolver = resolverGroup.getResolver(callback.nettyEventLoop()); io.netty.util.concurrent.Future<InetSocketAddress> fut = resolver.resolve(InetSocketAddress.createUnresolved(hostname, 0)); fut.addListener(a -> { callback.runOnContext(v -> { if (a.isSuccess()) { InetSocketAddress address = fut.getNow(); resultHandler.handle(Future.succeededFuture(address.getAddress())); } else { resultHandler.handle(Future.failedFuture(a.cause())); } }); }); }
Source:
<code>public CompletableFuture<Acknowledge> cancel(Time timeout) { synchronized (lock) { if (isInitialized()) { return getJobMasterGateway().thenCompose(jobMasterGateway -> jobMasterGateway.cancel(timeout)); } else { log.info("Cancellation during initialization requested for job {}. Job will be cancelled once JobManager has been initialized.", jobId); jobManagerRunnerFuture .thenCompose(JobManagerRunner::getJobMasterGateway) .thenCompose(jobMasterGateway -> jobMasterGateway.cancel(RpcUtils.INF_TIMEOUT)) .whenComplete((ignored, cancelThrowable) -> { if (cancelThrowable != null) { log.warn("Cancellation of job failed", jobId, cancelThrowable); } }); jobStatus = DispatcherJobStatus.CANCELLING; jobResultFuture.whenComplete(((archivedExecutionGraph, throwable) -> { if (archivedExecutionGraph != null) { <START> jobStatus = DispatcherJobStatus.JOB_MANAGER_RUNNER_INITIALIZED; <END> } })); return jobResultFuture.thenApply(ignored -> Acknowledge.get()); } } }</code><technical_language>lock is missing</technical_language>

Target:
public CompletableFuture<Acknowledge> cancel(Time timeout) { synchronized (lock) { if (isInitialized()) { return getJobMasterGateway().thenCompose(jobMasterGateway -> jobMasterGateway.cancel(timeout)); } else { log.info("Cancellation during initialization requested for job {}. Job will be cancelled once JobManager has been initialized.", jobId); CompletableFuture<Acknowledge> cancelFuture = jobManagerRunnerFuture .thenCompose(JobManagerRunner::getJobMasterGateway) .thenCompose(jobMasterGateway -> jobMasterGateway.cancel(timeout)); cancelFuture.whenComplete((ignored, cancelThrowable) -> { if (cancelThrowable != null) { log.warn("Cancellation of job failed", jobId, cancelThrowable); } }); jobStatus = DispatcherJobStatus.CANCELLING; return cancelFuture; } } }
Source:
<code>private void preloadContextCache(List<Class<?>> classes) throws JAXBException { <START> for (Class<?> clazz : classes) { <END> getContext(clazz); } }</code><technical_language>isNullOrEmpty type check provided list</technical_language>

Target:
private void preloadContextCache(List<Class<?>> classes) throws JAXBException { if (classes != null && !classes.isEmpty()) { for (Class<?> clazz : classes) { getContext(clazz); } } }
Source:
<code>public boolean canConvertToAuto(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final Gson gson = new Gson(); <START> String urlBuilds = QUAY_URL + "repository/" + repo + "/build/?limit=2147483647"; <END> Optional<String> asStringBuilds = ResourceUtilities.asString(urlBuilds, quayToken.getContent(), client); if (asStringBuilds.isPresent()) { String json = asStringBuilds.get(); Map<String, ArrayList> map = new HashMap<>(); map = (Map<String, ArrayList>) gson.fromJson(json, map.getClass()); ArrayList builds = map.get("builds"); for (Object build : builds) { Map<String, Map<String, String>> triggerMetadataMap = (Map<String, Map<String, String>>)build; Map<String, String> triggerMetadata = triggerMetadataMap.get("trigger_metadata"); if (triggerMetadata != null) { String gitUrl = triggerMetadata.get("git_url"); if (Objects.equals(gitUrl, tool.getGitUrl())) { return true; } } } } return false; }</code><technical_language>a maxint const somehwere</technical_language>

Target:
public boolean canConvertToAuto(Tool tool) { final String repo = tool.getNamespace() + '/' + tool.getName(); final Gson gson = new Gson(); String urlBuilds = QUAY_URL + "repository/" + repo + "/build/?limit=" + Integer.MAX_VALUE; Optional<String> asStringBuilds = ResourceUtilities.asString(urlBuilds, quayToken.getContent(), client); if (asStringBuilds.isPresent()) { String json = asStringBuilds.get(); Map<String, ArrayList> map = new HashMap<>(); map = (Map<String, ArrayList>) gson.fromJson(json, map.getClass()); ArrayList builds = map.get("builds"); for (Object build : builds) { Map<String, Map<String, String>> triggerMetadataMap = (Map<String, Map<String, String>>)build; Map<String, String> triggerMetadata = triggerMetadataMap.get("trigger_metadata"); if (triggerMetadata != null) { String gitUrl = triggerMetadata.get("git_url"); if (Objects.equals(gitUrl, tool.getGitUrl())) { return true; } } } } return false; }
Source:
<code>public List<Group> listGroups(Condition condition, int limit, int offset, String sortBy, String sortOrder) throws UserStoreException { validateCondition(condition); String domain = getDomainFromCondition(condition); handlePreListGroup(condition, domain); List<Group> filteredGroups = new ArrayList<>(); UserStoreManager secManager = getSecondaryUserStoreManager(domain); if (secManager != null) { if (secManager instanceof AbstractUserStoreManager) { if (isUniqueUserIdEnabled(secManager)) { UniqueIDPaginatedSearchResult <Group> groups = ((AbstractUserStoreManager) secManager) .doListGroups(condition, domain, offset, limit, sortBy, sortOrder); filteredGroups = groups.getEntities(); } else { <START> throw new UserStoreException(" listGroups is not supported."); <END> } } } handlePostListGroups(condition, domain, false); return filteredGroups; }</code><technical_language>space prefix here</technical_language>

Target:
public List<Group> listGroups(Condition condition, int limit, int offset, String sortBy, String sortOrder) throws UserStoreException { validateCondition(condition); String domain = getDomainFromCondition(condition); handlePreListGroup(condition, domain); List<Group> filteredGroups = new ArrayList<>(); UserStoreManager secManager = getSecondaryUserStoreManager(domain); if (secManager != null) { if (secManager instanceof AbstractUserStoreManager) { if (isUniqueUserIdEnabled(secManager)) { UniqueIDPaginatedSearchResult <Group> groups = ((AbstractUserStoreManager) secManager) .doListGroups(condition, domain, offset, limit, sortBy, sortOrder); filteredGroups = groups.getEntities(); } else { throw new UserStoreException("listGroups is not supported in this: " + this.getClass()); } } } handlePostListGroups(condition, domain, false); return filteredGroups; }
Source:
<code>public void testPrometheusMetrics() throws Exception { SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID, SOLVER_PROMETHEUS_ID, SOLVER_1_CONFIG); assertNotNull(solverInstance); assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); Object planningProblem = loadPlanningProblem(5, 15); solverClient.solvePlanningProblem(CONTAINER_1_ID, SOLVER_PROMETHEUS_ID, planningProblem); solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_PROMETHEUS_ID); for (int i = 0; i < 5 && solverInstance.getStatus() == SolverInstance.SolverStatus.SOLVING; i++) { <START> Thread.sleep(3000); <END> solverInstance = solverClient.getSolver(CONTAINER_1_ID, SOLVER_PROMETHEUS_ID); assertNotNull(solverInstance); } assertEquals(SolverInstance.SolverStatus.NOT_SOLVING, solverInstance.getStatus()); solverClient.disposeSolver(CONTAINER_1_ID, SOLVER_PROMETHEUS_ID); checkPrometheusMetrics(); }</code><technical_language>) I know, I test. If want improve original test too, great. If find out tests differ (not)calling checkPrometheusMetrics(), worth reduce duplication introducing a new private method logic of test. If find complicated, feel free focus tests related Prometheus - I file a Jira test refactoring. Thanks</technical_language>

Target:
public void testPrometheusMetrics() throws Exception { testExecuteSolverHelper(SOLVER_PROMETHEUS_ID); checkPrometheusMetrics(); }
Source:
<code>protected void fillDisplay(final Collection collection) { DecimalFormat format = new DecimalFormat("0.##"); java.util.List<Collectible> list = collection.sort(new RarityComparator()); cContentTable.clear(); <START> System.out.println(list); <END> for (final Collectible collectible : list) { cContentTable.add(new Image(CollectibleDrawer.drawCollectible(collectible))).space(30); } cContentTable.row(); for (final Collectible collectible : list) { cContentTable.add(cGameSkin.generateDefaultLabel(format.format(collectible.getRarity()))); } }</code><technical_language>Is Syso needed? try log function remove it</technical_language>

Target:
protected void fillDisplay(final Collection collection) { DecimalFormat format = new DecimalFormat("0.##"); java.util.List<Collectible> list = collection.sort(new RarityComparator()); cContentTable.clear(); for (final Collectible collectible : list) { cContentTable.add(new Image(CollectibleDrawer.drawCollectible(collectible))).space(30); } cContentTable.row(); for (final Collectible collectible : list) { cContentTable.add(cGameSkin.generateDefaultLabel(format.format(collectible.getRarity()))); } }
Source:
<code>private Pair<Long, Boolean> checkArrivals(ObaArrivalInfoResponse response, Cursor c) { final String tripId = c.getString(COL_TRIP_ID); final ObaArrivalInfo[] arrivals = response.getArrivalInfo(); final int length = arrivals.length; for (int i = 0; i < length; ++i) { ObaArrivalInfo info = arrivals[i]; if (tripId.equals(info.getTripId())) { long depart = info.getPredictedArrivalTime(); boolean isArriving = true; if (depart == 0) { depart = info.getScheduledArrivalTime(); <START> isArriving = false; <END> } return new Pair<>(depart, isArriving); } } return null; }</code><technical_language>arrival/departure labeling consistent normal arrival times lists, construct instance of ArrivalInfo ObaArrivalInfo, call arrivalInfo.isArrival() determine if arrival departure. This is a more complicated I originally thinking, though, previously arrival time for reminder - technically I reminding users departure times for departures, arrival time for arrivals. I arrivalInfo.getEta() for this (internally calculate ETA arrival departure appropriately), resolution for getEta() is currently in seconds, this method expects return milliseconds. add another method returns ETA in milliseconds</technical_language>

Target:
private Long checkArrivals(ObaArrivalInfoResponse response, Cursor c) { final String tripId = c.getString(COL_TRIP_ID); final ObaArrivalInfo[] arrivals = response.getArrivalInfo(); final int length = arrivals.length; for (int i = 0; i < length; ++i) { ObaArrivalInfo info = arrivals[i]; if (tripId.equals(info.getTripId())) { long depart = info.getPredictedArrivalTime(); if (depart == 0) { depart = info.getScheduledArrivalTime(); } return depart; } } return null; }
Source:
<code><START> public Observable<DataPoint<RatioMap>> findAvailabilityRatioMap( <END> String tenantId, Map<String, String> tagFilters, long start, long end, int limit, Order order) { checkArgument(isValidTimeRange(start, end), "Invalid time range"); Observable<DataPoint<RatioMap>> result = findMetricsWithFilters(tenantId, AVAILABILITY, tagFilters) .map(metric -> findDataPoints(metric.getMetricId(), start, end, limit, order)) .compose(o -> buildRatioMapSeries(o, order, AvailabilityType::getText)); if (limit > 0) { result = result.limit(limit); } return result; }</code><technical_language>This accept limiter functions findMetrics</technical_language>

Target:
public Observable<DataPoint<RatioMap>> findAvailabilityRatioMap( String tenantId, Map<String, String> tagFilters, long start, long end, int limit, Order order) { checkArgument(isValidTimeRange(start, end), "Invalid time range"); Observable<DataPoint<RatioMap>> result = findMetricsWithFilters(tenantId, AVAILABILITY, tagFilters) .map(metric -> findDataPoints(metric.getMetricId(), start, end, limit, order)) .compose(o -> buildRatioMapSeries(o, order, AvailabilityType::getText)); if (limit > 0) { result = result.take(limit); } return result; }
Source:
<code>void next(ServiceBusReceivedMessageContext message) { try { <START> if (timeoutBeforeNextMessageOperation != null && !timeoutBeforeNextMessageOperation.isDisposed()) { <END> timeoutBeforeNextMessageOperation.dispose(); } emitter.next(message); remaining.decrementAndGet(); timeoutBeforeNextMessageOperation = getShortTimeoutBetweenMessages(); } catch (Exception e) { logger.warning("Exception occurred while publishing downstream.", e); error(e); } }</code><technical_language>This reactive create a new Mono operation everytime a message in. a combination of Flux.swithOnNext(publisher).takeUntil(notCancelled) a new item is emitted publisher if is a next message? for item emitted, delay interval. if item is emitted, cancel emitter</technical_language>

Target:
void next(ServiceBusReceivedMessageContext message) { try { emitter.next(message); messageReceivedSink.next(message); remaining.decrementAndGet(); } catch (Exception e) { logger.warning("Exception occurred while publishing downstream.", e); error(e); } }
Source:
<code>public String getDescription() { <START> return null; <END> }</code><technical_language>This needs implemented</technical_language>

Target:
public String getDescription() { return ""; }
Source:
<code><START> public void simplifyScopedStoragePathTest() { <END> assertThat(FileUtils.simplifyScopedStoragePath(null), is(nullValue())); assertThat(FileUtils.simplifyScopedStoragePath(""), is("")); assertThat(FileUtils.simplifyScopedStoragePath("blahblahblah"), is("blahblahblah")); assertThat(FileUtils.simplifyScopedStoragePath("/storage/emulated/0/Android/data/org.odk.collect.android/files/layers"), is("/sdcard/Android/data/org.odk.collect.android/files/layers")); }</code><technical_language>I is equivelant == alias of is(equalTo()). in future</technical_language>

Target:
public void simplifyScopedStoragePathTest() { assertThat(FileUtils.simplifyScopedStoragePath(null), is(nullValue())); assertThat(FileUtils.simplifyScopedStoragePath(""), is("")); assertThat(FileUtils.simplifyScopedStoragePath("blahblahblah"), is("blahblahblah")); assertThat(FileUtils.simplifyScopedStoragePath("/storage/emulated/0/Android/data/org.odk.collect.android/files/layers"), is("/sdcard/Android/data/org.odk.collect.android/files/layers")); assertThat(FileUtils.simplifyScopedStoragePath("/storage/emulated/0/Android/data/org.odk.collect.android/files/layers/countries/countries-raster.mbtiles"), is("/sdcard/Android/data/org.odk.collect.android/files/layers/countries/countries-raster.mbtiles")); }
Source:
<code>public String getName() { if(getEcoreOperation() == null) { <START> return safeName("null"); <END> } return safeName(getEcoreOperation().getName()); }</code><technical_language>return "", do need pass safeName()</technical_language>

Target:
public String getName() { if(getEcoreOperation() == null) { return ""; } return safeName(getEcoreOperation().getName()); }
Source:
<code><START> public String getFactorySnippet(String factoryId, <END> String snippetType, UriInfo uriInfo) throws NotFoundException, ServerException { requireNonNull(factoryId); final URI baseUri = uriInfo.getBaseUri(); final String baseUrl = UriBuilder.fromUri(baseUri) .replacePath("") .build() .toString(); switch (snippetType) { case URL_SNIPPET_TYPE: return UriBuilder.fromUri(baseUri) .replacePath("factory") .queryParam("id", factoryId) .build() .toString(); case HTML_SNIPPET_TYPE: return SnippetGenerator.generateHtmlSnippet(baseUrl, factoryId); case IFRAME_SNIPPET_TYPE: return SnippetGenerator.generateiFrameSnippet(baseUrl, factoryId); case MARKDOWN_SNIPPET_TYPE: final Set<FactoryImage> images = getFactoryImages(factoryId); final String imageId = (images.size() > 0) ? images.iterator().next().getName() : null; try { return SnippetGenerator.generateMarkdownSnippet(baseUrl, getById(factoryId), imageId); } catch (IllegalArgumentException e) { throw new ServerException(e.getLocalizedMessage()); } default: return null; } }</code><technical_language>Mark method @Nullable factory follow _everything is not-null default_ pattern</technical_language>

Target:
public String getFactorySnippet(String factoryId, String snippetType, UriInfo uriInfo) throws NotFoundException, ServerException { requireNonNull(factoryId); final URI baseUri = uriInfo.getBaseUri(); final String baseUrl = UriBuilder.fromUri(baseUri) .replacePath("") .build() .toString(); switch (firstNonNull(snippetType, URL_SNIPPET_TYPE)) { case URL_SNIPPET_TYPE: return UriBuilder.fromUri(baseUri) .replacePath("factory") .queryParam("id", factoryId) .build() .toString(); case HTML_SNIPPET_TYPE: return SnippetGenerator.generateHtmlSnippet(baseUrl, factoryId); case IFRAME_SNIPPET_TYPE: return SnippetGenerator.generateiFrameSnippet(baseUrl, factoryId); case MARKDOWN_SNIPPET_TYPE: final Set<FactoryImage> images = getFactoryImages(factoryId); final String imageId = (images.size() > 0) ? images.iterator().next().getName() : null; try { return SnippetGenerator.generateMarkdownSnippet(baseUrl, getById(factoryId), imageId); } catch (IllegalArgumentException e) { throw new ServerException(e.getLocalizedMessage()); } default: return null; } }
Source:
<code>public int compare(Map<String, String> map1, Map<String, String> map2) { <START> return new LexoNumericComparator().compare(map1.get(key), map2.get(key)); <END> }</code><technical_language>Minor thing, I suggest have: private final LexoNumericComparator lexoNumeric = new LexoNumericComparator(); in compare() method: return lexoNumeric.compare(map1.get(key), map2.get(key)); (I tend prefer avoiding instance creation, in this case, big of a deal, though.)</technical_language>

Target:
public int compare(Map<String, String> map1, Map<String, String> map2) { return lexoNumericComparator.compare(map1.get(key), map2.get(key)); }
Source:
<code>public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException { for (Collector.MetricFamilySamples metricFamilySamples: Collections.list(mfs)) { writer.write("# HELP " + metricFamilySamples.name + " " + escapeHelp(metricFamilySamples.help) + "\n"); writer.write("# TYPE " + metricFamilySamples.name + " " + typeString(metricFamilySamples.type) + "\n"); for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) { writer.write(sample.name); if (sample.labels != null && !sample.labels.isEmpty()) { writer.write("{"); <START> for (Map.Entry<String, String> label : sample.labels.entrySet()) { <END> writer.write(String.format("%s=\"%s\",", label.getKey(), escapeLabelValue(label.getValue()))); } writer.write("}"); } writer.write(" " + Collector.doubleToGoString(sample.value) + "\n"); } } }</code><technical_language>This sorted for efficiency</technical_language>

Target:
public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException { for (Collector.MetricFamilySamples metricFamilySamples: Collections.list(mfs)) { writer.write("# HELP " + metricFamilySamples.name + " " + escapeHelp(metricFamilySamples.help) + "\n"); writer.write("# TYPE " + metricFamilySamples.name + " " + typeString(metricFamilySamples.type) + "\n"); for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) { writer.write(sample.toString() + "\n"); } } }
Source:
<code>public void stop() { synchronized (lock) { if (!started) { return; } <START> rules.set(new HashMap<String, List<Rule>>()); <END> started = false; exec.shutdownNow(); exec = null; } }</code><technical_language>Please Collections.emptyMap()</technical_language>

Target:
public void stop() { synchronized (lock) { if (!started) { return; } rules.set(Collections.emptyMap()); started = false; exec.shutdownNow(); exec = null; } }
Source:
<code>public String toString() { <START> return String.format("Checkpoint: %s, Topic: %s, Partition: %d, Event Index: %d, Source Partition: %d", _checkpoint, <END> _topic, _partition, _eventIndex, _sourcePartition); }</code><technical_language>Partition -> Destination Partition</technical_language>

Target:
public String toString() { return String.format("Checkpoint: %s, Topic: %s, Destination Partition: %d, Event Index: %d, Source Partition: %d", _checkpoint, _topic, _partition, _eventIndex, _sourcePartition); }
Source:
<code>public void loadValidators(Props props, Logger log) { validators = new LinkedHashMap<String, ProjectValidator>(); DirectoryFlowLoader flowLoader = new DirectoryFlowLoader(log); validators.put(flowLoader.getValidatorInfo(), flowLoader); if (!props.containsKey(XML_FILE_PARAM)) { <START> return; <END> } String xmlPath = props.get(XML_FILE_PARAM); File file = new File(xmlPath); if (!file.exists()) { return; } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ValidatorManagerException( "Exception while parsing validator xml. Document builder not created.", e); } Document doc = null; try { doc = builder.parse(file); } catch (SAXException e) { throw new ValidatorManagerException("Exception while parsing " + xmlPath + ". Invalid XML.", e); } catch (IOException e) { throw new ValidatorManagerException("Exception while parsing " + xmlPath + ". Error reading file.", e); } NodeList tagList = doc.getChildNodes(); Node azkabanValidators = tagList.item(0); NodeList azkabanValidatorsList = azkabanValidators.getChildNodes(); for (int i = 0; i < azkabanValidatorsList.getLength(); ++i) { Node node = azkabanValidatorsList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals(VALIDATOR_TAG)) { parseValidatorTag(node, props, log); } } } }</code><technical_language>Please add logging easier debug XML_FILE_PARAM key exist</technical_language>

Target:
public void loadValidators(Props props, Logger log) { validators = new LinkedHashMap<String, ProjectValidator>(); DirectoryFlowLoader flowLoader = new DirectoryFlowLoader(log); validators.put(flowLoader.getValidatorName(), flowLoader); if (!props.containsKey(XML_FILE_PARAM)) { logger.warn("Azkaban properties file does not contain the key " + XML_FILE_PARAM); return; } String xmlPath = props.get(XML_FILE_PARAM); File file = new File(xmlPath); if (!file.exists()) { logger.error("Azkaban validator configuration file " + xmlPath + " does not exist."); return; } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new ValidatorManagerException( "Exception while parsing validator xml. Document builder not created.", e); } Document doc = null; try { doc = builder.parse(file); } catch (SAXException e) { throw new ValidatorManagerException("Exception while parsing " + xmlPath + ". Invalid XML.", e); } catch (IOException e) { throw new ValidatorManagerException("Exception while parsing " + xmlPath + ". Error reading file.", e); } NodeList tagList = doc.getChildNodes(); Node azkabanValidators = tagList.item(0); NodeList azkabanValidatorsList = azkabanValidators.getChildNodes(); for (int i = 0; i < azkabanValidatorsList.getLength(); ++i) { Node node = azkabanValidatorsList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals(VALIDATOR_TAG)) { parseValidatorTag(node, props, log); } } } }
Source:
<code>protected List<String> getProcessDefinitionFiles() { List<String> processes = new ArrayList<String>(); processes.add("cases/EmptyCase.bpmn2"); processes.add("cases/UserTaskCase.bpmn2"); <START> processes.add("processes/UserTaskProcess.bpmn2"); <END> return processes; }</code><technical_language>This process is referenced in this test class</technical_language>

Target:
protected List<String> getProcessDefinitionFiles() { List<String> processes = new ArrayList<String>(); processes.add("cases/EmptyCase.bpmn2"); processes.add("cases/UserTaskCase.bpmn2"); return processes; }
Source:
<code>public MultipartAttachmentWriter() { this.basicBoundary = this.makeBoundary(); <START> this.boundary = ("--"+basicBoundary).getBytes(); <END> this.trailingBoundary = ("--"+basicBoundary+"--").getBytes(); components = new ArrayList<InputStream>(); contentLength += boundary.length; contentLength += 6; contentLength += contentType.length; components.add(new ByteArrayInputStream(boundary)); components.add(new ByteArrayInputStream(crlf)); components.add(new ByteArrayInputStream(contentType)); components.add(new ByteArrayInputStream(crlf)); components.add(new ByteArrayInputStream(crlf)); }</code><technical_language>boundary partBoundary basicBoundry expressive</technical_language>

Target:
public MultipartAttachmentWriter() { this.boundary = this.makeBoundary(); this.partBoundary = ("--"+boundary).getBytes(); this.trailingBoundary = ("--"+boundary+"--").getBytes(); components = new ArrayList<InputStream>(); contentLength += partBoundary.length; contentLength += 6; contentLength += contentType.length; components.add(new ByteArrayInputStream(partBoundary)); components.add(new ByteArrayInputStream(crlf)); components.add(new ByteArrayInputStream(contentType)); components.add(new ByteArrayInputStream(crlf)); components.add(new ByteArrayInputStream(crlf)); }
Source:
<code>public static ServerScope parse(String scope) throws IllegalArgumentException { if (scope.startsWith("unlimited")) { return new Unlimited(); } String[] chunks = scope.trim().split(":", 2); <START> if (chunks.length != 2) throw new IllegalArgumentException("Invalid scope: " + scope); <END> if ("node".equals(chunks[0])) { return new Node(chunks[1]); } else if ("run".equals(chunks[0])) { return new Build(chunks[1]); } else if ("time".equals(chunks[0])) { return new Time(chunks[1]); } else { throw new IllegalArgumentException("Invalid scope kind: " + chunks[0]); } }</code><technical_language>This a singleton</technical_language>

Target:
public static ServerScope parse(String scope) throws IllegalArgumentException { if (scope.startsWith("unlimited")) { return Unlimited.getInstance(); } String[] chunks = scope.trim().split(":", 2); if (chunks.length != 2) throw new IllegalArgumentException("Invalid scope: " + scope); if ("node".equals(chunks[0])) { return new Node(chunks[1]); } else if ("run".equals(chunks[0])) { return new Build(chunks[1]); } else if ("time".equals(chunks[0])) { return new Time(chunks[1]); } else { throw new IllegalArgumentException("Invalid scope kind: " + chunks[0]); } }
Source:
<code>public void testDoesNotFireOnNestedNonCountAggregate() { tester().assertThat(new PruneCountAggregationOverScalar()) .on(p -> { Symbol totalPrice = p.symbol("total_price", DOUBLE); AggregationNode inner = p.aggregation((a) -> a .addAggregation(totalPrice, new FunctionCall(QualifiedName.of("sum"), ImmutableList.of(new SymbolReference("totalprice"))), ImmutableList.of(DOUBLE)) .globalGrouping() .source( p.project( Assignments.of(totalPrice, totalPrice.toSymbolReference()), p.tableScan( new TableHandle( new ConnectorId("local"), new TpchTableHandle("orders", TINY_SCALE_FACTOR), TestingTransactionHandle.create(), <START> Optional.of(TestingHandle.INSTANCE)), <END> ImmutableList.of(totalPrice), ImmutableMap.of(totalPrice, new TpchColumnHandle(totalPrice.getName(), DOUBLE)))))); return p.aggregation((a) -> a .addAggregation( p.symbol("sum_outer", DOUBLE), new FunctionCall(QualifiedName.of("sum"), ImmutableList.of(new SymbolReference("sum_inner"))), ImmutableList.of(DOUBLE)) .globalGrouping() .source(inner)); }).doesNotFire(); }</code><technical_language>Optional.empty() ? :)</technical_language>

Target:
public void testDoesNotFireOnNestedNonCountAggregate() { tester().assertThat(new PruneCountAggregationOverScalar()) .on(p -> { Symbol totalPrice = p.symbol("total_price", DOUBLE); AggregationNode inner = p.aggregation((a) -> a .addAggregation(totalPrice, new FunctionCall(QualifiedName.of("sum"), ImmutableList.of(new SymbolReference("totalprice"))), ImmutableList.of(DOUBLE)) .globalGrouping() .source( p.project( Assignments.of(totalPrice, totalPrice.toSymbolReference()), p.tableScan( new TableHandle( new ConnectorId("local"), new TpchTableHandle("orders", TINY_SCALE_FACTOR), TestingTransactionHandle.create(), Optional.empty()), ImmutableList.of(totalPrice), ImmutableMap.of(totalPrice, new TpchColumnHandle(totalPrice.getName(), DOUBLE)))))); return p.aggregation((a) -> a .addAggregation( p.symbol("sum_outer", DOUBLE), new FunctionCall(QualifiedName.of("sum"), ImmutableList.of(new SymbolReference("sum_inner"))), ImmutableList.of(DOUBLE)) .globalGrouping() .source(inner)); }).doesNotFire(); }
Source:
<code>private void updateTableLayoutForLabels(ChangeList list) { labelNames = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) { for (String name : list.get(i).labels()) { if (!labelNames.contains(name)) { labelNames.add(name); } } } if (BASE_COLUMNS + labelNames.size() < columns) { int n = columns - (BASE_COLUMNS + labelNames.size()); for (int row = 0; row < table.getRowCount(); row++) { table.removeCells(row, columns, n); } } columns = BASE_COLUMNS + labelNames.size(); FlexCellFormatter fmt = table.getFlexCellFormatter(); <START> for (int i = 0; i < labelNames.size(); i++) { <END> String name = labelNames.get(i); int col = BASE_COLUMNS + i; StringBuilder abbrev = new StringBuilder(); for (String t : name.split("-")) { abbrev.append(t.substring(0, 1).toUpperCase()); } table.setText(0, col, abbrev.toString()); table.getCellFormatter().getElement(0, col).setTitle(name); fmt.addStyleName(0, col, Gerrit.RESOURCES.css().dataHeader()); } }</code><technical_language>sort label names (by name) columns in order? I is confusing if order change</technical_language>

Target:
private void updateTableLayoutForLabels(ChangeList list) { labelNames = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) { for (String name : list.get(i).labels()) { if (!labelNames.contains(name)) { labelNames.add(name); } } } Collections.sort(labelNames); if (BASE_COLUMNS + labelNames.size() < columns) { int n = columns - (BASE_COLUMNS + labelNames.size()); for (int row = 0; row < table.getRowCount(); row++) { table.removeCells(row, columns, n); } } columns = BASE_COLUMNS + labelNames.size(); FlexCellFormatter fmt = table.getFlexCellFormatter(); for (int i = 0; i < labelNames.size(); i++) { String name = labelNames.get(i); int col = BASE_COLUMNS + i; StringBuilder abbrev = new StringBuilder(); for (String t : name.split("-")) { abbrev.append(t.substring(0, 1).toUpperCase()); } table.setText(0, col, abbrev.toString()); table.getCellFormatter().getElement(0, col).setTitle(name); fmt.addStyleName(0, col, Gerrit.RESOURCES.css().dataHeader()); } }
Source:
<code><START> public GlusterStatus isGlusterRunning(Guid vdsId) { <END> VDSReturnValue returnValue = resourceManager.runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vdsId, Arrays.asList("glusterd"), "status")); if (!returnValue.getSucceeded()) { log.error("Failed to check Gluster running status of host : '{}' ", vdsId); return GlusterStatus.UNKNOWN; } ArrayList<GlusterServerService> returnList = (ArrayList<GlusterServerService>) returnValue.getReturnValue(); if (returnList == null || returnList.isEmpty()) { log.error("Failed to check Gluster running status of host : '{}' returned empty object", vdsId); return GlusterStatus.UNKNOWN; } GlusterServerService gss = returnList.get(0); if (gss != null) { return gss.getStatus().getStatusMsg().equalsIgnoreCase("Up") ? GlusterStatus.UP : GlusterStatus.DOWN; } log.info("Failed to check Gluster running status of host : '{}' ", vdsId); return GlusterStatus.UNKNOWN; }</code><technical_language>Do need log in method, if log details error? I logging done upper level method deal gluster service status</technical_language>

Target:
public GlusterStatus isGlusterRunning(Guid vdsId) { VDSReturnValue result = resourceManager.runVdsCommand(VDSCommandType.ManageGlusterService, new GlusterServiceVDSParameters(vdsId, Arrays.asList("glusterd"), "status")); if (result.getSucceeded()) { @SuppressWarnings("unchecked") ArrayList<GlusterServerService> serviceList = (ArrayList<GlusterServerService>) result.getReturnValue(); if (serviceList != null && !serviceList.isEmpty()) { return serviceList.get(0).getStatus().getStatusMsg().equalsIgnoreCase("up") ? GlusterStatus.UP : GlusterStatus.DOWN; } } return GlusterStatus.UNKNOWN; }
Source:
<code>SshKeyCacheEntry(final AccountSshKey.Id i, final PublicKey k) { id = i; publicKey = k; <START> lastUsed = null; <END> }</code><technical_language>Hmm, caller invoking a full AccountSshKey object in hand. pass time database column initialize this field, assume is null</technical_language>

Target:
SshKeyCacheEntry(final AccountSshKey.Id i, final PublicKey k) { id = i; publicKey = k; }
Source:
<code><START> public void merge(GridHubConfiguration other) { <END> super.merge(other); if (other.jettyMaxThreads != null) jettyMaxThreads = other.jettyMaxThreads; capabilityMatcher = other.capabilityMatcher; if (other.newSessionWaitTimeout != null) newSessionWaitTimeout = other.newSessionWaitTimeout; if (other.prioritizer != null) prioritizer = other.prioritizer; if (other.throwOnCapabilityNotPresent != throwOnCapabilityNotPresent) throwOnCapabilityNotPresent = other.throwOnCapabilityNotPresent; }</code><technical_language>@Override annotation here. IDEs busy freaking out you, some java versions compile code</technical_language>

Target:
public void merge(GridHubConfiguration other) { super.merge(other); if (other.jettyMaxThreads != null) { jettyMaxThreads = other.jettyMaxThreads; } capabilityMatcher = other.capabilityMatcher; if (other.newSessionWaitTimeout != null) { newSessionWaitTimeout = other.newSessionWaitTimeout; } if (other.prioritizer != null) { prioritizer = other.prioritizer; } if (other.throwOnCapabilityNotPresent != throwOnCapabilityNotPresent) { throwOnCapabilityNotPresent = other.throwOnCapabilityNotPresent; } }
Source:
<code>protected void validateInitialization() { <START> assertNotNull(((YarnResourceManagerDriver) getDriver()).getResourceManagerClient()); assertNotNull(((YarnResourceManagerDriver) getDriver()).getNodeManagerClient()); <END> }</code><technical_language>I suggest references of client in Context, verify started. need this type conversion exposing getters @VisibleForTesting annotations</technical_language>

Target:
protected void validateInitialization() throws Exception { assertNotNull(testingYarnAMRMClientAsync); assertNotNull(testingYarnNMClientAsync); verifyFutureCompleted(nodeManagerClientInitFuture); verifyFutureCompleted(nodeManagerClientStartFuture); verifyFutureCompleted(resourceManagerClientInitFuture); verifyFutureCompleted(resourceManagerClientStartFuture); }
Source:
<code><START> public ImapIdleChannelAdapterSpec adviceChain(Advice... adviceChain) { <END> this.target.setAdviceChain(Arrays.asList(adviceChain)); return this; }</code><technical_language>missed transactional() option for convenience</technical_language>

Target:
public ImapIdleChannelAdapterSpec adviceChain(Advice... adviceChain) { this.adviceChain.addAll(Arrays.asList(adviceChain)); return this; }
Source:
<code>public static String getResourceName(String uniqueId) { if (StringUtils.isEmpty(uniqueId)) { return null; } <START> String[] comps = uniqueId.split("@"); <END> if (comps.length > 0) { return comps[comps.length - 1]; } else { return null; } }</code><technical_language>"@" replaced constant UNIQUE_ID_PROJECT_NAME_DELIMITER</technical_language>

Target:
public static String getResourceName(String uniqueId) { if (StringUtils.isEmpty(uniqueId)) { return null; } String[] comps = uniqueId.split(String.valueOf(UNIQUE_ID_PROJECT_NAME_DELIMITER)); if (comps.length > 0) { return comps[comps.length - 1]; } else { return null; } }
Source:
<code>private Class<?> getAdapterType(Object adapter) { <START> final Class<?> klazz; <END> if(adapter.getClass().getName().contains("$Proxy$")){ final String[] split = adapter.getClass().getName().split("\\$Proxy\\$"); try { klazz = Class.forName(split[0]); } catch (final ClassNotFoundException e) { throw new RuntimeException(e); } }else{ klazz = adapter.getClass(); } final Type[] genericInterfaces = klazz.getGenericInterfaces(); final ParameterizedType type = (ParameterizedType) genericInterfaces[0]; final Type actualType = type.getActualTypeArguments()[0]; if (actualType instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) actualType).getRawType(); } else { return (Class<?>) actualType; } }</code><technical_language>Instead of String comparison CDIProxies.isCDIProxy method check if class is a proxy</technical_language>

Target:
private Class<?> getAdapterType(Object adapter) { final Class<?> klazz = extractRawTypeIfPossible(adapter.getClass()); final Type[] genericInterfaces = klazz.getGenericInterfaces(); final ParameterizedType type = (ParameterizedType) genericInterfaces[0]; final Type actualType = type.getActualTypeArguments()[0]; if (actualType instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) actualType).getRawType(); } else { return (Class<?>) actualType; } }
Source:
<code>private KeyPair readDecodedKeyPair(final PlainBuffer keyBuffer) throws IOException, GeneralSecurityException { byte[] bytes = new byte[AUTH_MAGIC.length]; keyBuffer.readRawBytes(bytes); if (!ByteArrayUtils.equals(bytes, 0, AUTH_MAGIC, 0, AUTH_MAGIC.length)) { throw new IOException("This key does not contain the 'openssh-key-v1' format magic header"); } String cipherName = keyBuffer.readString(); String kdfName = keyBuffer.readString(); String kdfOptions = keyBuffer.readString(); int nrKeys = keyBuffer.readUInt32AsInt(); if (nrKeys != 1) { throw new IOException("We don't support having more than 1 key in the file (yet)."); } PublicKey publicKey = readPublicKey(new PlainBuffer(keyBuffer.readBytes())); PlainBuffer privateKeyBuffer = new PlainBuffer(keyBuffer.readBytes()); if ("none".equals(cipherName)) { logger.debug("Reading unencrypted keypair"); return readUnencrypted(privateKeyBuffer, publicKey); } else { logger.info("Keypair is encrypted with: " + cipherName + ", " + kdfName + ", " + kdfOptions); <START> throw new IOException("Cannot read encrypted keypair with " + cipherName + " yet.."); <END> } }</code><technical_language>Double full stop</technical_language>

Target:
private KeyPair readDecodedKeyPair(final PlainBuffer keyBuffer) throws IOException, GeneralSecurityException { byte[] bytes = new byte[AUTH_MAGIC.length]; keyBuffer.readRawBytes(bytes); if (!ByteArrayUtils.equals(bytes, 0, AUTH_MAGIC, 0, AUTH_MAGIC.length)) { throw new IOException("This key does not contain the 'openssh-key-v1' format magic header"); } String cipherName = keyBuffer.readString(); String kdfName = keyBuffer.readString(); String kdfOptions = keyBuffer.readString(); int nrKeys = keyBuffer.readUInt32AsInt(); if (nrKeys != 1) { throw new IOException("We don't support having more than 1 key in the file (yet)."); } PublicKey publicKey = readPublicKey(new PlainBuffer(keyBuffer.readBytes())); PlainBuffer privateKeyBuffer = new PlainBuffer(keyBuffer.readBytes()); if ("none".equals(cipherName)) { logger.debug("Reading unencrypted keypair"); return readUnencrypted(privateKeyBuffer, publicKey); } else { logger.info("Keypair is encrypted with: " + cipherName + ", " + kdfName + ", " + kdfOptions); throw new IOException("Cannot read encrypted keypair with " + cipherName + " yet."); } }