auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ChePluginReference cheServiceReference = (ChePluginReference) o; return Objects.equals(name, cheServiceReference.name) && Objects.equals(version, cheServiceReference.version) && Objects.equals(parameters, cheServiceReference.parameters); }

Target:
public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ChePluginReference chePluginReference = (ChePluginReference) o; return Objects.equals(name, chePluginReference.name) && Objects.equals(version, chePluginReference.version) && Objects.equals(parameters, chePluginReference.parameters); }
Source:
public Boolean getAlignSampling() { return _alignSampling; }

Target:
public Optional<Boolean> getAlignSampling() { return _alignSampling; }
Source:
Request build() { String apiUrl = this.apiUrl; StringBuilder url = new StringBuilder(apiUrl); if (apiUrl.endsWith("/")) { url.deleteCharAt(url.length() - 1); } url.append(relativeUrl); StringBuilder queryParams = this.queryParams; if (queryParams != null) { url.append(queryParams); } RequestBody body = this.body; if (formEncodingBuilder != null) { body = formEncodingBuilder.build(); } else if (multipartBuilder != null) { body = multipartBuilder.build(); } Headers.Builder headerBuilder = this.headers; if (contentTypeHeader != null) { if (body != null) { body = new MediaTypeOverridingRequestBody(body, contentTypeHeader); } else { if (headerBuilder == null) { headerBuilder = new Headers.Builder(); } headerBuilder.add("Content-Type", contentTypeHeader); } } Headers headers = headerBuilder != null ? headerBuilder.build() : NO_HEADERS; return new Request.Builder() .url(url.toString()) .method(requestMethod, body) .headers(headers) .build(); }

Target:
Request build() { String apiUrl = this.apiUrl; StringBuilder url = new StringBuilder(apiUrl); if (apiUrl.endsWith("/")) { url.deleteCharAt(url.length() - 1); } url.append(relativeUrl); StringBuilder queryParams = this.queryParams; if (queryParams != null) { url.append(queryParams); } RequestBody body = this.body; if (body == null) { if (formEncodingBuilder != null) { body = formEncodingBuilder.build(); } else if (multipartBuilder != null) { body = multipartBuilder.build(); } } Headers.Builder headerBuilder = this.headers; if (contentTypeHeader != null) { if (body != null) { body = new MediaTypeOverridingRequestBody(body, contentTypeHeader); } else { if (headerBuilder == null) { headerBuilder = new Headers.Builder(); } headerBuilder.add("Content-Type", contentTypeHeader); } } Headers headers = headerBuilder != null ? headerBuilder.build() : NO_HEADERS; return new Request.Builder() .url(url.toString()) .method(requestMethod, body) .headers(headers) .build(); }
Source:
public void testConvertProfileGenericDataResponseDto() { final ProfileGenericDataResponseDto dto = this.makeProfileGenericDataResponseDto(); final ProfileGenericDataResponse result = this.mapper.map(dto, ProfileGenericDataResponse.class); Assert.assertTrue(result != null && result instanceof ProfileGenericDataResponse); }

Target:
public void testConvertProfileGenericDataResponseDto() { final ProfileGenericDataResponseDto dto = this.makeProfileGenericDataResponseDto(); final ProfileGenericDataResponse result = this.mapper.map(dto, ProfileGenericDataResponse.class); assertNotNull("mapping ProfileGenericDataResponse should not return null", result); assertThat("mapping ProfileGenericDataResponse should return correct type", result, instanceOf(ProfileGenericDataResponse.class)); }
Source:
public static GSSContext getGssContext(Subject subject, String servicePrincipal) { return Subject.doAs(subject, (PrivilegedAction<GSSContext>) () -> { GSSContext context = null; try { Principal subjectPrincipal = subject.getPrincipals().iterator().next(); GSSName gssUserName = gssManager.createName(subjectPrincipal.getName(), GSSName.NT_USER_NAME); GSSCredential clientCredential = gssManager.createCredential(gssUserName, GSSCredential.DEFAULT_LIFETIME, KERBEROS_OID, GSSCredential.INITIATE_ONLY); GSSName gssServiceName = gssManager.createName(servicePrincipal, null); context = gssManager.createContext(gssServiceName, SPNEGO_OID, clientCredential, GSSContext.INDEFINITE_LIFETIME); context.requestMutualAuth(true); context.requestConf(true); context.requestInteg(true); context.requestCredDeleg(false); return context; } catch (GSSException e) { throw Throwables.propagate(e); } }); }

Target:
public static GSSContext getGssContext(Subject subject, String servicePrincipal) { return Subject.doAs(subject, (PrivilegedAction<GSSContext>) () -> { try { Principal subjectPrincipal = subject.getPrincipals().iterator().next(); GSSName gssUserName = gssManager.createName(subjectPrincipal.getName(), GSSName.NT_USER_NAME); GSSCredential clientCredential = gssManager.createCredential(gssUserName, GSSCredential.DEFAULT_LIFETIME, KERBEROS_OID, GSSCredential.INITIATE_ONLY); GSSName gssServiceName = gssManager.createName(servicePrincipal, null); GSSContext context = null; context = gssManager.createContext(gssServiceName, SPNEGO_OID, clientCredential, GSSContext.INDEFINITE_LIFETIME); context.requestMutualAuth(true); context.requestConf(true); context.requestInteg(true); context.requestCredDeleg(false); return context; } catch (GSSException e) { throw Throwables.propagate(e); } }); }
Source:
protected AbstractFixedIntervalTask( String id, TaskResource taskResource, String dataSource, Interval interval ) { this(id, id, taskResource, dataSource, interval); }

