auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Integer invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { if (f.exists() && f.length() > 0) { try { <START> Charset cs = transcodingCharset(charset); <END> String fileString = Files.readFirstLine(f, cs != null ? cs : Charset.defaultCharset()); if (fileString == null || fileString.isEmpty()) { return null; } else { fileString = fileString.trim(); if (fileString.isEmpty()) { return null; } else { return Integer.parseInt(fileString); } } } catch (NumberFormatException x) { throw new IOException("corrupted content in " + f + ": " + x, x); } } return null; }</code><technical_language>Similarly, this nervous (and impact limited z/OS): expect status file in EBCDIC if z/OS, in ASCII other platform. if JVM z/OS fails report default charset EBCDIC (why??), need hard-code here</technical_language>

Target:
public Integer invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { if (f.exists() && f.length() > 0) { try { String fileString = Files.readFirstLine(f, Charset.defaultCharset()); if (fileString == null || fileString.isEmpty()) { return null; } else { fileString = fileString.trim(); if (fileString.isEmpty()) { return null; } else { return Integer.parseInt(fileString); } } } catch (NumberFormatException x) { throw new IOException("corrupted content in " + f + ": " + x, x); } } return null; }
Source:
<code>public void onResume(Activity activity) { <START> if (isLightModeCahnged(activity)) { <END> Intent intent = activity.getIntent(); activity.finish(); activity.overridePendingTransition(0, 0); activity.startActivity(intent); activity.overridePendingTransition(0, 0); } }</code><technical_language>@rezita, isLightModeCahnged renamed isLightModeChanged</technical_language>

Target:
public void onResume(Activity activity) { if (isLightModeChanged(activity)) { Intent intent = activity.getIntent(); activity.finish(); activity.overridePendingTransition(0, 0); activity.startActivity(intent); activity.overridePendingTransition(0, 0); } }
Source:
<code><START> private String runSshCommand(URIish sshUri, FS fs, String command) <END> throws IOException { RemoteSession session = null; Process process = null; StreamCopyThread errorThread = null; try (MessageWriter stderr = new MessageWriter()) { session = SshSessionFactory.getInstance().getSession(sshUri, null, fs, 5_000); process = session.exec(command, 0); errorThread = new StreamCopyThread(process.getErrorStream(), stderr.getRawStream()); errorThread.start(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), Constants.CHARSET))) { return reader.readLine(); } } finally { if (process != null) { process.destroy(); } if (errorThread != null) { try { errorThread.halt(); } catch (InterruptedException e) { } finally { errorThread = null; } } if (session != null) { SshSessionFactory.getInstance().releaseSession(session); } } }</code><technical_language>a candidate factored out. some tests</technical_language>

Target:
private String runSshCommand(URIish sshUri, FS fs, String command) throws IOException { RemoteSession session = null; Process process = null; StreamCopyThread errorThread = null; try (MessageWriter stderr = new MessageWriter()) { session = SshSessionFactory.getInstance().getSession(sshUri, null, fs, 5_000); process = session.exec(command, 0); errorThread = new StreamCopyThread(process.getErrorStream(), stderr.getRawStream()); errorThread.start(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), org.eclipse.jgit.lib.Constants.CHARSET))) { return reader.readLine(); } } finally { if (process != null) { process.destroy(); } if (errorThread != null) { try { errorThread.halt(); } catch (InterruptedException e) { } finally { errorThread = null; } } if (session != null) { SshSessionFactory.getInstance().releaseSession(session); } } }
Source:
<code>public synchronized Address<? extends Node> getOrCreateNodeByRecipe(RecipeTraceInfo recipeTrace) { ReteNodeRecipe recipe = recipeTrace.getRecipe(); Address<? extends Node> result = getNodesByRecipe().get(recipe); if (result != null) { if (getRecipeTraces().add(recipeTrace)) result.getNodeCache().assignTraceInfo(recipeTrace); } else { ReteNodeRecipe canonicalRecipe = recognizer.canonicalizeRecipe(recipe); if (canonicalRecipe != recipe) { result = getNodesByRecipe().get(canonicalRecipe); if (result != null) { recipeTrace.shadowWithEquivalentRecipe(canonicalRecipe); getNodesByRecipe().put(recipe, result); if (getRecipeTraces().add(recipeTrace)) result.getNodeCache().assignTraceInfo(recipeTrace); ensureParents(recipeTrace); } else { if (recipe instanceof IndexerRecipe) { } else { <START> throw new IllegalStateException(); <END> } } } if (result == null) { final Node freshNode = instantiateNodeForRecipe(recipeTrace, recipe); result = reteContainer.makeAddress(freshNode); } } return result; }</code><technical_language>Please add exception message</technical_language>