Target:
protected AbstractFixedIntervalTask( String id, TaskResource taskResource, String dataSource, Interval interval ) { this( id, id, taskResource == null ? new TaskResource(id, 1) : taskResource, dataSource, interval ); }
Source:
private boolean detachUsers() { if (getVm().getVmPoolId() == null) { return false; } List<DbUser> users = getDbUserDao().getAllForVm(getVmId()); if (users == null || users.isEmpty()) { if (!templateVersionChanged) { runInternalActionWithTasksContext(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(getVmId()), getLock()); } return true; } if (VmPoolType.Automatic.equals(getVmPoolType())) { for (DbUser dbUser : users) { runInternalActionWithTasksContext(VdcActionType.DetachUserFromVmFromPool, new DetachUserFromVmFromPoolParameters(getVm().getVmPoolId(), dbUser.getId(), getVmId(), !templateVersionChanged), getLock()); } return true; } return false; }

Target:
private boolean detachUsers() { if (getVm().getVmPoolId() == null) { return false; } List<DbUser> users = getDbUserDao().getAllForVm(getVmId()); if (users == null || users.isEmpty()) { if (!templateVersionChanged) { runInternalActionWithTasksContext(VdcActionType.RestoreStatelessVm, new VmOperationParameterBase(getVmId()), getLock()); } return true; } if (getVmPoolType() == VmPoolType.Automatic) { for (DbUser dbUser : users) { runInternalActionWithTasksContext(VdcActionType.DetachUserFromVmFromPool, new DetachUserFromVmFromPoolParameters(getVm().getVmPoolId(), dbUser.getId(), getVmId(), !templateVersionChanged), getLock()); } return true; } return false; }
Source:
public void are_columns_created() { Job job1 = createJobAndBuild(); String jobDslScript = "listView('"+ LIST_VIEW_NAME +"') {\n" + " columns {\n" + " status()\n" + " weather()\n" + " name()\n" + " lastSuccess()\n" + " lastFailure()\n" + " lastDuration()\n" + " buildButton()\n" + " }\n" + " jobs{\n" + " name('"+job1.name+"')\n" + " }\n" + "}"; openNewlyCreatedListView(jobDslScript, LIST_VIEW_NAME); Assert.assertThat(driver, hasElement(By.xpath(" Assert.assertThat(driver, hasElement(By.xpath(" Assert.assertThat(driver, hasElement(By.xpath(" Assert.assertThat(driver, hasElement(By.xpath(" Assert.assertThat(driver, hasElement(By.xpath(" Assert.assertThat(driver, hasElement(By.xpath(" Assert.assertThat(driver, hasElement(By.xpath(" }

Target:
public void are_columns_created() { Job job1 = createJobAndBuild(); String jobDslScript = "listView('"+ LIST_VIEW_NAME +"') {\n" + " columns {\n" + " status()\n" + " weather()\n" + " name()\n" + " lastSuccess()\n" + " lastFailure()\n" + " lastDuration()\n" + " buildButton()\n" + " }\n" + " jobs{\n" + " name('"+job1.name+"')\n" + " }\n" + "}"; View view = openNewlyCreatedListView(jobDslScript, LIST_VIEW_NAME); assertThat(view, containsColumnHeaderTooltip("Status of the last build")); assertThat(view, containsColumnHeaderTooltip("Weather report showing aggregated status of recent builds")); assertThat(view, containsColumnHeader("Name")); assertThat(view, containsColumnHeader("Last Success")); assertThat(view, containsColumnHeader("Last Failure")); assertThat(view, containsColumnHeader("Last Duration")); assertThat(view, containsImage("clock.png")); }
Source:
public List<Hardware> listHardwareProfiles() { float disk = 20; List<Float> diskOptions = new ArrayList<Float>(); while (disk <= 2000) { diskOptions.add(disk); disk += 10; } List<Hardware> hardwares = Lists.newArrayList(); for (int core = 1; core <= 16; core++) { for (int ram : new int[]{1024, 2 * 1024, 4 * 1024, 8 * 1024, 10 * 1024, 16 * 1024, 24 * 1024, 28 * 1024, 32 * 1024, 64 * 1024, 128 * 1024}) { for (float size : diskOptions) { String id = String.format("cpu=%d,ram=%s,disk=%f", core, ram, size); hardwares.add(new HardwareBuilder() .ids(id) .ram(ram) .hypervisor("kvm") .name(id) .processor(new Processor(core, 1d)) .volume(new VolumeImpl(size, true, true)) .build()); } } } return hardwares; }

Target:
public List<HardwareFlavour> listHardwareProfiles() { return api.serverApi().listHardwareFlavours(); }
Source:
static String sha256(Path path) { try (InputStream in = Files.newInputStream(path)) { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] buffer = new byte[BUFFER_SIZE]; int read = 0; do { read = in.read(buffer); digest.update(buffer); } while (read > 0); return Util.toHexString(digest.digest()); } catch (NoSuchFileException e) { return null; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
static String sha256(Path path) { try (ByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ)) { MessageDigest digest = MessageDigest.getInstance("SHA-256"); if (channel instanceof FileChannel) { FileChannel fileChannel = (FileChannel) channel; MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); digest.update(byteBuffer); } else { ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE); while (channel.read(bb) != -1) { bb.flip(); digest.update(bb); bb.flip(); } } return Util.toHexString(digest.digest()); } catch (NoSuchFileException e) { return null; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private static boolean isValidTypeRefExpression(GoType goType) { if (goType instanceof GoParType) { goType = ((GoParType)goType).getType(); } if (goType instanceof GoPointerType) { goType = ((GoPointerType)goType).getType(); if (goType == null) return false; } GoTypeReferenceExpression refExpr = goType.getTypeReferenceExpression(); if (refExpr == null) return isValidType(goType); GoType baseType = GoPsiImplUtil.findBaseTypeFromRef(refExpr); if (!(baseType instanceof GoSpecType)) return false; goType = ((GoSpecType)baseType).getType(); return isValidType(goType); }

Target:
private static boolean isValidTypeRefExpression(GoType goType) { if (goType instanceof GoParType) { goType = ((GoParType)goType).getType(); } if (goType instanceof GoPointerType) { goType = ((GoPointerType)goType).getType(); if (goType == null) return false; } return isValidType(goType.getUnderlyingType()); }
Source:
public String getAppKey() { return thingIfApi.getAppKey(); }

Target:
public String getAppKey() { return this.thingIfApi.getAppKey(); }
Source:
public void canAcquireLockOnMultipleCellsOnSameRow(ConflictHandler conflictHandler) { Assume.assumeTrue(conflictHandler.lockCellsForConflicts()); PreCommitCondition canAcquireLockOnDifferentCell = (ignored) -> { LockResponse response = acquireCellLock("row1", "col2"); assertTrue(response.wasSuccessful()); }; Transaction transaction = startTransaction(canAcquireLockOnDifferentCell, conflictHandler); put(transaction, "row1", "col1", "100"); transaction.commit(); }

Target:
public void canAcquireLockOnMultipleCellsOnSameRow(ConflictHandler conflictHandler) { Assume.assumeTrue(conflictHandler.lockCellsForConflicts()); PreCommitCondition canAcquireLockOnDifferentCell = (ignored) -> { LockResponse response = acquireCellLock(ROW, OTHER_COLUMN); assertTrue(response.wasSuccessful()); }; commitWriteWith(canAcquireLockOnDifferentCell, conflictHandler); }
Source:
protected Supplier<String> internalGetAttribute(String attr) { Widget widget = getWidget(); switch(attr){ case "style": return () -> swtStyles; case "class": return () -> Objects.toString(getCSSClass(widget), ""); case "swt-data-class": return () -> { Object data = widget.getData(); if (data == null) { return ""; } StringBuilder sb = new StringBuilder(); for (Class<?> clazz = data.getClass(); clazz != Object.class; sb.append(' ')) { sb.append(clazz.getName()); clazz = clazz.getSuperclass(); } return sb.toString(); }; default: Object o = widget.getData(attr.toLowerCase()); if (o != null) { return () -> o.toString(); } } return null; }

Target:
protected Supplier<String> internalGetAttribute(String attr) { Widget widget = getWidget(); switch(attr){ case "style": return () -> swtStyles != null ? swtStyles : ""; case "class": return () -> Objects.toString(getCSSClass(widget), ""); case "swt-data-class": return () -> { Object data = widget.getData(); if (data == null) { return ""; } StringBuilder sb = new StringBuilder(); for (Class<?> clazz = data.getClass(); clazz != Object.class; sb.append(' ')) { sb.append(clazz.getName()); clazz = clazz.getSuperclass(); } return sb.toString(); }; default: Object o = widget.getData(attr.toLowerCase()); if (o != null) { return () -> o.toString(); } } return null; }
Source:
public Image deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject json = jsonElement.getAsJsonObject(); Map<String, Object> complexMetatdata = null; Map<String, String> metadata = null; JsonElement meta = json.get(METADATA); if (meta != null && meta.isJsonObject()) { metadata = Maps.newTreeMap(); complexMetatdata = Maps.newTreeMap(); for (Map.Entry<String, JsonElement> e : meta.getAsJsonObject().entrySet()) { Object value; if (e.getValue().isJsonArray()) { value = context.deserialize(e.getValue().getAsJsonArray(), ArrayList.class); } else if (e.getValue().isJsonObject()) { value = context.deserialize(e.getValue().getAsJsonArray(), TreeMap.class); } else if (e.getValue().isJsonPrimitive()) { value = e.getValue().getAsJsonPrimitive().getAsString(); } else { continue; } if (value instanceof String) { metadata.put(e.getKey(), (String) value); } complexMetatdata.put(e.getKey(), value); } json.remove(METADATA); } return apply(context.<ImageInternal>deserialize(json, ImageInternal.class), metadata, complexMetatdata); }

Target:
public Image deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject json = jsonElement.getAsJsonObject(); Map<String, String> metadata = null; List<BlockDeviceMapping> blockDeviceMapping = null; JsonElement meta = json.get(METADATA); if (meta != null && meta.isJsonObject()) { metadata = Maps.newTreeMap(); for (Map.Entry<String, JsonElement> e : meta.getAsJsonObject().entrySet()) { Object value; if (e.getValue().isJsonArray()) { value = context.deserialize(e.getValue().getAsJsonArray(), ArrayList.class); } else if (e.getValue().isJsonObject()) { value = context.deserialize(e.getValue().getAsJsonObject(), TreeMap.class); } else if (e.getValue().isJsonPrimitive()) { value = e.getValue().getAsJsonPrimitive().getAsString(); } else { continue; } if (value instanceof String) { metadata.put(e.getKey(), (String) value); } else if (value instanceof List && BLOCK_DEVICE_MAPPING.equals(e.getKey())) { blockDeviceMapping = context.deserialize(e.getValue(), new TypeToken<List<BlockDeviceMapping>>(){}.getType()); } } json.remove(METADATA); } return apply(context.<ImageInternal>deserialize(json, ImageInternal.class), metadata, blockDeviceMapping); }
Source:
private boolean setLabelWithFeatureValue(final DCell cell, final ColumnMapping columnMapping, final String featureName) { boolean init = false; String label = ""; try { final Object featureObject = accessor.eGet(cell.getTarget(), featureName); if (featureObject != null) { if (featureObject instanceof EList<?>) { List<String> texts = Lists.newArrayList(); for (Object obj : (EList<?>) featureObject) { if (obj instanceof String) { texts.add((String) obj); } else { texts.add(getText(obj)); } } label = texts.toString(); } else if (featureObject instanceof EObject) { label = getText(featureObject); } else { label = featureObject.toString(); } init = true; } else if (cell.getTarget().eClass().getEStructuralFeature(featureName) != null) { init = true; } if (init) { if (isDifferent(cell.getLabel(), label)) { cell.setLabel(label); } } } catch (final FeatureNotFoundException e) { RuntimeLoggerManager.INSTANCE.error(columnMapping, DescriptionPackage.eINSTANCE.getFeatureColumnMapping_FeatureName(), e); } return init; }

Target:
private boolean setLabelWithFeatureValue(final DCell cell, final ColumnMapping columnMapping, final String featureName) { boolean init = false; String label = ""; try { final Object featureObject = accessor.eGet(cell.getTarget(), featureName); if (featureObject != null) { if (featureObject instanceof EList<?>) { List<String> texts = Lists.newArrayList(); for (Object obj : (EList<?>) featureObject) { texts.add(getText(obj)); } label = texts.toString(); } else if (featureObject instanceof EObject) { label = getText(featureObject); } else { label = featureObject.toString(); } init = true; } else if (cell.getTarget().eClass().getEStructuralFeature(featureName) != null) { init = true; } if (init) { if (isDifferent(cell.getLabel(), label)) { cell.setLabel(label); } } } catch (final FeatureNotFoundException e) { RuntimeLoggerManager.INSTANCE.error(columnMapping, DescriptionPackage.eINSTANCE.getFeatureColumnMapping_FeatureName(), e); } return init; }
Source:
public void InteractiveMaps_030_PalantirSetPlayerCorrectPosition() { InteractiveMapPageObject selectedMap = new InteractiveMapPageObject(driver); selectedMap.openMap(wikiURL, 3); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = new PalantirContent(); handle = poi.setAndVerifyPlayerPosition(-40, -10, 3, true); poi.verifyCorrectPlayerPos(handle.success, handle.responseCode, handle.message); poi.verifyPoiAppearOnMap(); }

Target:
public void InteractiveMaps_030_PalantirSetPlayerCorrectPosition() { InteractiveMapsPageObject specialMap = new InteractiveMapsPageObject(driver); InteractiveMapPageObject selectedMap = specialMap.openMap(wikiURL, PalantirContent.PALANTIR_MAP); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = poi.setAndVerifyPlayerPosition(-40, -10, 3, true); poi.verifyCorrectPlayerPos(handle); poi.verifyPoiAppearOnMap(); }
Source:
protected byte[] getSampleBuffer() { final File file = new File(getFilename()); final int bufferSize = getBufferSize(); byte[] bytes = new byte[bufferSize]; FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); int startPosition = getStartPosition(); fileInputStream.skip(startPosition); int bytesRead = fileInputStream.read(bytes, 0, bufferSize); if (bytesRead != -1 && bytesRead <= bufferSize) { bytes = Arrays.copyOf(bytes, bytesRead); } return bytes; } catch (IOException e) { logger.error("IOException occurred while reading sample buffer", e); return new byte[0]; } finally { FileHelper.safeClose(fileInputStream); } }

Target:
protected byte[] getSampleBuffer() { final File file = new File(getFilename()); final int bufferSize = getBufferSize(); byte[] bytes = new byte[bufferSize]; try (final FileInputStream fileInputStream = new FileInputStream(file)) { int startPosition = getStartPosition(); fileInputStream.skip(startPosition); int bytesRead = fileInputStream.read(bytes, 0, bufferSize); if (bytesRead != -1 && bytesRead <= bufferSize) { bytes = Arrays.copyOf(bytes, bytesRead); } return bytes; } catch (IOException e) { logger.error("IOException occurred while reading sample buffer", e); return new byte[0]; } }
Source:
private void closeMainWindow(WindowEvent event) { if (applicationContext.getBean(GameService.class).isGameRunning()) { I18n i18n = applicationContext.getBean(I18n.class); NotificationService notificationService = applicationContext.getBean(NotificationService.class); notificationService.addNotification(new ImmediateNotification(i18n.get("exitWarning.title"), i18n.get("exitWarning.message"), Severity.WARN, asList( new Action(i18n.get("yes"), ev -> { Window window = (Window) event.getSource(); window.hide(); }), new Action(i18n.get("no"), ev -> { }) ))); event.consume(); } }

Target:
private void closeMainWindow(WindowEvent event) { if (applicationContext.getBean(GameService.class).isGameRunning()) { I18n i18n = applicationContext.getBean(I18n.class); NotificationService notificationService = applicationContext.getBean(NotificationService.class); notificationService.addNotification(new ImmediateNotification(i18n.get("exitWarning.title"), i18n.get("exitWarning.message"), Severity.WARN, asList( new Action(i18n.get("yes"), ev -> { Platform.exit(); }), new Action(i18n.get("no"), ev -> { }) ))); event.consume(); } }
Source:
public static Object convert(Schema.Type type, Object value) { Objects.requireNonNull(value, "'null' value is not allowed"); switch (type) { case BOOLEAN: if (value instanceof Boolean) { return value; } else if (value instanceof String) { return Boolean.valueOf((String) value); } break; case BYTE: case SHORT: case INTEGER: case LONG: case FLOAT: case DOUBLE: return convertNumber(type, value); case STRING: if (value instanceof String) { return value; } break; case BINARY: if (value instanceof byte[]) { return value; } break; case NESTED: if (value instanceof Map) { return value; } break; case ARRAY: if (value instanceof List) { return value; } break; } throw new IllegalArgumentException("Cannot convert value " + value + " with Java type class " + value.getClass() + " to type " + type); }

Target:
public static Object convert(Schema.Type type, Object value) { if (value == null) { return null; } switch (type) { case BOOLEAN: if (value instanceof Boolean) { return value; } else if (value instanceof String) { return Boolean.valueOf((String) value); } break; case BYTE: case SHORT: case INTEGER: case LONG: case FLOAT: case DOUBLE: return convertNumber(type, value); case STRING: if (value instanceof String) { return value; } break; case BINARY: if (value instanceof byte[]) { return value; } break; case NESTED: if (value instanceof Map) { return value; } break; case ARRAY: if (value instanceof List) { return value; } break; } throw new IllegalArgumentException("Cannot convert value " + value + " with Java type class " + value.getClass() + " to type " + type); }
Source:
private Constraint flightConflict(ConstraintFactory constraintFactory) { return constraintFactory.fromUniquePair(FlightAssignment.class) .filter((first, second) -> Objects.equals(first.getEmployee(), second.getEmployee())) .filter((first, second) -> second.getFlight().overlaps(first.getFlight())) .filter((first, second) -> second.getId() > first.getId()) .penalize("Flight conflict", HardSoftLongScore.ofHard(10)); }

Target:
private Constraint flightConflict(ConstraintFactory constraintFactory) { return constraintFactory.fromUniquePair(FlightAssignment.class, Joiners.equal(FlightAssignment::getEmployee)) .filter((first, second) -> second.getFlight().overlaps(first.getFlight())) .penalize("Flight conflict", HardSoftLongScore.ofHard(10)); }
Source:
private void generateGetMethod(Method method) { Parameter mainParameter = jaxrsGeneratorUtils.getMainUpdateParameter(method); if (mainParameter == null) { throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter"); } Service service = method.getDeclaringService(); boolean isRoot = service == service.getModel().getRoot(); javaBuffer.addImport(GET.class); javaBuffer.addLine("@GET"); if (isRoot) { javaBuffer.addImport(Response.class); addResponseReturnMethod("get()"); } else { Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImports(mainTypeReference.getImports()); generateDoGetMethod(mainParameter, mainTypeReference); generateDoc(method); javaBuffer.addLine(""); addMethod(mainTypeReference.getText(), "get()"); } javaBuffer.addLine(); }

Target:
private void generateGetMethod(Method method) { Parameter mainParameter = jaxrsGeneratorUtils.getMainUpdateParameter(method); if (mainParameter == null) { throw new IllegalStateException("Method \"" + method + "\" doesn't have any struct parameter"); } Service service = method.getDeclaringService(); boolean isRoot = service == service.getModel().getRoot(); javaBuffer.addImport(GET.class); javaBuffer.addLine("@GET"); if (isRoot) { javaBuffer.addImport(Response.class); addResponseReturnMethod("get()"); } else { Type mainType = mainParameter.getType(); JavaTypeReference mainTypeReference = schemaNames.getXjcTypeReference(mainType); javaBuffer.addImports(mainTypeReference.getImports()); generateDoGetMethod(mainParameter, mainTypeReference); generateDoc(method); javaBuffer.addLine(); addMethod(mainTypeReference.getText(), "get()"); } javaBuffer.addLine(); }
Source:
public static Map<String, List<String>> splitQuery(URI uri) { try { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); final String[] pairs = uri.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } catch (Exception e) { return Collections.emptyMap(); } }

Target:
public static Map<String, List<String>> splitQuery(URI uri) { try { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); final String[] pairs = uri.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } catch (Exception e) { LOGGER.warning("Unable to split query into key/value pairs for URI " + uri + ". " + e.getMessage()); return Collections.emptyMap(); } }
Source:
public int compareTo(Name o) { return normalizedName.compareTo(o.normalizedName); }

Target:
public int compareTo(Name o) { return normalisedName.compareTo(o.normalisedName); }
Source:
EntityDescriptor getEntityDescriptor() { if (!isMetadataValid()) { LOGGER.debug("SSO metadata is invalid. Purging metadata cache"); entityData.set(null); } EntityData ed = Optional.ofNullable(entityData.get()) .orElse( Optional.ofNullable(parseMetadata()) .map(this::extractRootEntityFromMap) .map(EntityData::new) .orElse(null)); if (isMetadataExpired()) { LOGGER.debug("SSO metadata cache is expired. Attempted to retrieve new metadata"); entityData.set(null); } boolean updated = entityData.compareAndSet(null, ed); if (!updated) { LOGGER.debug("Safe but concurrent update to serviceProviders map; using processed value"); } return entityData.get().getEntityDescriptor(); }

Target:
EntityDescriptor getEntityDescriptor() { EntityData previousEntityData = null; if (!isMetadataValid()) { LOGGER.debug("SSO metadata is invalid. Purging metadata cache"); entityData.set(null); } if (isMetadataExpired()) { LOGGER.debug("SSO metadata cache is expired. Attempt to retrieve new metadata"); previousEntityData = entityData.getAndSet(null); } EntityData newEntityData = null; if (entityData.get() == null) { newEntityData = Optional.ofNullable(parseMetadata()) .map(this::extractRootEntityFromMap) .map(EntityData::new) .orElse(previousEntityData); } boolean updated = entityData.compareAndSet(null, newEntityData); if (!updated) { LOGGER.trace("Safe but concurrent update to SAML entity; using processed value"); } final EntityData ed = entityData.get(); return ed == null ? null : ed.getEntityDescriptor(); }
Source:
private String getAbbreviatedName(Abbreviation text) { if (abbrvType == 0) { return text.getIsoAbbreviation(); } else if (abbrvType == 1) { return text.getMedlineAbbreviation(); } else if (abbrvType == 2) { return text.getShortestUnique(); } return null; }

Target:
private String getAbbreviatedName(Abbreviation text) { switch (abbreviationType) { case DEFAULT: return text.getAbbreviation(); case MEDLINE: return text.getMedlineAbbreviation(); case SHORTEST_UNIQUE: return text.getShortestUniqueAbbreviation(); default: throw new IllegalStateException(String.format("Unexpected value: %s", abbreviationType)); } }
Source:
private static <T> Object getFieldValue(T entity, String fieldPath, RequestScope requestScope) { Object val = entity; for (String field : fieldPath.split("\\.")) { if ("this".equals(field)) { continue; } if (val == null) { continue; } val = PersistentResource.getValue(val, field, requestScope); } return val; }

Target:
private static <T> Object getFieldValue(T entity, String fieldPath, RequestScope requestScope) { Object val = entity; for (String field : fieldPath.split("\\.")) { if ("this".equals(field)) { continue; } if (val == null) { break; } val = PersistentResource.getValue(val, field, requestScope); } return val; }
Source:
public static void main(String[] args) { MiniOptions options = new MiniOptions(); try { JCommander jcommand = new JCommander(options, args); if (options.help) { jcommand.usage(); System.exit(-1); } options.validateConfig(); ClusterUtil.verifyConfigFilesExist(options.getConfigDir(), "fluo.properties", "log4j-stdout.xml"); Log4jUtil.init("MiniAdmin", options.getConfigDir(), "STDOUT", false); } catch (Exception e) { System.err.println("Exception running MiniFluo: "+ e.getMessage()); e.printStackTrace(); } try { FluoConfiguration config = new FluoConfiguration(new File(options.getFluoProps())); switch (options.getCommand().toLowerCase()) { case "stop": File dataDir = new File(config.getMiniDataDir()); if (dataDir.exists() && config.getMiniStartAccumulo()) { FileUtils.deleteDirectory(dataDir); } break; default: log.error("Unknown command: " + options.getCommand()); break; } } catch (Exception e) { log.error("Exception running MiniAdmin: ", e); } }

Target:
public static void main(String[] args) { MiniOptions options = new MiniOptions(); try { JCommander jcommand = new JCommander(options, args); if (options.help) { jcommand.usage(); System.exit(-1); } options.validateConfig(); Log4jUtil.init("MiniAdmin", options.getConfigDir(), "STDOUT", false); } catch (Exception e) { System.err.println("Exception running MiniFluo: "+ e.getMessage()); e.printStackTrace(); } try { ClusterUtil.verifyConfigPathsExist(options.getFluoProps()); FluoConfiguration config = new FluoConfiguration(new File(options.getFluoProps())); switch (options.getCommand().toLowerCase()) { case "stop": File dataDir = new File(config.getMiniDataDir()); if (dataDir.exists() && config.getMiniStartAccumulo()) { FileUtils.deleteDirectory(dataDir); } break; default: log.error("Unknown command: " + options.getCommand()); break; } } catch (Exception e) { log.error("Exception running MiniAdmin: ", e); } }
Source:
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) { SessionFactoryImplementor sessionFactoryImplementor = factory; ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry(); Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class ); createSequences( sessionFactoryImplementor, provider ); createEntityConstraints( provider.getDataBase(), configuration ); initializeQueries( sessionFactoryImplementor, registry ); }

Target:
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) { SessionFactoryImplementor sessionFactoryImplementor = factory; ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry(); Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class ); createSequences( sessionFactoryImplementor, provider ); createEntityConstraints( provider.getDataBase(), configuration ); }
Source:
TimeOfDay currentTimeOfDay() { TimeOfDay[] values = TimeOfDay.values(); flag++; if (flag >= values.length) { flag = 0; } return values[flag]; }

Target:
TimeOfDay currentTimeOfDay() { Calendar calendar = Calendar.getInstance(); int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); return TimeOfDay.forHourOfDay(hourOfDay); }
Source:
private XmlRpcStruct[] getVmInfo(List<String> vmsToUpdate) { return (XmlRpcStruct[]) (new FullListVdsCommand<VdsIdAndVdsVDSCommandParametersBase>( new FullListVDSCommandParameters(_vds.getId(), vmsToUpdate)).ExecuteWithReturnValue()); }

Target:
private XmlRpcStruct[] getVmInfo(List<String> vmsToUpdate) { return (XmlRpcStruct[]) (new FullListVdsCommand<FullListVDSCommandParameters>( new FullListVDSCommandParameters(_vds.getId(), vmsToUpdate)).ExecuteWithReturnValue()); }
Source:
public void testImportOpenShift3AppViaServerAdapterSettings() { ServerSettingsWizard serverWizard = new ServerSettingsWizard().openFromOpenshiftView(service); ImportApplicationWizard importWizard = new ServerSettingsWizardPage().importProject(); importWizard.next(); importWizard.finish(); serverWizard.cancel(); assertProjectExistsInProjectView(OpenShiftResources.NODEJS_GIT_NAME); }

Target:
public void testImportOpenShift3AppViaServerAdapterSettings() { ServerSettingsWizard serverWizard = new ServerSettingsWizard().openFromOpenshiftView(service); ImportApplicationWizard importWizard = new ServerSettingsWizardPage().importProject(); importWizard.next(); importWizard.finish(); new DefaultShell(serverWizard.getTitle()); assertProjectNameFilled(); serverWizard.cancel(); assertProjectExistsInProjectView(OpenShiftResources.NODEJS_GIT_NAME); }
Source:
public StreamBlockQueue(String path, String nonce, String streamName, int partitionId, long genId) throws java.io.IOException { m_path = path; m_nonce = nonce; m_streamName = streamName; m_partitionId = partitionId; long initialGenId = genId; Table streamTable = VoltDB.instance().getCatalogContext().database.getTables().get(m_streamName); ExportRowSchema schema = ExportRowSchema.create(streamTable, m_partitionId, initialGenId, genId); ExportRowSchemaSerializer serializer = new ExportRowSchemaSerializer(); m_persistentDeque = PersistentBinaryDeque.builder(m_nonce, new VoltFile(m_path), exportLog) .initialExtraHeader(schema, serializer) .compression(!DISABLE_COMPRESSION).build(); m_reader = m_persistentDeque.openForRead(m_nonce); BinaryDequeReader.Entry<ExportRowSchema> entry = m_reader.pollHeader(); if (entry != null) { initialGenId = entry.getExtraHeader().initialGenerationId; schema = ExportRowSchema.create(streamTable, m_partitionId, initialGenId, genId); m_persistentDeque.updateExtraHeader(schema); } m_initialGenerationId = initialGenId; if (exportLog.isDebugEnabled()) { exportLog.debug(m_nonce + " At SBQ creation, PBD size is " + (m_reader.sizeInBytes() - (8 * m_reader.getNumObjects())) + " initial generation ID is " + m_initialGenerationId); } }

Target:
public StreamBlockQueue(String path, String nonce, String streamName, int partitionId, long genId) throws java.io.IOException { m_path = path; m_nonce = nonce; m_streamName = streamName; m_partitionId = partitionId; m_initialGenerationId = genId; constructPBD(genId); if (exportLog.isDebugEnabled()) { exportLog.debug(m_nonce + " At SBQ creation, PBD size is " + (m_reader.sizeInBytes() - (8 * m_reader.getNumObjects())) + " initial generation ID is " + m_initialGenerationId); } }
Source:
public void testProjectWithMapType() { String sqlQuery = "SELECT a, d['e']\n" + "FROM MyTable"; util().verifyPlan(sqlQuery); }

Target:
public void testProjectWithMapType() { String sqlQuery = "SELECT id, testMap['e']\n" + "FROM NestedTable"; util().verifyPlan(sqlQuery); }
Source:
public void tearDown() throws Exception { Activator.getDefault().getRepositoryCache().clear(); for (IProject project : createdProjects) { if (project.exists()) { project.delete(true, true, null); } } for (File pathToClean : pathsToClean) { if (pathToClean.exists()) { FileUtils.delete(pathToClean, FileUtils.RECURSIVE | FileUtils.RETRY); } } }

Target:
public void tearDown() throws Exception { Activator.getDefault().getRepositoryCache().clear(); for (IProject project : createdProjects) if (project.exists()) project.delete(true, true, null); for (File pathToClean : pathsToClean) if (pathToClean.exists()) FileUtils.delete(pathToClean, FileUtils.RECURSIVE | FileUtils.RETRY); }
Source:
private Long getHeaderValueLong(String headerName) throws Exception { String headerString = getHeaderValueString(headerName); try { return Long.parseLong(headerString); } catch (Exception e){ throw new SdkException("Error parsing " + headerName + " header"); } }

Target:
private long getHeaderValueLong(String headerName) throws Exception { String headerString = getHeaderValueString(headerName); try { return Long.parseLong(headerString); } catch (Exception e){ throw new SdkException("Error parsing " + headerName + " header"); } }
Source:
protected void setUp() throws Exception { super.setUp(); git = new Git(db); writeTrashFile("SomeFile.txt", "Hi there"); git.commit().setMessage("initial commit").call(); File sourceFile = new File(db.getWorkTree(), "Test.txt"); FileOutputStream fos = new FileOutputStream(sourceFile); fos.write("Hello world".getBytes("UTF-8")); fos.close(); git.add().addFilepattern("Test.txt").call(); initialCommit = git.commit().setMessage("Initial commit").call(); fos = new FileOutputStream(sourceFile); fos.write("Some change".getBytes("UTF-8")); fos.close(); git.add().addFilepattern("Test.txt").call(); secondCommit = git.commit().setMessage("Second commit").call(); RefUpdate rup = db.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.setForceUpdate(true); rup.update(); }

Target:
protected void setUp() throws Exception { super.setUp(); git = new Git(db); git.commit().setMessage("initial commit").call(); writeTrashFile("Test.txt", "Hello world"); git.add().addFilepattern("Test.txt").call(); initialCommit = git.commit().setMessage("Initial commit").call(); writeTrashFile("Test.txt", "Some change"); git.add().addFilepattern("Test.txt").call(); secondCommit = git.commit().setMessage("Second commit").call(); RefUpdate rup = db.updateRef("refs/heads/master"); rup.setNewObjectId(initialCommit.getId()); rup.setForceUpdate(true); rup.update(); }
Source:
public void setBoolean(StudyIdentifier studyIdentifier, String healthCode, ParticipantOption option, boolean value) { checkNotNull(studyIdentifier); checkArgument(isNotBlank(healthCode)); checkNotNull(option == ParticipantOption.EMAIL_NOTIFICATIONS); AccountId accountId = AccountId.forHealthCode(studyIdentifier.getIdentifier(), healthCode); Account account = accountDao.getAccount(accountId); if (account != null) { account.setNotifyByEmail(value); accountDao.updateAccount(account, false); } }

Target:
public void setBoolean(StudyIdentifier studyIdentifier, String healthCode, ParticipantOption option, boolean value) { checkNotNull(studyIdentifier); checkArgument(isNotBlank(healthCode)); checkArgument(option == ParticipantOption.EMAIL_NOTIFICATIONS); AccountId accountId = AccountId.forHealthCode(studyIdentifier.getIdentifier(), healthCode); Account account = accountDao.getAccount(accountId); if (account == null) { throw new EntityNotFoundException(Account.class, "Account not found"); } account.setNotifyByEmail(value); accountDao.updateAccount(account, false); }
Source:
public static Configuration getHBaseConfiguration() { Configuration result = new HBaseConfiguration().create(); boolean foundHBaseConfiguration = false; String possibleHBaseConfPath = null; final String hbaseHome = System.getenv("HBASE_HOME"); if (hbaseHome != null) { LOG.debug("Searching HBase configuration files in HBASE_HOME: {}", hbaseHome); possibleHBaseConfPath = hbaseHome + "/conf"; } if (possibleHBaseConfPath != null) { foundHBaseConfiguration = addHBaseConfIfFound(result, possibleHBaseConfPath); } String hbaseConfDir = System.getenv("HBASE_CONF_DIR"); if (hbaseConfDir != null) { LOG.debug("Searching HBase configuration files in HBASE_CONF_DIR: {}", hbaseConfDir); foundHBaseConfiguration = addHBaseConfIfFound(result, hbaseConfDir) || foundHBaseConfiguration; } if (!foundHBaseConfiguration) { LOG.warn("Could not find HBase configuration via any of the supported methods " + "(Flink configuration, environment variables)."); } return result; }

Target:
public static Configuration getHBaseConfiguration() { Configuration result = HBaseConfiguration.create(); boolean foundHBaseConfiguration = false; String possibleHBaseConfPath = null; final String hbaseHome = System.getenv("HBASE_HOME"); if (hbaseHome != null) { LOG.debug("Searching HBase configuration files in HBASE_HOME: {}", hbaseHome); possibleHBaseConfPath = hbaseHome + "/conf"; } if (possibleHBaseConfPath != null) { foundHBaseConfiguration = addHBaseConfIfFound(result, possibleHBaseConfPath); } String hbaseConfDir = System.getenv("HBASE_CONF_DIR"); if (hbaseConfDir != null) { LOG.debug("Searching HBase configuration files in HBASE_CONF_DIR: {}", hbaseConfDir); foundHBaseConfiguration = addHBaseConfIfFound(result, hbaseConfDir) || foundHBaseConfiguration; } if (!foundHBaseConfiguration) { LOG.warn("Could not find HBase configuration via any of the supported methods " + "(Flink configuration, environment variables)."); } return result; }
Source:
private void doSuspend(IExecutionDMContext context, final RequestMonitor rm) { final MonitorSuspendJob monitorJob = new MonitorSuspendJob(0, rm); fCommandControl.queueCommand(fCommandFactory.createMIExecInterrupt(context), new ImmediateDataRequestMonitor<MIInfo>() { @Override protected void handleSuccess() { } @Override protected void handleFailure() { monitorJob.cleanAndCancel(); rm.done(getStatus()); } }); }

Target:
private void doSuspend(IExecutionDMContext context, final RequestMonitor rm) { if (fGDBBackEnd.isFullGdbConsoleSupported()) { final MonitorSuspendJob monitorJob = new MonitorSuspendJob(0, rm); fCommandControl.queueCommand(fCommandFactory.createMIExecInterrupt(context), new ImmediateDataRequestMonitor<MIInfo>() { @Override protected void handleSuccess() { } @Override protected void handleFailure() { monitorJob.cleanAndCancel(); rm.done(getStatus()); } }); } else { super.suspend(context, rm); } }
Source:
public Collection<CommentedFile> getFileComments(AbstractBuild build) { if (thisOverrides("getFileComments", Run.class)) { return getFileComments((Run)build); } return null; }

Target:
public Collection<CommentedFile> getFileComments(AbstractBuild build) { if (thisOverrides("getFileComments", Run.class)) { return getFileComments((Run)build); } return Collections.emptyList(); }
Source:
public void expressionsAreConcurrentHashMap() { assertTrue("Expressions should be concurrent to allow startup", getField(source, "channels") instanceof ConcurrentHashMap); assertTrue("Expressions should be concurrent to allow startup", getField(source, "payloadExpressions") instanceof ConcurrentHashMap); assertTrue("Expressions should be concurrent to allow startup", getField(source, "headersExpressions") instanceof ConcurrentHashMap); }

Target:
public void expressionsAreConcurrentHashMap() { assertThat("Expressions should be concurrent to allow startup", ReflectionTestUtils.getField(source, "channels"), instanceOf(ConcurrentHashMap.class)); assertThat("Expressions should be concurrent to allow startup", ReflectionTestUtils.getField(source, "payloadExpressions"), instanceOf(ConcurrentHashMap.class)); assertThat("Expressions should be concurrent to allow startup", ReflectionTestUtils.getField(source, "headersExpressions"), instanceOf(ConcurrentHashMap.class)); }
Source:
public GrillClientResultSet getResults(String sql) { GrillStatement statement = new GrillStatement(conn); LOG.debug("Executing query " + sql); statement.execute(sql, true); if(statement.getStatus().getStatus() != QueryStatus.Status.SUCCESSFUL) { throw new IllegalStateException(statement.getStatus().getErrorMessage()); } return new GrillClientResultSet(statement.getResultSet(), statement.getResultSetMetaData()); }

Target:
public GrillClientResultSet getResults(String sql) { GrillStatement statement = new GrillStatement(conn); LOG.debug("Executing query " + sql); statement.execute(sql, true); if(statement.getStatus().getStatus() == QueryStatus.Status.FAILED) { throw new IllegalStateException(statement.getStatus().getErrorMessage()); } return new GrillClientResultSet(statement.getResultSet(), statement.getResultSetMetaData()); }
Source:
private ValidationResult validateStatus(VDSStatus hostStatus) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.createSetVariableString("hostStatus", host.getStatus().name())) .unless(hostStatus == host.getStatus()); }

Target:
private ValidationResult validateStatus(VDSStatus hostStatus) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL, ReplacementUtils.createSetVariableString("hostStatus", hostStatus.name())) .unless(hostStatus == host.getStatus()); }
Source:
public IllegalIdentifierNameCheck() { super("(?i)^(?!(record|yield|var|_)$).+$"); }

Target:
public IllegalIdentifierNameCheck() { super("(?i)^(?!(record|yield|var|permits|sealed|_)$).+$"); }
Source:
private CompletionStage<RestResponse> runTask(RestRequest request) { String taskName = request.variables().get("taskName"); EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); TaskManager taskManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(TaskManager.class); TaskContext taskContext = new TaskContext(); request.parameters().forEach((k, v) -> { if (k.startsWith("param.")) { taskContext.addParameter(k.substring(6), v.get(0)); } }); return taskManager.runTask(taskName, taskContext).thenApply(result -> { NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); try { if (result instanceof byte[]) { builder.contentType(TEXT_PLAIN_TYPE).entity(result); } else { byte[] resultBytes = invocationHelper.getMapper().writeValueAsBytes(result); builder.contentType(APPLICATION_JSON_TYPE).entity(resultBytes); } } catch (JsonProcessingException e) { builder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return builder.build(); }); }

Target:
private CompletionStage<RestResponse> runTask(RestRequest request) { String taskName = request.variables().get("taskName"); EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); TaskManager taskManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(TaskManager.class); TaskContext taskContext = new TaskContext(); request.parameters().forEach((k, v) -> { if (k.startsWith("param.")) { taskContext.addParameter(k.substring(6), v.get(0)); } }); return taskManager.runTask(taskName, taskContext).thenApply(result -> { NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); try { if (result instanceof byte[]) { builder.contentType(TEXT_PLAIN_TYPE).entity(result); } else { byte[] resultBytes = invocationHelper.getMapper().writeValueAsBytes(result); builder.contentType(APPLICATION_JSON_TYPE).entity(resultBytes); } } catch (JsonProcessingException e) { builder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR).entity(e.getMessage()); } return builder.build(); }); }