Target:
public synchronized Address<? extends Node> getOrCreateNodeByRecipe(RecipeTraceInfo recipeTrace) { ReteNodeRecipe recipe = recipeTrace.getRecipe(); Address<? extends Node> result = getNodesByRecipe().get(recipe); if (result != null) { if (getRecipeTraces().add(recipeTrace)) result.getNodeCache().assignTraceInfo(recipeTrace); } else { ReteNodeRecipe canonicalRecipe = recognizer.canonicalizeRecipe(recipe); if (canonicalRecipe != recipe) { result = getNodesByRecipe().get(canonicalRecipe); if (result != null) { recipeTrace.shadowWithEquivalentRecipe(canonicalRecipe); getNodesByRecipe().put(recipe, result); if (getRecipeTraces().add(recipeTrace)) result.getNodeCache().assignTraceInfo(recipeTrace); ensureParents(recipeTrace); } else { if (recipe instanceof IndexerRecipe) { } else { throw new IllegalStateException( "This should not happen: " + "non-indexer nodes are are supposed to be constructed " + "as soon as they are designated as canonical recipes"); } } } if (result == null) { final Node freshNode = instantiateNodeForRecipe(recipeTrace, recipe); result = reteContainer.makeAddress(freshNode); } } return result; }
Source:
<code>public String changePasswordRandom(PerunSession session, User user, String loginNamespace) throws PasswordOperationTimeoutException, LoginNotExistsException, InternalErrorException, PasswordChangeFailedException { char[] possibleCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()-_=+;:,<.>/?" .toCharArray(); String newRandomPassword = RandomStringUtils.random(12, 0, possibleCharacters.length - 1, false, false, possibleCharacters, new SecureRandom()); try { changePassword(session, user, loginNamespace, null, newRandomPassword, false); } catch (PasswordDoesntMatchException | PasswordStrengthFailedException e) { <START> throw new InternalError(e); <END> } String template = getPasswordResetTemplate(session, loginNamespace); String userLogin; try { Attribute userLoginAttribute = getPerunBl().getAttributesManagerBl().getAttribute(session, user, AttributesManager.NS_USER_ATTR_DEF + ":login-namespace:" + loginNamespace); userLogin = (String) userLoginAttribute.getValue(); } catch (WrongAttributeAssignmentException | AttributeNotExistsException e) { throw new InternalError(e); } return template .replace("{password}", newRandomPassword) .replace("{login}", userLogin); }</code><technical_language>InternalErrorException</technical_language>

Target:
public String changePasswordRandom(PerunSession session, User user, String loginNamespace) throws PasswordOperationTimeoutException, LoginNotExistsException, InternalErrorException, PasswordChangeFailedException { char[] possibleCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%&*()-_=+;:,<.>/?" .toCharArray(); String newRandomPassword = RandomStringUtils.random(12, 0, possibleCharacters.length - 1, false, false, possibleCharacters, new SecureRandom()); try { changePassword(session, user, loginNamespace, null, newRandomPassword, false); } catch (PasswordDoesntMatchException | PasswordStrengthFailedException e) { throw new InternalErrorException(e); } String template = getPasswordResetTemplate(session, loginNamespace); String userLogin; try { Attribute userLoginAttribute = getPerunBl().getAttributesManagerBl().getAttribute(session, user, AttributesManager.NS_USER_ATTR_DEF + ":login-namespace:" + loginNamespace); userLogin = (String) userLoginAttribute.getValue(); } catch (WrongAttributeAssignmentException | AttributeNotExistsException e) { throw new InternalErrorException(e); } return template .replace("{password}", StringEscapeUtils.escapeHtml4(newRandomPassword)) .replace("{login}", StringEscapeUtils.escapeHtml4(userLogin)); }
Source:
<code>public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() throws Exception { List<GlobalProperty> globalProperties = Context.getAdministrationService().getAllGlobalProperties(); <START> globalProperties.remove(3); <END> globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc")); Context.getAdministrationService().saveGlobalProperties(globalProperties); Assert.assertNotNull(Context.getAdministrationService().getGlobalPropertyObject("new prop").getUuid()); }</code><technical_language>removing this? test fail if don't</technical_language>

Target:
public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() throws Exception { List<GlobalProperty> globalProperties = Context.getAdministrationService().getAllGlobalProperties(); globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc")); Context.getAdministrationService().saveGlobalProperties(globalProperties); Assert.assertNotNull(Context.getAdministrationService().getGlobalPropertyObject("new prop").getUuid()); }
Source:
<code><START> private JBIterable<PsiErrorElement> errorElements(PsiElement root) { <END> return SyntaxTraverser.psiTraverser(root).traverse().filter(PsiErrorElement.class); }</code><technical_language>code smells errorElements parseAs static</technical_language>

Target:
private static JBIterable<PsiErrorElement> errorElements(PsiElement root) { return SyntaxTraverser.psiTraverser(root).traverse().filter(PsiErrorElement.class); }
Source:
<code>public List<ModuleMetaData> getAllModule() { <START> JsonModuleMetaDataProvider provider = new JsonModuleMetaDataProvider(new JsonFlowMetaDataProvider()); <END> return this.moduleMetadata.values().stream() .map(moduleMetadata -> provider.deserialiseModule(moduleMetadata)) .collect(Collectors.toList()); }</code><technical_language>do</technical_language>

Target:
public List<ModuleMetaData> getAllModule() { return this.moduleMetadata.values().stream() .map(moduleMetadata -> provider.deserialiseModule(moduleMetadata)) .collect(Collectors.toList()); }
Source:
<code>public Expr toExpr() { <START> return new LongExpr(value == null ? null : (value).longValue()); <END> }</code><technical_language>unnecessary parentheses</technical_language>

Target:
public Expr toExpr() { return new LongExpr(value == null ? null : value.longValue()); }
Source:
<code>public Object[] getElements(Object inputElement) { if (inputElement instanceof Object[]) { List<Object> result = new ArrayList<Object>(); for (Object next : (Object[]) inputElement) { if (next instanceof String) { String diagramCategory = (String) next; for (ModelTemplateDescription template : getTemplatesDescription()) { if ((diagramCategory == null || diagramCategory.equals(template.getLanguage())) && template.getDi_path() != null) { result.add(template); } } } } <START> result.add(0, new Object()); <END> return result.toArray(); } return new Object[0]; }</code><technical_language>UnsetObject.instance (from oep.infra.widgets). a singleton instance easier test nature of object: if (value == UnsetObject.instance){ //Nothing selected }</technical_language>

Target:
public Object[] getElements(Object inputElement) { if (inputElement instanceof Object[]) { List<Object> result = new ArrayList<Object>(); for (Object next : (Object[]) inputElement) { if (next instanceof String) { String diagramCategory = (String) next; for (ModelTemplateDescription template : getTemplatesDescription()) { if ((diagramCategory == null || diagramCategory.equals(template.getLanguage())) && template.getDi_path() != null) { result.add(template); } } } } result.add(0, UnsetObject.instance); return result.toArray(); } return new Object[0]; }
Source:
<code>protected void configure() { <START> bind(Tracer.class).toInstance(NoopTracerFactory.create()); <END> }</code><technical_language>bind TracerProvider well</technical_language>

Target:
protected void configure() { bind(Tracer.class).toProvider(new TracerProvider(NoopTracerFactory.create())); }
Source:
<code>private static Node constructAddOrStringNode(Iterator<CharSequence> partsIterator, Node argListNode) throws MalformedException { <START> if (partsIterator.hasNext()) { <END> CharSequence part = partsIterator.next(); Node partNode = null; if (part instanceof JsMessage.PlaceholderReference) { JsMessage.PlaceholderReference phRef = (JsMessage.PlaceholderReference) part; for (Node node : argListNode.children()) { if (node.isName()) { String arg = node.getString(); if (arg.equalsIgnoreCase(phRef.getName())) { partNode = IR.name(arg); } } } if (partNode == null) { throw new MalformedException( "Unrecognized message placeholder referenced: " + phRef.getName(), argListNode); } } else { partNode = IR.string(part.toString()); } if (partsIterator.hasNext()) { return IR.add(partNode, constructAddOrStringNode(partsIterator, argListNode)); } else { return partNode; } } else { return IR.string(""); } }</code><technical_language>avoid extra nesting (and diff smaller) making bailout condition return early</technical_language>

Target:
private static Node constructAddOrStringNode(Iterator<CharSequence> partsIterator, Node argListNode) throws MalformedException { if (!partsIterator.hasNext()) { return IR.string(""); } CharSequence part = partsIterator.next(); Node partNode = null; if (part instanceof JsMessage.PlaceholderReference) { JsMessage.PlaceholderReference phRef = (JsMessage.PlaceholderReference) part; for (Node node : argListNode.children()) { if (node.isName()) { String arg = node.getString(); if (arg.equalsIgnoreCase(phRef.getName())) { partNode = IR.name(arg); } } } if (partNode == null) { throw new MalformedException( "Unrecognized message placeholder referenced: " + phRef.getName(), argListNode); } } else { partNode = IR.string(part.toString()); } if (partsIterator.hasNext()) { return IR.add(partNode, constructAddOrStringNode(partsIterator, argListNode)); } else { return partNode; } }
Source:
<code>public IStatus validate(IProject project, String path) { File dir = new File(path); int confidence = 0; if (dir.isDirectory()) { confidence += 5; List<String> data = Arrays.asList(dir.list()); for (String file : data) { if (file.endsWith(".dat")) { try { <START> DatParser dp = new DatParser(new File(file)); <END> dp.iterator().next(); } catch (IllegalArgumentException e) { confidence = Integer.MIN_VALUE; } confidence += 4; } if (file.endsWith(".map")) { try { if (MapParser.create(new File(file)) != null) { confidence += 4; } } catch (IOException e) { confidence = Integer.MIN_VALUE; } } if (file.endsWith("*.sym")) { confidence += 3; } } } if (confidence > 10) { return new TraceValidationStatus(confidence, Activator.class.getCanonicalName()); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most probably not a UFTrace"); }</code><technical_language>prepend path file name. I get a NoSuchFileException a file file name</technical_language>

Target:
public IStatus validate(IProject project, String path) { File dir = new File(path); int confidence = 0; if (dir.isDirectory()) { confidence += 5; List<File> data = Arrays.asList(dir.listFiles()); for (File file : data) { String extension = FilenameUtils.getExtension(file.getName()); if (extension.equals(".dat")) { try { DatParser dp = new DatParser(file); dp.iterator().next(); } catch (IllegalArgumentException e) { confidence = Integer.MIN_VALUE; } confidence += 4; } if (extension.equals(".map")) { try { if (MapParser.create(file) != null) { confidence += 4; } } catch (IOException e) { confidence = Integer.MIN_VALUE; } } if (extension.equals("*.sym")) { confidence += 3; } } } if (confidence > 10) { return new TraceValidationStatus(confidence, Activator.class.getCanonicalName()); } return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Most probably not a UFTrace"); }
Source:
<code>public void validate(JobParameters parameters) throws JobParametersInvalidException { <START> String configRestartabilityAllowValue = parameters.getString(JobParametersNames.STATISTICS_OVERWRITE); <END> ParametersValidatorUtil.checkIsNotNullOrEmptyString( configRestartabilityAllowValue, JobParametersNames.STATISTICS_OVERWRITE); ParametersValidatorUtil.checkIsBoolean( configRestartabilityAllowValue,JobParametersNames.CONFIG_RESTARTABILITY_ALLOW); }</code><technical_language>statisticsOverwriteValue</technical_language>

Target:
public void validate(JobParameters parameters) throws JobParametersInvalidException { String statisticsOverwriteValue = parameters.getString(JobParametersNames.STATISTICS_OVERWRITE); ParametersValidatorUtil.checkIsNotNullOrEmptyString( statisticsOverwriteValue, JobParametersNames.STATISTICS_OVERWRITE); ParametersValidatorUtil.checkIsBoolean( statisticsOverwriteValue,JobParametersNames.STATISTICS_OVERWRITE); }
Source:
<code>public UndertowSecurityProvider getSecurityProvider() { <START> if (this.securityProvider == null) { <END> return getComponent().getSecurityProvider(); } return this.securityProvider; }</code><technical_language>getter/setters plain, tricks. Instead creating endpoint in component, set security provider endpoint correctly</technical_language>

Target:
public UndertowSecurityProvider getSecurityProvider() { return this.securityProvider; }
Source:
<code>public String toString() { return getId(); <START> } <END></code><technical_language>prefer "Context: " + getId()</technical_language>

Target:
public String toString() { return "Context: " + getId(); }
Source:
<code>default boolean anyExists() { <START> return entities(Pager.builder().withPageSize(1).orderBy(Order.unspecified()).build()).hasNext(); <END> }</code><technical_language>java Pager.builder().withPageSize(1).orderBy(Order.unspecified)).build() replaced by: java Pager.single()</technical_language>

Target:
default boolean anyExists() { return entities(Pager.single()).hasNext(); }
Source:
<code>public static void killRunningImageJobs() { Job[] currentJobs = Job.getJobManager().find(null); for (Job job : currentJobs) { <START> if (job.getName().startsWith(JOB_PULLING_DOCKER_IMAGE) || job.getName().startsWith(JOB_TAGGING_IMAGE) <END> || job.getName().startsWith(JOB_PUSHING_DOCKER_IMAGE)|| job.getName().startsWith(JOB_OPENNING_CONNECTION)) { job.cancel(); } } }</code><technical_language>job.getName() extracted variable for more readability</technical_language>

Target:
public static void killRunningImageJobs() { Job[] currentJobs = Job.getJobManager().find(null); for (Job job : currentJobs) { String jobName = job.getName(); if (jobName.startsWith(JOB_PULLING_DOCKER_IMAGE) || jobName.startsWith(JOB_TAGGING_IMAGE) || jobName.startsWith(JOB_PUSHING_DOCKER_IMAGE)|| jobName.startsWith(JOB_OPENNING_CONNECTION)) { job.cancel(); } } }
Source:
<code>public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog) { super(localCatalog, remoteCatalog); <START> localCatalog.getClusters().get("cluster").getDrclusterid(); <END> }</code><technical_language>This needed</technical_language>

Target:
public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog) { super(localCatalog, remoteCatalog); }
Source:
<code>public SchedulableEntityInstanceResult getFeedSLAMissPendingAlerts(String feedName, String startStr, String endStr, String colo) { Set<SchedulableEntityInstance> instances = new HashSet<>(); try { checkColo(colo); Date start = EntityUtil.parseDateUTC(startStr); Date end = (endStr == null) ? new Date() : EntityUtil.parseDateUTC(endStr); if (StringUtils.isBlank(feedName)) { <START> instances.addAll(EntitySLAMonitoringService.get().getFeedSLAMissPendingAlerts(start, end)); <END> } else { for (String clusterName : DeploymentUtil.getCurrentClusters()) { instances.addAll(EntitySLAMonitoringService.get().getFeedSLAMissPendingAlerts(feedName, clusterName, start, end, EntityType.FEED.toString())); } } } catch (FalconException e) { throw FalconWebException.newAPIException(e); } SchedulableEntityInstanceResult result = new SchedulableEntityInstanceResult(APIResult.Status.SUCCEEDED, "Success!"); result.setCollection(instances.toArray()); return result; }</code><technical_language>changes fine, but, is API exposed for FeedSLA, need extend API add/modify methods return process SLA misses</technical_language>

Target:
public SchedulableEntityInstanceResult getFeedSLAMissPendingAlerts(String feedName, String startStr, String endStr, String colo) { Set<SchedulableEntityInstance> instances = new HashSet<>(); try { checkColo(colo); Date start = EntityUtil.parseDateUTC(startStr); Date end = (endStr == null) ? new Date() : EntityUtil.parseDateUTC(endStr); if (StringUtils.isBlank(feedName)) { instances.addAll(EntitySLAMonitoringService.get().getEntitySLAMissPendingAlerts(start, end)); } else { for (String clusterName : DeploymentUtil.getCurrentClusters()) { instances.addAll(EntitySLAMonitoringService.get().getEntitySLAMissPendingAlerts(feedName, clusterName, start, end, EntityType.FEED.toString())); } } } catch (FalconException e) { throw FalconWebException.newAPIException(e); } SchedulableEntityInstanceResult result = new SchedulableEntityInstanceResult(APIResult.Status.SUCCEEDED, "Success!"); result.setCollection(instances.toArray()); return result; }
Source:
<code>protected void upgradeFrom(UpdateUI ui, CurrentSchemaVersion curr, ReviewDb db, boolean toTargetVersion) throws OrmException { throw new OrmException("Cannot upgrade from " + curr.versionNbr + "; manually run scripts from" <START> + " <LINK_0>" <END> + " and restart."); }</code><technical_language>This true. need run earlier version of gerrit init this schema version</technical_language>

Target:
protected void upgradeFrom(UpdateUI ui, CurrentSchemaVersion curr, ReviewDb db, boolean toTargetVersion) throws OrmException { throw new OrmException("Cannot upgrade from " + curr.versionNbr + "; run first gerrit version 2.1.5 or 2.1.4 to upgrade the" + " schema at least to version 34" + "; then restart this new gerrit version."); }
Source:
<code>public void waitForSchemaUpdates(Session session, String keyspace, long delay, int maxRetries) throws InterruptedException { String configId = "org.hawkular.metrics"; String configName = "schema-version"; int retries = 0; PreparedStatement getVersion = null; SchemaService schemaService = new SchemaService(session, keyspace); String version = schemaService.getSchemaVersion(); while (maxRetries > retries) { try { if (getVersion == null) { getVersion = session.prepare("SELECT value FROM " + keyspace + ".sys_config " + "WHERE config_id = ? AND name = ?"); } ResultSet resultSet = session.execute(getVersion.bind(configId, configName)); if (!resultSet.isExhausted()) { String schemaVersion = resultSet.one().getString(0); if(version.equals(schemaVersion)) { <START> logger.infof("Hawkular Metrics is up to date at version %s", version); <END> return; } else { logger.infof("Hawkular Metrics schema version does not match," + " should be %s, present: %s, Trying again in %d ms", version, schemaVersion, delay); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Version check failed", e); } else { logger.infof("Version check failed: %s", e.getMessage()); } logger.infof("Trying again in %d ms", delay); } retries++; Thread.sleep(delay); } throw new SchemaVersionCheckException("Version check unsuccessful after " + maxRetries + " attempts"); }</code><technical_language>I change this slightly to, "Hawkular Metrics schema is date version %s"</technical_language>

Target:
public void waitForSchemaUpdates(Session session, String keyspace, long delay, int maxRetries) throws InterruptedException { String configId = "org.hawkular.metrics"; String configName = "schema-version"; int retries = 0; PreparedStatement getVersion = null; SchemaService schemaService = new SchemaService(session, keyspace); String version = schemaService.getSchemaVersion(); while (maxRetries > retries) { try { if (getVersion == null) { getVersion = session.prepare("SELECT value FROM " + keyspace + ".sys_config " + "WHERE config_id = ? AND name = ?"); } ResultSet resultSet = session.execute(getVersion.bind(configId, configName)); if (!resultSet.isExhausted()) { String schemaVersion = resultSet.one().getString(0); if(version.equals(schemaVersion)) { logger.infof("Hawkular Metrics schema is up to date at version %s", version); return; } else { logger.infof("Hawkular Metrics schema version does not match," + " should be %s, present: %s, Trying again in %d ms", version, schemaVersion, delay); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Version check failed", e); } else { logger.infof("Version check failed: %s", e.getMessage()); } logger.infof("Trying again in %d ms", delay); } retries++; Thread.sleep(delay); } throw new SchemaVersionCheckException("Version check unsuccessful after " + maxRetries + " attempts"); }
Source:
<code>public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception { Long startId = getParam(parameters, "start_id").orElse(0); final OptionalLong maybeMaxId = getParam(parameters, "max_id"); <START> Long patchBackfillParam = getParam(parameters, "force_patch").orElse(0); <END> boolean forcePatchBackfill = patchBackfillParam != 0; logger.info("Execute called start_id={} max_id={} - processing", startId, maybeMaxId); try { logger.info("Request accepted"); if (forcePatchBackfill) { executor.execute(() -> worker.executePatchCreatedAndDetailsEntered(startId, maybeMaxId)); } else { executor.execute(() -> worker.execute(startId, maybeMaxId)); } output.println("Accepted"); } catch (java.util.concurrent.RejectedExecutionException e) { logger.info("Rejected request, worker already running"); output.println("Rejected request, worker already running"); } }</code><technical_language>is a PATCH, this true/false avoids deriving forcePatchBackfill</technical_language>

Target:
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception { Long startId = getLongParam(parameters, "start_id").orElse(0); final OptionalLong maybeMaxId = getLongParam(parameters, "max_id"); Boolean patchBackfill = getBoolParam(parameters, "force_patch").orElse(false); logger.info("Execute called start_id={} max_id={} - processing", startId, maybeMaxId); try { logger.info("Request accepted"); if (patchBackfill) { executor.execute(() -> worker.executePatchCreatedAndDetailsEntered(startId, maybeMaxId)); } else { executor.execute(() -> worker.execute(startId, maybeMaxId)); } output.println("Accepted"); } catch (java.util.concurrent.RejectedExecutionException e) { logger.info("Rejected request, worker already running"); output.println("Rejected request, worker already running"); } }
Source:
<code>public void testFindLiveVersionFile() throws Exception{ String folderName = "/testOldFile"+UUIDGenerator.generateUuid(); Folder ff = APILocator.getFolderAPI().createFolders(folderName, host, user, false); java.io.File tmp=new java.io.File(APILocator.getFileAPI().getRealAssetPathTmpBinary()+java.io.File.separator+"testOldFile"); if(!tmp.exists()) tmp.mkdirs(); java.io.File data=new java.io.File(tmp, "test-"+UUIDGenerator.generateUuid()+".txt"); FileWriter fw=new FileWriter(data,true); fw.write("file content"); fw.close(); File file = new File(); file.setFileName("legacy.txt"); file.setFriendlyName("legacy.txt"); file.setMimeType("text/plain"); file.setTitle("legacy.txt"); file.setSize((int)data.length()); file.setModUser(user.getUserId()); file.setModDate(Calendar.getInstance().getTime()); <START> file = APILocator.getFileAPI().saveFile(file, data, ff, user, false); <END> APILocator.getFileAPI().publishFile(file, user, false); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(ff, user, false); }</code><technical_language>extracted method createLegacyFile</technical_language>

Target:
public void testFindLiveVersionFile() throws Exception{ File file = createLegacyFile(); APILocator.getFileAPI().publishFile(file, user, false); Versionable verAPI = APILocator.getVersionableAPI().findLiveVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); Folder folder = APILocator.getFileAPI().getFileFolder(file, host, user, false); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(folder, user, false); }
Source:
<code>public Void perform( Task task, TaskActionToolbox toolbox ) throws IOException { toolbox.verifyTaskLocksAndSinglePartitionSettitude(task, segments, true); toolbox.getIndexerMetadataStorageCoordinator().updateSegmentMetadata(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension("dataSource", task.getDataSource()) <START> .setDimension("taskType", task.getType()); <END> for (DataSegment segment : segments) { metricBuilder.setDimension("interval", segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segmentMoved/bytes", segment.getSize())); } return null; }</code><technical_language>set a constant limit capacity for typos</technical_language>

Target:
public Void perform( Task task, TaskActionToolbox toolbox ) throws IOException { toolbox.verifyTaskLocksAndSinglePartitionSettitude(task, segments, true); toolbox.getIndexerMetadataStorageCoordinator().updateSegmentMetadata(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setDimension(DruidMetrics.DATASOURCE, task.getDataSource()) .setDimension(DruidMetrics.TASK_TYPE, task.getType()); for (DataSegment segment : segments) { metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("segment/moved/bytes", segment.getSize())); } return null; }
Source:
<code>private long persistVersionId(long articlePk, int revisionNumber) { return parentService.hibernateTemplate.execute(session -> { SQLQuery blankOtherRevisions = session.createSQLQuery("" + <START> "UPDATE articleVersion SET revisionNumber = NULL, lastModified = NOW() " + <END> "WHERE articleId=:articleId AND revisionNumber=:revisionNumber"); blankOtherRevisions.setParameter("articleId", articlePk); blankOtherRevisions.setParameter("revisionNumber", revisionNumber); blankOtherRevisions.executeUpdate(); SQLQuery insertEvent = session.createSQLQuery("" + "INSERT INTO articleVersion (articleId, revisionNumber, publicationState, lastModified) " + "VALUES (:articleId, :revisionNumber, :publicationState, NOW())"); insertEvent.setParameter("articleId", articlePk); insertEvent.setParameter("revisionNumber", revisionNumber); insertEvent.setParameter("publicationState", ArticleItem.PublicationState.INGESTED.getValue()); insertEvent.executeUpdate(); return getLastInsertId(session); }); }</code><technical_language>publication state updated</technical_language>

Target:
private long persistVersionId(long articlePk, int revisionNumber) { return parentService.hibernateTemplate.execute(session -> { SQLQuery replaceOtherRevisions = session.createSQLQuery("" + "UPDATE articleVersion SET publicationState = :replaced, lastModified = NOW() " + "WHERE articleId = :articleId AND revisionNumber = :revisionNumber " + " AND publicationState != :replaced"); replaceOtherRevisions.setParameter("articleId", articlePk); replaceOtherRevisions.setParameter("revisionNumber", revisionNumber); replaceOtherRevisions.setParameter("replaced", ArticleItem.PublicationState.REPLACED.getValue()); replaceOtherRevisions.executeUpdate(); SQLQuery insertEvent = session.createSQLQuery("" + "INSERT INTO articleVersion (articleId, revisionNumber, publicationState, lastModified) " + "VALUES (:articleId, :revisionNumber, :publicationState, NOW())"); insertEvent.setParameter("articleId", articlePk); insertEvent.setParameter("revisionNumber", revisionNumber); insertEvent.setParameter("publicationState", ArticleItem.PublicationState.INGESTED.getValue()); insertEvent.executeUpdate(); return getLastInsertId(session); }); }
Source:
<code>public static void setServeReadTips(boolean serveReadTips) { <START> log(LogUtil.info("setServiceReadTips = '" + serveReadTips + "'")); END> IEclipsePreferences node = getPreferences(); node.putBoolean(PREF_SERVE_READ_TIPS, serveReadTips); try { node.flush(); } catch (BackingStoreException e) { throw new RuntimeException(e); } }</code><technical_language>Please remove this write user -friendly. user understand current message</technical_language>

Target:
public static void setServeReadTips(boolean serveReadTips) { log(LogUtil.info("Entering method setServeReadTips with boolean parameter = '" + serveReadTips + "'")); IEclipsePreferences node = getPreferences(); node.putBoolean(PREF_SERVE_READ_TIPS, serveReadTips); try { node.flush(); } catch (BackingStoreException e) { log(LogUtil.error(e)); } }
Source:
<code>public static void workflowGarbageCollection(final WorkflowControllerDataProvider dataProvider, final HelixManager manager) { Set<String> toBeDeletedWorkflows = new HashSet<>(); try { Set<String> existingWorkflowContexts = new HashSet<>(dataProvider.getContexts().keySet()); for (String entry : existingWorkflowContexts) { if (entry != null) { WorkflowConfig cfg = dataProvider.getWorkflowConfig(entry); WorkflowContext ctx = dataProvider.getWorkflowContext(entry); <START> if (ctx != null && ctx.getId().equals(TaskUtil.WORKFLOW_CONTEXT_KW)) { if (cfg == null) { <END> toBeDeletedWorkflows.add(entry); } } } } } catch (Exception e) { LOG.warn(String.format( "Exception occurred while creating a list of all existing contexts with missing config!! Reason: %s"), e.getMessage()); } HelixDataAccessor accessor = manager.getHelixDataAccessor(); HelixPropertyStore<ZNRecord> propertyStore = manager.getHelixPropertyStore(); for (String workflowName : toBeDeletedWorkflows) { LOG.warn(String.format( "WorkflowContext exists for workflow %s. However, Workflow Config is missing! Deleting the WorkflowConfig and IdealState!!", workflowName)); if (!cleanupWorkflowIdealStateExtView(accessor, workflowName)) { LOG.warn(String.format( "Error occurred while trying to remove workflow idealstate/externalview for %s.", workflowName)); continue; } if (!removeWorkflowContext(propertyStore, workflowName)) { LOG.warn(String.format("Error occurred while trying to remove workflow context for %s.", workflowName)); continue; } } }</code><technical_language>merge if's</technical_language>

Target:
public static void workflowGarbageCollection(final WorkflowControllerDataProvider dataProvider, final HelixManager manager) { Set<String> existingContexts; try { existingContexts = new HashSet<>(dataProvider.getContexts().keySet()); } catch (Exception e) { LOG.warn( "Exception occurred while creating a list of all workflow/job context names!", e); return; } Set<String> toBeDeletedWorkflows = new HashSet<>(); for (String entry : existingContexts) { WorkflowConfig cfg = dataProvider.getWorkflowConfig(entry); WorkflowContext ctx = dataProvider.getWorkflowContext(entry); if (ctx != null && ctx.getId().equals(TaskUtil.WORKFLOW_CONTEXT_KW) && cfg == null) { toBeDeletedWorkflows.add(entry); } } HelixDataAccessor accessor = manager.getHelixDataAccessor(); HelixPropertyStore<ZNRecord> propertyStore = manager.getHelixPropertyStore(); for (String workflowName : toBeDeletedWorkflows) { LOG.warn(String.format( "WorkflowContext exists for workflow %s. However, Workflow Config is missing! Deleting the WorkflowConfig and IdealState!!", workflowName)); if (!cleanupWorkflowIdealStateExtView(accessor, workflowName)) { LOG.warn(String.format( "Error occurred while trying to remove workflow idealstate/externalview for %s.", workflowName)); continue; } if (!removeWorkflowContext(propertyStore, workflowName)) { LOG.warn(String.format("Error occurred while trying to remove workflow context for %s.", workflowName)); continue; } } }
Source:
<code>default String getPreferenceKey() { return <START> getClass().getCanonicalName(); <END> }</code><technical_language>getName(), getCanonicalName() return null for anonymous class</technical_language>

Target:
default String getPreferenceKey() { return getClass().getName(); }
Source:
<code>public void testEmptyPasswordWithNonRootUser() { thrown.expect(RuntimeException.class); MySQLContainer container = (MySQLContainer) new MySQLContainer("mysql:5.5") .withDatabaseName("TEST") .withUsername("test") .withPassword("") .withEnv("MYSQL_ROOT_HOST", "%"); <START> container.start(); <END> container.stop(); }</code><technical_language>do a try-catch here, catching ContainerException</technical_language>

Target:
public void testEmptyPasswordWithNonRootUser() { MySQLContainer container = (MySQLContainer) new MySQLContainer("mysql:5.5").withDatabaseName("TEST") .withUsername("test").withPassword("").withEnv("MYSQL_ROOT_HOST", "%"); try { container.start(); fail("ContainerLaunchException expected to be thrown"); } catch (ContainerLaunchException e) { } finally { container.stop(); } }
Source:
<code><START> public void mergeStatisticsCorenerCaseNodesTest() { <END> SegmentStoreStatistics expected = new SegmentStoreStatistics(); SegmentStoreStatistics a = new SegmentStoreStatistics(); SegmentStoreStatistics b = new SegmentStoreStatistics(); SegmentStoreStatistics c = new SegmentStoreStatistics(); SegmentStoreStatistics d = new SegmentStoreStatistics(); SegmentStoreStatistics e = new SegmentStoreStatistics(); SegmentStoreStatistics f = new SegmentStoreStatistics(); List<@NonNull ISegment> fixture = new ArrayList<>(); c.merge(d); f.update(new BasicSegment(1, 2)); e.update(new BasicSegment(1, 2)); for (int i = 0; i < 10; i++) { BasicSegment seg = new BasicSegment(i, i * 2 + 2); expected.update(seg); a.update(seg); fixture.add(seg); } validate(d, c); e.merge(d); validate(f, e); c.merge(f); validate(f, c); a.merge(b); OfflineStatisticsCalculator offlineExpected = new OfflineStatisticsCalculator(fixture); validate(offlineExpected, expected); validate(expected, a); }</code><technical_language>obvious corner cases tested. update I in merge method. verify I forget anything. I a good job of tests a bug in copy method ;-)</technical_language>

Target:
public void mergeStatisticsCorenerCaseNodesTest() { ISegment segment = new BasicSegment(1, 5); SegmentStoreStatistics noSegments = new SegmentStoreStatistics(); SegmentStoreStatistics oneSegment = new SegmentStoreStatistics(); oneSegment.update(segment); SegmentStoreStatistics testStats = new SegmentStoreStatistics(); SegmentStoreStatistics testStats2 = new SegmentStoreStatistics(); testStats.update(segment); testStats.merge(testStats2); validate(oneSegment, testStats); validate(noSegments, testStats2); testStats2.merge(testStats); validate(oneSegment, testStats); validate(oneSegment, testStats2); SegmentStoreStatistics expected = fillSmallStatistics(); expected.update(segment); testStats = fillSmallStatistics(); testStats.merge(testStats2); validate(oneSegment, testStats2); validate(expected, testStats); testStats = fillSmallStatistics(); testStats2.merge(testStats); validate(fillSmallStatistics(), testStats); validate(expected, testStats2); }
Source:
<code>private Bundle getBundleFromBundlesArray(String bundleSymbolicName) { Bundle[] bundles = bundleContext.getBundles(); <START> for(int i = 0; i < bundles.length; i++) { <END> if(bundles[i].getSymbolicName() == null) { continue; } else if (bundles[i].getSymbolicName().equals(bundleSymbolicName)) { return bundles[i]; } } return null; }</code><technical_language>do need track of count, this foreach</technical_language>

Target:
private Bundle getBundleFromBundlesArray(String bundleSymbolicName) { Bundle[] bundles = bundleContext.getBundles(); for(Bundle bundle : bundles) { if (bundle.getSymbolicName() == null) { continue; } else if (bundle.getSymbolicName().equals(bundleSymbolicName)) { return bundle; } } return null; }
Source:
<code>private static WebArchive createDeploymentWithSpringMvcDispatcher() { WebArchive archive = ShrinkWrap.create(WebArchive.class, deploymentWithSpringMvcDispatcherSpringIncluded + ".war") .addClass(TestResource.class) .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/web.xml", "web.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/mvc-dispatcher-servlet.xml", "mvc-dispatcher-servlet.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/applicationContext.xml", "applicationContext.xml"); archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new PropertyPermission("arquillian.*", "read"), new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader"), <START> new FilePermission("<<ALL FILES>>", "read"), <END> new LoggingPermission("control", "") ), "permissions.xml"); TestUtilSpring.addSpringLibraries(archive); archive.as(ZipExporter.class).exportTo(new File("target", deploymentWithSpringMvcDispatcherSpringIncluded + ".war"), true); return archive; }</code><technical_language>needed test pass</technical_language>

Target:
private static WebArchive createDeploymentWithSpringMvcDispatcher() { WebArchive archive = ShrinkWrap.create(WebArchive.class, deploymentWithSpringMvcDispatcherSpringIncluded + ".war") .addClass(TestResource.class) .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/web.xml", "web.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/mvc-dispatcher-servlet.xml", "mvc-dispatcher-servlet.xml") .addAsWebInfResource(AddSpringResteasyAsResourceRootTest.class.getPackage(), "mvc-dispatcher-servlet/applicationContext.xml", "applicationContext.xml"); archive.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader"), new FilePermission("<<ALL FILES>>", "read"), new LoggingPermission("control", "") ), "permissions.xml"); TestUtilSpring.addSpringLibraries(archive); archive.as(ZipExporter.class).exportTo(new File("target", deploymentWithSpringMvcDispatcherSpringIncluded + ".war"), true); return archive; }
Source:
<code>public Mono<PollResponse<T>> poll() { <START> return pollOperation.apply(pollResponse.get()) <END> .doOnEach(pollResponseSignal -> { if (pollResponseSignal.get() != null) { pollResponse.set(pollResponseSignal.get()); } }); }</code><technical_language>ok good for me</technical_language>

Target:
public Mono<PollResponse<T>> poll() { return pollOperation.apply(this.pollResponse) .doOnEach(pollResponseSignal -> { if (pollResponseSignal.get() != null) { this.pollResponse = pollResponseSignal.get(); } }); }
Source:
<code>public Monitor getPrimaryMonitor () { checkDevice (); if (OS.IsWinCE || OS.WIN32_VERSION < OS.VERSION (4, 10)) { Monitor monitor = new Monitor(); int width = OS.GetSystemMetrics (OS.SM_CXSCREEN); int height = OS.GetSystemMetrics (OS.SM_CYSCREEN); monitor.width = width; monitor.height = height; RECT rect = new RECT (); OS.SystemParametersInfo (OS.SPI_GETWORKAREA, 0, rect, 0); monitor.clientX = rect.left; monitor.clientY = rect.top; monitor.clientWidth = rect.right - rect.left; monitor.clientHeight = rect.bottom - rect.top; long hDC = internal_new_GC (null); monitor.dpi = (OS.GetDeviceCaps (hDC, OS.LOGPIXELSX)); monitor.imageSelectorIndex = DpiUtil.mapDpiToImageSelectorIndex (monitor.dpi); internal_dispose_GC (hDC, null); return monitor; <START> } <END> monitors = new Monitor [4]; Callback callback = new Callback (this, "monitorEnumProc", 4); long lpfnEnum = callback.getAddress (); if (lpfnEnum == 0) error (SWT.ERROR_NO_MORE_CALLBACKS); OS.EnumDisplayMonitors (0, null, lpfnEnum, 0); callback.dispose (); Monitor result = null; MONITORINFO lpmi = new MONITORINFO (); lpmi.cbSize = MONITORINFO.sizeof; for (int i = 0; i < monitorCount; i++) { Monitor monitor = monitors [i]; OS.GetMonitorInfo (monitors [i].handle, lpmi); if ((lpmi.dwFlags & OS.MONITORINFOF_PRIMARY) != 0) { result = monitor; break; } } monitors = null; monitorCount = 0; return result; }</code><technical_language>compute dpi & imageSelectorIndex in this method</technical_language>

Target:
public Monitor getPrimaryMonitor () { checkDevice (); if (OS.IsWinCE || OS.WIN32_VERSION < OS.VERSION (4, 10)) { Monitor monitor = new Monitor(); int width = OS.GetSystemMetrics (OS.SM_CXSCREEN); int height = OS.GetSystemMetrics (OS.SM_CYSCREEN); monitor.width = width; monitor.height = height; RECT rect = new RECT (); OS.SystemParametersInfo (OS.SPI_GETWORKAREA, 0, rect, 0); monitor.clientX = rect.left; monitor.clientY = rect.top; monitor.clientWidth = rect.right - rect.left; monitor.clientHeight = rect.bottom - rect.top; long hDC = internal_new_GC (null); monitor.dpi = (OS.GetDeviceCaps (hDC, OS.LOGPIXELSX)); monitor.imageSelectorIndex = DPIUtil.mapDPIToImageSelectorIndex (monitor.dpi); internal_dispose_GC (hDC, null); return monitor; } monitors = new Monitor [4]; Callback callback = new Callback (this, "monitorEnumProc", 4); long lpfnEnum = callback.getAddress (); if (lpfnEnum == 0) error (SWT.ERROR_NO_MORE_CALLBACKS); OS.EnumDisplayMonitors (0, null, lpfnEnum, 0); callback.dispose (); Monitor result = null; MONITORINFO lpmi = new MONITORINFO (); lpmi.cbSize = MONITORINFO.sizeof; for (int i = 0; i < monitorCount; i++) { Monitor monitor = monitors [i]; OS.GetMonitorInfo (monitors [i].handle, lpmi); if ((lpmi.dwFlags & OS.MONITORINFOF_PRIMARY) != 0) { result = monitor; break; } } monitors = null; monitorCount = 0; return result; }
Source:
<code>public void introspect() throws IOException { JsonObject msgBodyJson = new JsonObject(); msgBodyJson.addProperty("query", IntrospectionQuery.INTROSPECTION_QUERY); HttpRequestBody msgBody = new HttpRequestBody(msgBodyJson.toString()); HttpRequestHeader msgHeader = new HttpRequestHeader(HttpRequestHeader.POST, endpointUrl, "HTTP/1.1"); msgHeader.setHeader("Accept", "application/json"); msgHeader.setHeader("Content-Type", "application/json"); msgHeader.setContentLength(msgBody.length()); importMessage = new HttpMessage(msgHeader, msgBody); requestHandler.makeRequest(importMessage); try { Map<String, Object> result = new Gson() .fromJson( importMessage.getResponseBody().toString(), new TypeToken<Map<String, Object>>() {}.getType()); @SuppressWarnings("unchecked") Document schema = new IntrospectionResultToSchema() .createSchemaDefinition((Map<String, Object>) result.get("data")); String schemaSDL = new SchemaPrinter().print(schema); <START> Thread t = new Thread(() -> parse(schemaSDL)); <END> t.start(); } catch (JsonSyntaxException e) { throw new IOException("The response was not valid JSON."); } }</code><technical_language>Name thread ZAP- prefix easier a ZAP thread (e.g. ZAP-GraphQL-Parser). - thread started in importUrl, extract a method this avoid duplicating in of them</technical_language>

Target:
public void introspect() throws IOException { JsonObject msgBodyJson = new JsonObject(); msgBodyJson.addProperty("query", IntrospectionQuery.INTROSPECTION_QUERY); HttpRequestBody msgBody = new HttpRequestBody(msgBodyJson.toString()); HttpRequestHeader msgHeader = new HttpRequestHeader(HttpRequestHeader.POST, endpointUrl, "HTTP/1.1"); msgHeader.setHeader("Accept", "application/json"); msgHeader.setHeader("Content-Type", "application/json"); msgHeader.setContentLength(msgBody.length()); HttpMessage importMessage = new HttpMessage(msgHeader, msgBody); requestor.send(importMessage); try { Map<String, Object> result = new Gson() .fromJson( importMessage.getResponseBody().toString(), new TypeToken<Map<String, Object>>() {}.getType()); @SuppressWarnings("unchecked") Document schema = new IntrospectionResultToSchema() .createSchemaDefinition((Map<String, Object>) result.get("data")); String schemaSdl = new SchemaPrinter().print(schema); parse(schemaSdl); } catch (JsonSyntaxException e) { throw new IOException("The response was not valid JSON."); } }