auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void doSerialization(Element field, TemplateInput param) throws TemplateInputBadFormat { field.addAttribute("name", param.getName()); InputType type = param.getType(); if (type == null) { if (param.getStringValue() == null) { log.warn(param.getName() + " is null"); throw new TemplateInputBadFormat(); } else type = StringValue; } field.addAttribute("type", type.getValue()); if (param.isReadOnly()) field.addAttribute("readonly", "true"); if (param.isAutoLoop()) field.addAttribute("autoloop", "true"); if (param.getDesciption() != null) field.setText(param.getDesciption()); switch (type) { case StringValue: field.addAttribute("value", param.getStringValue()); break; case DateValue: SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); field.addAttribute("value", dateFormat.format(param.getDateValue())); break; case BooleanValue: field.addAttribute("value", param.getBooleanValue().toString()); break; case MapValue: case ListValue: Map<String, TemplateInput> map = param.getMapValue(); for (String childParamName : map.keySet()) { TemplateInput childParam = map.get(childParamName); if (childParamName.equals(childParam.getName())) { log.warn("Child param in map and child param name doesn't match, get child param name as key: " + childParam.toString()); } Element subfield = field.addElement(fieldTag); doSerialization(subfield, childParam); } break; case DocumentProperty: case PictureProperty: case Content: field.addAttribute("source", param.getSource()); break; } }

Target:
protected void doSerialization(Element field, TemplateInput param) throws TemplateInputBadFormat { field.addAttribute("name", param.getName()); InputType type = param.getType(); if (type == null) { if (param.getStringValue() == null) { log.warn(param.getName() + " is null"); throw new TemplateInputBadFormat(); } else type = StringValue; } field.addAttribute("type", type.getValue()); if (param.isReadOnly()) { field.addAttribute("readonly", "true"); } if (param.isAutoLoop()) { field.addAttribute("autoloop", "true"); } if (param.getDesciption() != null) { field.setText(param.getDesciption()); } switch (type) { case StringValue: field.addAttribute("value", param.getStringValue()); break; case DateValue: SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); field.addAttribute("value", dateFormat.format(param.getDateValue())); break; case BooleanValue: field.addAttribute("value", param.getBooleanValue().toString()); break; case MapValue: case ListValue: Map<String, TemplateInput> map = param.getMapValue(); for (String childParamName : map.keySet()) { TemplateInput childParam = map.get(childParamName); if (MapValue.equals(type) && childParamName.equals(childParam.getName())) { log.warn("Child param in map and child param name doesn't match, get child param name as key: " + childParam.toString()); } Element subfield = field.addElement(fieldTag); doSerialization(subfield, childParam); } break; case DocumentProperty: case PictureProperty: case Content: field.addAttribute("source", param.getSource()); break; } }
Source:
private LocalTxQueueTransactionContext createLocalTxContext(LocalTxQueueTransactionJournal txLog, QueueProvider provider) throws InterruptedException { Lock lock = mock(Lock.class); when(lock.tryLock(anyLong(), eq(TimeUnit.MILLISECONDS))).thenAnswer((Answer<Boolean>) invocationOnMock -> { sleep(invocationOnMock.getArgument(0, Long.class) / 2); return true; }); return new LocalTxQueueTransactionContext(txLog, provider, lock); }

Target:
private LocalTxQueueTransactionContext createLocalTxContext(LocalTxQueueTransactionJournal txLog, QueueProvider provider) throws InterruptedException { Lock lock = mock(Lock.class); when(lock.tryLock(anyLong(), eq(MILLISECONDS))).thenAnswer((Answer<Boolean>) invocationOnMock -> { sleep(invocationOnMock.getArgument(0, Long.class) / 2); return true; }); return new LocalTxQueueTransactionContext(txLog, provider, lock); }
Source:
public RestRequest createRestService(WsdlProject project, String URI) throws MalformedURLException { return createRestService(project, URI, true); }

Target:
public void createRestService(WsdlProject project, String URI) throws MalformedURLException { if (StringUtils.isNullOrEmpty(URI)) { return; } RestResource restResource = createResource(ModelCreationStrategy.CREATE_NEW_MODEL, project, URI); RestRequest restRequest = addNewRequest(addNewMethod(ModelCreationStrategy.CREATE_NEW_MODEL, restResource, RestRequestInterface.HttpMethod.GET)); copyParameters(extractParams(URI), restResource.getParams()); UISupport.select(restRequest); UISupport.showDesktopPanel(restRequest); }
Source:
public void testSize() { final int max_size = CircularBuffer.MAX_SIZE; for (int size = 0; size < max_size; size <<= 1) { testSize(size); testSize(1 + size); if (0 == size) size = 1; } }

Target:
public void testSize() { testSize(0); testSize(1); testSize(2); final int max_size = MAX_SIZE >> 3; for (int size = 4; size < max_size; size <<= 1) { testSize(size - 1); testSize(size); testSize(size + 1); } }
Source:
public void testBroadcast() throws Exception { assumeTrue(!isMainRun()); Topology topology = newTopology(); TStream<String> strings = topology.strings("1", "7", "19", "23", "57"); TStream<String> stringsP = strings.parallel(()->3, Routing.BROADCAST); TStream<ChannelAndSequence> withChannel = stringsP.map(stringTupleChannelSeqTransformer()); withChannel = withChannel.asType(ChannelAndSequence.class).endParallel(); TStream<String> result = StringStreams.toString(withChannel); Tester tester = topology.getTester(); Condition<Long> fifeteenTuples = tester.tupleCount(result, 15); Condition<List<String>> contents = tester.stringContentsUnordered(result, "CS:0:1", "CS:0:7", "CS:0:19", "CS:0:23", "CS:0:57", "CS:1:1", "CS:1:7", "CS:1:19", "CS:1:23", "CS:1:57", "CS:2:1", "CS:2:7", "CS:2:19", "CS:2:23", "CS:2:57"); this.getConfig().put(ContextProperties.KEEP_ARTIFACTS, true); complete(tester, allConditions(fifeteenTuples, contents), 10, TimeUnit.SECONDS); assertTrue("broadcast count: ", fifeteenTuples.valid()); assertTrue("broadcast contents: ", contents.valid()); }

Target:
public void testBroadcast() throws Exception { checkUdpSupported(); Topology topology = newTopology(); TStream<String> strings = topology.strings("1", "7", "19", "23", "57"); TStream<String> stringsP = strings.parallel(()->3, Routing.BROADCAST); TStream<ChannelAndSequence> withChannel = stringsP.map(stringTupleChannelSeqTransformer()); withChannel = withChannel.asType(ChannelAndSequence.class).endParallel(); TStream<String> result = StringStreams.toString(withChannel); Tester tester = topology.getTester(); Condition<Long> fifeteenTuples = tester.tupleCount(result, 15); Condition<List<String>> contents = tester.stringContentsUnordered(result, "CS:0:1", "CS:0:7", "CS:0:19", "CS:0:23", "CS:0:57", "CS:1:1", "CS:1:7", "CS:1:19", "CS:1:23", "CS:1:57", "CS:2:1", "CS:2:7", "CS:2:19", "CS:2:23", "CS:2:57"); this.getConfig().put(ContextProperties.KEEP_ARTIFACTS, true); complete(tester, allConditions(fifeteenTuples, contents), 10, TimeUnit.SECONDS); assertTrue("broadcast count: ", fifeteenTuples.valid()); assertTrue("broadcast contents: ", contents.valid()); }
Source:
protected Account(long containerCount, long objectCount, long bytesUsed, Map<String, String> metadata, Multimap<String, String> headers) { this.containerCount = containerCount; this.objectCount = objectCount; this.bytesUsed = bytesUsed; this.metadata = metadata == null ? ImmutableMap.<String, String> of() : checkNotNull(metadata, "metadata"); this.headers = headers == null ? ImmutableMultimap.<String, String> of() : checkNotNull(headers, "headers"); }

Target:
protected Account(long containerCount, long objectCount, long bytesUsed, Map<String, String> metadata, Multimap<String, String> headers) { this.containerCount = containerCount; this.objectCount = objectCount; this.bytesUsed = bytesUsed; this.metadata = metadata == null ? ImmutableMap.<String, String> of() : metadata; this.headers = headers == null ? ImmutableMultimap.<String, String> of() : headers; }
Source:
public Object getAdapter(Class adapter) { if (adapter == IFile.class || adapter == IResource.class) { final IFile[] file = new IFile[1]; Display.getDefault().syncExec(new Runnable() { public void run() { Object selectedEdition = getSelectedEdition(); if (selectedEdition instanceof DiffNode) { DiffNode diffNode = (DiffNode) selectedEdition; ITypedElement element = diffNode.getLeft(); if (element instanceof ResourceEditableRevision) { ResourceEditableRevision resourceRevision = (ResourceEditableRevision) element; file[0] = resourceRevision.getFile(); } } } }); if (file[0] != null) { return file[0]; } } return super.getAdapter(adapter); }

Target:
public Object getAdapter(Class adapter) { if ((adapter == IFile.class || adapter == IResource.class) && isUIThread()) { Object selectedEdition = getSelectedEdition(); if (selectedEdition instanceof DiffNode) { DiffNode diffNode = (DiffNode) selectedEdition; ITypedElement element = diffNode.getLeft(); if (element instanceof ResourceEditableRevision) { ResourceEditableRevision resourceRevision = (ResourceEditableRevision) element; return resourceRevision.getFile(); } } } return super.getAdapter(adapter); }
Source:
public void asLocal() { assertCurlOrPowershellv3Plus(); File tmpDir = new File(System.getProperty("java.io.tmpdir")); File jar = new File(tmpDir, "slave"+createRandomName()+".jar"); String command; if (SystemUtils.IS_OS_UNIX) { String java = "java"; String jh = System.getProperty("java.home"); if (!StringUtils.isEmpty(jh)) { java = new File(jh, "bin/java").getAbsolutePath(); } command = String.format( "sh -c 'curl -s -o %1$s %2$sjnlpJars/slave.jar && \"%3$s\" -jar %1$s'", jar, url("../../"), java ); } else { command = String.format("powershell -command \"& { " + "try { " + "Invoke-WebRequest %2$sjnlpJars/slave.jar -OutFile %1$s " + "} catch { " + "echo 'download of slave jar failed'; " + "exit 2 "+ "} " + "java -jar %1$s "+ "}\"", jar, url("../../") ); } setLauncher(CommandSlaveLauncher.class).command(command); }

Target:
public void asLocal() { assertCurlOrPowershellv3Plus(); File tmpDir = new File(System.getProperty("java.io.tmpdir")); File jar = new File(tmpDir, "slave"+createRandomName()+".jar"); String command; if (SystemUtils.IS_OS_UNIX) { command = String.format( "sh -c 'curl -s -o %1$s %2$sjnlpJars/slave.jar && java -jar %1$s'", jar, url("../../") ); } else { command = String.format("powershell -command \"& { " + "try { " + "Invoke-WebRequest %2$sjnlpJars/slave.jar -OutFile %1$s " + "} catch { " + "echo 'download of slave jar failed'; " + "exit 2 "+ "} " + "java -jar %1$s "+ "}\"", jar, url("../../") ); } setLauncher(CommandSlaveLauncher.class).command(command); }
Source:
public void testExecuteBatchPreparedStatementFailBulkTypes() throws Exception { try (Connection conn = DriverManager.getConnection(connectionStr)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id, string_field) values (?, ?)"); stmt.setInt(1, 2); stmt.setString(2, "foo"); stmt.addBatch(); stmt.setInt(1, 3); stmt.setString(2, "bar"); stmt.addBatch(); stmt.setInt(1, 1); stmt.setObject(2, newHashMap()); stmt.addBatch(); try { stmt.executeBatch(); fail("BatchUpdateException not thrown"); } catch (BatchUpdateException e) { assertThat( e.getMessage(), containsString("Validation failed for string_field: cannot be cast to type string") ); assertArrayEquals( new int[]{Statement.EXECUTE_FAILED, Statement.EXECUTE_FAILED, Statement.EXECUTE_FAILED}, e.getUpdateCounts() ); } conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(1L)); } }

Target:
public void testExecuteBatchPreparedStatementFailBulkTypes() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id) values (?)"); stmt.setObject(1, newHashMap()); stmt.addBatch(); try { stmt.executeBatch(); fail("BatchUpdateException not thrown"); } catch (BatchUpdateException e) { assertThat( e.getMessage(), containsString("Validation failed for id: cannot be cast to type integer") ); assertArrayEquals(new int[]{Statement.EXECUTE_FAILED}, e.getUpdateCounts()); } conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(0L)); } }
Source:
private static byte[] fromHexString(final String encoded) { final byte result[] = new byte[encoded.length()/2]; final char enc[] = encoded.toCharArray(); for (int i = 0; i < enc.length; i += 2) { StringBuilder curr = new StringBuilder(2); curr.append(enc[i]).append(enc[i + 1]); result[i/2] = (byte) Integer.parseInt(curr.toString(), 16); } return result; }

Target:
private static byte[] fromHexString(final String encoded) { final byte result[] = new byte[encoded.length()/2]; String hexPair; for (int i = 0; i < encoded.length(); i += 2) { hexPair = encoded.substring(i, i + 2); result[i/2] = (byte) Integer.parseInt(hexPair, 16); } return result; }
Source:
private void registerService(Class<?> api, Object service, boolean saveInContext) { if (api == null) { throw new NullPointerException("The service key cannot be null"); } if (!api.isInstance(service)) { throw new IllegalArgumentException( "The service does not implement the given interface"); } if (isDisposed()) { IllegalStateException ex = new IllegalStateException("An attempt was made to register service " + service + " with implementation class " + api + " on a disposed service locator"); WorkbenchPlugin.log(StatusUtil.newStatus(IStatus.ERROR, ex.getMessage(), ex)); } if (service instanceof INestable && activated) { ((INestable) service).activate(); } services.put(api, service); if (saveInContext) { IEclipseContext context = e4Context; if (context == null) { return; } context.set(api.getName(), service); } }

Target:
private void registerService(Class<?> api, Object service, boolean saveInContext) { if (api == null) { throw new NullPointerException("The service key cannot be null"); } if (!api.isInstance(service)) { throw new IllegalArgumentException( "The service does not implement the given interface"); } if (isDisposed()) { IllegalStateException ex = new IllegalStateException("An attempt was made to register service " + service + " with implementation class " + api + " on a disposed service locator"); WorkbenchPlugin.log(StatusUtil.newStatus(IStatus.ERROR, ex.getMessage(), ex)); return; } if (service instanceof INestable && activated) { ((INestable) service).activate(); } services.put(api, service); if (saveInContext) { IEclipseContext context = e4Context; if (context == null) { return; } context.set(api.getName(), service); } }
Source:
public void testVisitAnyRequestFirst() { VisitedResourceRequestTracker tracker = new VisitedResourceRequestTracker(nodeTracker); Assert.assertTrue(tracker.visit(anyRequest)); Assert.assertFalse(tracker.visit(rackRequest)); Assert.assertFalse(tracker.visit(node1Request)); Assert.assertFalse(tracker.visit(node2Request)); }

Target:
public void testVisitAnyRequestFirst() { VisitedResourceRequestTracker tracker = new VisitedResourceRequestTracker(nodeTracker); assertTrue(FIRST_CALL_FAILURE, tracker.visit(anyRequest)); assertFalse(ANY_VISITED + RACK_FAILURE, tracker.visit(rackRequest)); assertFalse(ANY_VISITED + NODE_FAILURE, tracker.visit(node1Request)); assertFalse(ANY_VISITED + NODE_FAILURE, tracker.visit(node2Request)); }
Source:
public UserExtSource updateUserExtSource(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException, UserExtSourceNotExistsException, PrivilegeException { Utils.checkPerunSession(sess); if(!AuthzResolver.isAuthorized(sess, Role.REGISTRAR)) { throw new PrivilegeException(sess, "updateUserExtSource"); } if (getUsersManagerBl().checkUserExtSourceExistsById(sess, userExtSource.getId())) { return getUsersManagerBl().updateUserExtSource(sess, userExtSource); } else { throw new UserExtSourceNotExistsException("UserExtSource: " + userExtSource); } }

Target:
public UserExtSource updateUserExtSource(PerunSession sess, UserExtSource userExtSource) throws InternalErrorException, UserExtSourceNotExistsException, UserExtSourceExistsException, PrivilegeException { Utils.checkPerunSession(sess); if(!AuthzResolver.isAuthorized(sess, Role.REGISTRAR)) { throw new PrivilegeException(sess, "updateUserExtSource"); } getUsersManagerBl().checkUserExtSourceExistsById(sess, userExtSource.getId()); try { getUsersManagerBl().checkUserExtSourceExists(sess, userExtSource); } catch (UserExtSourceNotExistsException ex) { } return getUsersManagerBl().updateUserExtSource(sess, userExtSource); }
Source:
private NodeMetrics(final StreamsMetricsImpl metrics, final String processorNodeName, final ProcessorContext context) { this.metrics = metrics; final String taskName = context.taskId().toString(); final Map<String, String> tagMap = metrics.nodeLevelTagMap(context.taskId().toString(), processorNodeName); final Map<String, String> allTagMap = metrics.taskLevelTagMap(context.taskId().toString(), PROCESSOR_NODE_ID_TAG, ROLLUP_VALUE); nodeProcessTimeSensor = createTaskAndNodeLatencyAndThroughputSensors( "process", metrics, taskName, processorNodeName, allTagMap, tagMap ); nodePunctuateTimeSensor = createTaskAndNodeLatencyAndThroughputSensors( "punctuate", metrics, taskName, processorNodeName, allTagMap, tagMap ); nodeCreationSensor = createTaskAndNodeLatencyAndThroughputSensors( "create", metrics, taskName, processorNodeName, allTagMap, tagMap ); nodeDestructionSensor = createTaskAndNodeLatencyAndThroughputSensors( "destroy", metrics, taskName, processorNodeName, allTagMap, tagMap ); sourceNodeForwardSensor = createTaskAndNodeLatencyAndThroughputSensors( "forward", metrics, taskName, processorNodeName, allTagMap, tagMap ); this.taskName = taskName; this.processorNodeName = processorNodeName; }

Target:
private NodeMetrics(final StreamsMetricsImpl metrics, final String processorNodeName, final ProcessorContext context) { this.metrics = metrics; final String threadId = Thread.currentThread().getName(); final String taskName = context.taskId().toString(); final Map<String, String> tagMap = metrics.nodeLevelTagMap(threadId, context.taskId().toString(), processorNodeName); final Map<String, String> allTagMap = metrics.nodeLevelTagMap(threadId, context.taskId().toString(), ROLLUP_VALUE); nodeProcessTimeSensor = createTaskAndNodeLatencyAndThroughputSensors( "process", metrics, threadId, taskName, processorNodeName, allTagMap, tagMap ); nodePunctuateTimeSensor = createTaskAndNodeLatencyAndThroughputSensors( "punctuate", metrics, threadId, taskName, processorNodeName, allTagMap, tagMap ); nodeCreationSensor = createTaskAndNodeLatencyAndThroughputSensors( "create", metrics, threadId, taskName, processorNodeName, allTagMap, tagMap ); nodeDestructionSensor = createTaskAndNodeLatencyAndThroughputSensors( "destroy", metrics, threadId, taskName, processorNodeName, allTagMap, tagMap ); sourceNodeForwardSensor = createTaskAndNodeLatencyAndThroughputSensors( "forward", metrics, threadId, taskName, processorNodeName, allTagMap, tagMap ); this.taskName = taskName; this.processorNodeName = processorNodeName; }
Source:
public String getUrl(int requestId, CheckerInfo checkerInfo) { return String.format(URL_TICKER, checkerInfo.getCurrencyBaseLowerCase()); }

Target:
public String getUrl(int requestId, CheckerInfo checkerInfo) { return String.format(URL, checkerInfo.getCurrencyBaseLowerCase()); }
Source:
private void setUserPreferences() { GUIPreferences guiPreferences = GUIPreferences.getInstance(); setSize(guiPreferences.getMechSelectorSizeWidth(), guiPreferences.getMechSelectorSizeHeight()); comboUnitType.setSelectedIndex(guiPreferences.getMechSelectorUnitType()); comboWeight.setSelectedIndex(guiPreferences.getMechSelectorWeightClass()); updateTypeCombo(guiPreferences.getMechSelectorRulesLevels().replaceAll("\\[", "")); List<SortKey> sortList = new ArrayList<>(); try { sortList.add(new SortKey(guiPreferences.getMechSelectorSortColumn(), SortOrder.valueOf(guiPreferences.getMechSelectorSortOrder()))); } catch (Exception e) { logger.error(getClass(), "setUserPreferences", "Failed to set based on user preferences, attempting to use default", e); sortList.add(new SortKey(guiPreferences.getMechSelectorDefaultSortColumn(), SortOrder.valueOf(guiPreferences.getMechSelectorDefaultSortOrder()))); } tableUnits.getRowSorter().setSortKeys(sortList); ((DefaultRowSorter<?, ?>) tableUnits.getRowSorter()).sort(); tableUnits.invalidate(); pack(); }

Target:
private void setUserPreferences() { GUIPreferences guiPreferences = GUIPreferences.getInstance(); setSize(guiPreferences.getMechSelectorSizeWidth(), guiPreferences.getMechSelectorSizeHeight()); comboUnitType.setSelectedIndex(guiPreferences.getMechSelectorUnitType()); comboWeight.setSelectedIndex(guiPreferences.getMechSelectorWeightClass()); updateTypeCombo(guiPreferences); List<SortKey> sortList = new ArrayList<>(); try { sortList.add(new SortKey(guiPreferences.getMechSelectorSortColumn(), SortOrder.valueOf(guiPreferences.getMechSelectorSortOrder()))); } catch (Exception e) { logger.error(getClass(), "setUserPreferences", "Failed to set based on user preferences, attempting to use default", e); sortList.add(new SortKey(guiPreferences.getMechSelectorDefaultSortColumn(), SortOrder.valueOf(guiPreferences.getMechSelectorDefaultSortOrder()))); } tableUnits.getRowSorter().setSortKeys(sortList); ((DefaultRowSorter<?, ?>) tableUnits.getRowSorter()).sort(); tableUnits.invalidate(); pack(); }
Source:
public void afterRun() throws Exception { if (recordStore.isWanReplicationEnabled()) { CacheRecord record = recordStore.getRecord(key); if (record != null) { publishWanUpdate(key, record); } else { publishWanRemove(key); } } super.afterRun(); }

Target:
public void afterRun() throws Exception { if (recordStore == null) { return; } if (recordStore.isWanReplicationEnabled()) { CacheRecord record = recordStore.getRecord(key); if (record != null) { publishWanUpdate(key, record); } else { publishWanRemove(key); } } super.afterRun(); }
Source:
public void readWithWrongPayloadType() throws Exception{ KryoMessageConverter kryoMessageConverter = new KryoMessageConverter(null,true); Message message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE,KryoMessageConverter.KRYO_MIME_TYPE+";type=java.lang.String").build(); Object result = kryoMessageConverter.fromMessage(message,String.class); }

Target:
public void readWithWrongPayloadType() throws Exception{ KryoMessageConverter kryoMessageConverter = new KryoMessageConverter(null,true); Message message = MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE,KryoMessageConverter.KRYO_MIME_TYPE+";type=java.lang.String").build(); kryoMessageConverter.fromMessage(message,String.class); }
Source:
public JmsConfiguration incomingWebServiceRequestsJmsConfiguration( final JmsConfigurationFactory jmsConfigurationFactory) { return jmsConfigurationFactory.initializeReceiveConfiguration("jms.incoming.ws.requests", this.incomingWebServiceRequestMessageListener); }

Target:
public JmsConfiguration incomingWebServiceRequestsJmsConfiguration( final JmsConfigurationFactory jmsConfigurationFactory) { return jmsConfigurationFactory.initializeReceiveConfiguration(JmsConfigurationNames.JMS_INCOMING_WS_REQUESTS, this.incomingWebServiceRequestMessageListener); }
Source:
public void returnIterator() throws IOException { final String user = "testuser1"; final RepoCommits commits = new MkRepoCommits( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo1") ); MatcherAssert.assertThat( commits.iterate( Collections.<String, String>emptyMap() ), Matchers.notNullValue() ); }

Target:
public void returnIterator() throws IOException { final String user = "testuser1"; MatcherAssert.assertThat( new MkRepoCommits( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo1") ).iterate(Collections.<String, String>emptyMap()), Matchers.notNullValue() ); }
Source:
private static void createItem(PDOutlineItem item, FeatureTreeNode root, FeaturesCollection collection, Set<PDOutlineItem> items) throws FeaturesTreeNodeException { if (item != null) { items.add(item); FeatureTreeNode itemNode = FeatureTreeNode.newChildInstance( "outline", root); PBCreateNodeHelper.addNotEmptyNode("title", item.getTitle(), itemNode); FeatureTreeNode color = FeatureTreeNode.newChildInstance( "color", itemNode); PDColor clr = item.getTextColor(); float[] rgb = clr.getComponents(); if (rgb.length == RGB_COLORS_NUMBER) { FeatureTreeNode.newChildInstanceWithValue("red", String.valueOf(rgb[RGB_RED_COLOR_NUMBER]), color); FeatureTreeNode.newChildInstanceWithValue("green", String.valueOf(rgb[RGB_GREEN_COLOR_NUMBER]), color); FeatureTreeNode.newChildInstanceWithValue("blue", String.valueOf(rgb[RGB_BLUE_COLOR_NUMBER]), color); } else { color.addAttribute(ErrorsHelper.ERRORID, ErrorsHelper.OUTLINESCOLOR_ID); ErrorsHelper.addErrorIntoCollection(collection, ErrorsHelper.OUTLINESCOLOR_ID, ErrorsHelper.OUTLINESCOLOR_MESSAGE); } FeatureTreeNode.newChildInstanceWithValue("italic", String.valueOf(item.isItalic()), itemNode); FeatureTreeNode.newChildInstanceWithValue("bold", String.valueOf(item.isBold()), itemNode); for (PDOutlineItem child : item.children()) { if (!items.contains(item)) { createItem(child, itemNode, collection, items); } } } }

Target:
private static void createItem(PDOutlineItem item, FeatureTreeNode root, FeaturesCollection collection, Set<PDOutlineItem> items) throws FeaturesTreeNodeException { if (item != null) { items.add(item); FeatureTreeNode itemNode = FeatureTreeNode.newChildInstance( "outline", root); PBCreateNodeHelper.addNotEmptyNode("title", item.getTitle(), itemNode); if (item.getTextColor() != null) { FeatureTreeNode color = FeatureTreeNode.newChildInstance( "color", itemNode); PDColor clr = item.getTextColor(); float[] rgb = clr.getComponents(); if (rgb.length == RGB_COLORS_NUMBER) { FeatureTreeNode.newChildInstanceWithValue("red", String.valueOf(rgb[RGB_RED_COLOR_NUMBER]), color); FeatureTreeNode.newChildInstanceWithValue("green", String.valueOf(rgb[RGB_GREEN_COLOR_NUMBER]), color); FeatureTreeNode.newChildInstanceWithValue("blue", String.valueOf(rgb[RGB_BLUE_COLOR_NUMBER]), color); } else { color.addAttribute(ErrorsHelper.ERRORID, ErrorsHelper.OUTLINESCOLOR_ID); ErrorsHelper.addErrorIntoCollection(collection, ErrorsHelper.OUTLINESCOLOR_ID, ErrorsHelper.OUTLINESCOLOR_MESSAGE); } } FeatureTreeNode.newChildInstanceWithValue("italic", String.valueOf(item.isItalic()), itemNode); FeatureTreeNode.newChildInstanceWithValue("bold", String.valueOf(item.isBold()), itemNode); for (PDOutlineItem child : item.children()) { if (!items.contains(item)) { createItem(child, itemNode, collection, items); } } } }
Source:
private void recoverTempFiles(String logPath) { File logPathFile = new File(logPath).getParentFile(); File[] tempFiles = logPathFile.listFiles((dir, name) -> name.endsWith(TEMP_FILE_EXTENSION)); if (tempFiles != null) { for (File tempFile : tempFiles) { String newName = tempFile.getName().substring(0, tempFile.getName().length() - TEMP_FILE_EXTENSION.length()); File newFile = new File(tempFile.getParent(), newName + LOG_FILE_EXTENSION); if (!tempFile.renameTo(newFile)) { reportError("Could not rename temp file [" + tempFile + "] to [" + newFile + "]", null, ErrorManager.OPEN_FAILURE); } } } }

Target:
private void recoverTempFiles(String logPath) { File logPathFile = new File(logPath).getParentFile(); File[] tempFiles = logPathFile.listFiles((dir, name) -> name.endsWith(TEMP_FILE_EXTENSION)); if (tempFiles == null) { return; } for (File tempFile : tempFiles) { String newName = tempFile.getName().substring(0, tempFile.getName().length() - TEMP_FILE_EXTENSION.length()); File newFile = new File(tempFile.getParent(), newName + LOG_FILE_EXTENSION); if (!tempFile.renameTo(newFile)) { reportError(format("Could not rename temp file [%s] to [%s]", tempFile, newFile), null, ErrorManager.OPEN_FAILURE); } } }
Source:
private void generateIBClassesFile(File installDir) throws IOException { List<String> customClasses = config.getCustomIBClasses(); if (!customClasses.isEmpty()) { FileWriter fw = new FileWriter(new File(installDir, "ib.classes")); String array = StringUtils.toString(customClasses.toArray(new String[customClasses.size()]), ","); fw.write(array); fw.close(); } }

Target:
private void generateIBClassesFile(File installDir) throws IOException { List<String> customClasses = config.getCustomIBClasses(); if (!customClasses.isEmpty()) { try (FileWriter fw = new FileWriter(new File(installDir, "ib.classes"))) { String array = StringUtils.toString(customClasses.toArray(new String[customClasses.size()]), ","); fw.write(array); } } }
Source:
protected void processEventChunk(ComplexEventChunk complexEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) { while (complexEventChunk.hasNext()) { ComplexEvent complexEvent = complexEventChunk.next(); Object[] outputData; switch (attributeExpressionLength) { case 0: outputData = process((Object) null); complexEventPopulater.populateComplexEvent(complexEvent, outputData); break; case 1: outputData = process(attributeExpressionExecutors[0].execute(complexEvent)); complexEventPopulater.populateComplexEvent(complexEvent, outputData); break; default: Object[] inputData = new Object[attributeExpressionLength]; for (int i = 0; i < attributeExpressionLength; i++) { inputData[i] = attributeExpressionExecutors[i].execute(complexEvent); } outputData = process(inputData); complexEventPopulater.populateComplexEvent(complexEvent, outputData); break; } } nextProcessor.process(complexEventChunk); }

Target:
protected void processEventChunk(ComplexEventChunk complexEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) { while (complexEventChunk.hasNext()) { ComplexEvent complexEvent = complexEventChunk.next(); Object[] outputData; switch (attributeExpressionLength) { case 0: outputData = process((Object) null); complexEventPopulater.populateComplexEvent(complexEvent, outputData); break; case 1: outputData = process(attributeExpressionExecutors[0].execute(complexEvent)); complexEventPopulater.populateComplexEvent(complexEvent, outputData); break; default: Object[] inputData = new Object[attributeExpressionLength]; for (int i = 0; i < attributeExpressionLength; i++) { inputData[i] = attributeExpressionExecutors[i].execute(complexEvent); } outputData = process(inputData); complexEventPopulater.populateComplexEvent(complexEvent, outputData); } } nextProcessor.process(complexEventChunk); }
Source:
private boolean isSnapshotUsed(VM vm) { if (vm.isRunning() || vm.getStatus() == VMStatus.Paused) { Set<Guid> volumeChain = imagesHandler.getVolumeChain(vm.getId(), vm.getRunOnVds(), getDiskImage()); if (volumeChain == null) { log.warn("Could not retrieve chain, skipping deletion"); return true; } if (volumeChain.contains(getDiskImage().getImageId())) { log.warn("Image '{}' appears to be in use by VM '{}', skipping deletion", getDiskImage().getImageId(), vm.getId()); return true; } } return false; }

Target:
private boolean isSnapshotUsed(VM vm) { if (vm.isRunningOrPaused() && vm.getStatus() != VMStatus.WaitForLaunch) { Set<Guid> volumeChain = imagesHandler.getVolumeChain(vm.getId(), vm.getRunOnVds(), getDiskImage()); if (volumeChain == null) { log.warn("Could not retrieve chain, skipping deletion"); return true; } if (volumeChain.contains(getDiskImage().getImageId())) { log.warn("Image '{}' appears to be in use by VM '{}', skipping deletion", getDiskImage().getImageId(), vm.getId()); return true; } } return false; }
Source:
private <P> Flowable<P> publish(IntSet segments, Function<ResultSet, Flowable<P>> function) { return Flowable.using(() -> { Connection connection = connectionFactory.getConnection(); connection.setAutoCommit(false); String sql; if (segments != null) { sql = tableManager.getLoadNonExpiredRowsSqlForSegments(segments.size()); } else { sql = tableManager.getLoadNonExpiredAllRowsSql(); } if (trace) { log.tracef("Running sql %s", sql); } return new KeyValuePair<>(connection, connection.prepareStatement(sql)); }, kvp -> { PreparedStatement ps = kvp.getValue(); int offset = 1; ps.setLong(offset, timeService.wallClockTime()); if (segments != null) { for (PrimitiveIterator.OfInt segIter = segments.iterator(); segIter.hasNext(); ) { ps.setInt(++offset, segIter.nextInt()); } } ps.setFetchSize(tableManager.getFetchSize()); ResultSet rs = ps.executeQuery(); return function.apply(rs).doOnComplete(() -> JdbcUtil.safeClose(rs)); }, kvp -> { JdbcUtil.safeClose(kvp.getValue()); Connection connection = kvp.getKey(); connection.rollback(); connectionFactory.releaseConnection(connection); }); }

Target:
private <P> Flowable<P> publish(IntSet segments, Function<ResultSet, Flowable<P>> function) { return Flowable.using(() -> { String sql; if (segments != null) { sql = tableManager.getLoadNonExpiredRowsSqlForSegments(segments.size()); } else { sql = tableManager.getLoadNonExpiredAllRowsSql(); } if (trace) { log.tracef("Running sql %s", sql); } return new FlowableConnection(connectionFactory, sql); }, fc -> { PreparedStatement ps = fc.statement; int offset = 1; ps.setLong(offset, timeService.wallClockTime()); if (segments != null) { for (PrimitiveIterator.OfInt segIter = segments.iterator(); segIter.hasNext(); ) { ps.setInt(++offset, segIter.nextInt()); } } ps.setFetchSize(tableManager.getFetchSize()); ResultSet rs = ps.executeQuery(); return function.apply(rs).doOnComplete(() -> JdbcUtil.safeClose(rs)); }, FlowableConnection::close); }
Source:
public Interval getSourceInterval() { if ( stop==null ) { if ( start!=null ) { return Interval.of(start.getTokenIndex(), start.getTokenIndex()-1); } else { return Interval.of(0, -1); } } return Interval.of(start.getTokenIndex(), stop.getTokenIndex()); }

Target:
public Interval getSourceInterval() { if ( start == null ) { return Interval.INVALID; } if ( stop==null || stop.getTokenIndex()<start.getTokenIndex() ) { return Interval.of(start.getTokenIndex(), start.getTokenIndex()-1); } return Interval.of(start.getTokenIndex(), stop.getTokenIndex()); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LegalInformationComplete that = (LegalInformationComplete) o; return content != null ? content.equals(that.content) : that.content == null; }

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof LegalInformationComplete)) return false; LegalInformationComplete that = (LegalInformationComplete) o; return content != null ? content.equals(that.content) : that.content == null; }
Source:
public boolean isGround() { if (isGround == null) { if (variableSet == null || !variableSet.isEmpty()) { new IsGroundFieldInitializer().visitNode(this); } else { isGround = true; } } return isGround; }

Target:
public boolean isGround() { if (isGround == null) { if (variableSet == null) { new IsGroundFieldInitializer().visitNode(this); } else { isGround = variableSet.isEmpty(); } } return isGround; }
Source:
public void newStreamWithData() throws Exception { HTTP2Client http2Client = new HTTP2Client(); http2Client.start(); SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); CompletableFuture<Session> sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); Session session = sessionCF.get(); HttpFields.Mutable requestHeaders = HttpFields.build() .put(HttpHeader.CONTENT_TYPE, "application/json"); MetaData.Request request = new MetaData.Request("POST", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, false); CompletableFuture<Stream> streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter()); Stream stream = streamCF.get(); String content1 = "{\"greet\": \"hello world\"}"; ByteBuffer buffer1 = StandardCharsets.UTF_8.encode(content1); String content2 = "{\"user\": \"jetty\"}"; ByteBuffer buffer2 = StandardCharsets.UTF_8.encode(content2); CompletableFuture<Stream> dataCF1 = stream.data(new DataFrame(stream.getId(), buffer1, false)); dataCF1.thenCompose(s -> s.data(new DataFrame(s.getId(), buffer2, true))); }

Target:
public void newStreamWithData() throws Exception { HTTP2Client http2Client = new HTTP2Client(); http2Client.start(); SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); CompletableFuture<Session> sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() .put(HttpHeader.CONTENT_TYPE, "application/json"); MetaData.Request request = new MetaData.Request("POST", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, false); CompletableFuture<Stream> streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter()); Stream stream = streamCF.get(); String content1 = "{\"greet\": \"hello world\"}"; ByteBuffer buffer1 = StandardCharsets.UTF_8.encode(content1); String content2 = "{\"user\": \"jetty\"}"; ByteBuffer buffer2 = StandardCharsets.UTF_8.encode(content2); CompletableFuture<Stream> dataCF1 = stream.data(new DataFrame(stream.getId(), buffer1, false)); dataCF1.thenCompose(s -> s.data(new DataFrame(s.getId(), buffer2, true))); }
Source:
private JobResult executeSchedulingTest(int numSlots) throws Exception { final Configuration configuration = new Configuration(); configuration.setString(RestOptions.BIND_PORT, "0"); configuration.setLong(JobManagerOptions.SLOT_REQUEST_TIMEOUT, 5000L); final MiniClusterConfiguration miniClusterConfiguration = new MiniClusterConfiguration.Builder() .setConfiguration(configuration) .setNumTaskManagers(1) .setNumSlotsPerTaskManager(numSlots) .build(); try (MiniCluster miniCluster = new MiniCluster(miniClusterConfiguration)) { miniCluster.start(); final MiniClusterClient miniClusterClient = new MiniClusterClient(configuration, miniCluster); final JobGraph jobGraph = createJobGraph(100); final JobID jobID = miniClusterClient.submitJob(jobGraph).get(); final CompletableFuture<JobResult> resultFuture = miniClusterClient.requestJobResult(jobID); final JobResult jobResult = resultFuture.get(); return jobResult; } }

Target:
private JobResult executeSchedulingTest(int numSlots) throws Exception { final Configuration configuration = new Configuration(); configuration.setString(RestOptions.BIND_PORT, "0"); configuration.setLong(JobManagerOptions.SLOT_REQUEST_TIMEOUT, 5000L); configuration.setString(JobManagerOptions.SCHEDULING_STRATEGY, "region"); final MiniClusterConfiguration miniClusterConfiguration = new MiniClusterConfiguration.Builder() .setConfiguration(configuration) .setNumTaskManagers(1) .setNumSlotsPerTaskManager(numSlots) .build(); try (MiniCluster miniCluster = new MiniCluster(miniClusterConfiguration)) { miniCluster.start(); final MiniClusterClient miniClusterClient = new MiniClusterClient(configuration, miniCluster); final JobGraph jobGraph = createJobGraph(10); final JobID jobID = miniClusterClient.submitJob(jobGraph).get(); final CompletableFuture<JobResult> resultFuture = miniClusterClient.requestJobResult(jobID); final JobResult jobResult = resultFuture.get(); return jobResult; } }
Source:
public void obtainNewAccessToken() throws InterruptedException, ExecutionException, TimeoutException { new NetworkCallTask().execute(); }

Target:
public void obtainNewAccessToken() { new NetworkCallTask().execute(); }
Source:
public ConsistentHash getReadConsistentHash() { switch (phase) { case CONFLICT_RESOLUTION: assert pendingCH != null; assert unionCH != null; return currentCH; case NO_REBALANCE: assert pendingCH == null; assert unionCH == null; return currentCH; case READ_OLD_WRITE_ALL: assert pendingCH != null; assert unionCH != null; return currentCH; case READ_ALL_WRITE_ALL: assert pendingCH != null; return unionCH; case READ_NEW_WRITE_ALL: assert unionCH != null; return pendingCH; } return currentCH; }

Target:
public ConsistentHash getReadConsistentHash() { switch (phase) { case NO_REBALANCE: assert pendingCH == null; assert unionCH == null; return currentCH; case CONFLICT_RESOLUTION: case READ_OLD_WRITE_ALL: assert pendingCH != null; assert unionCH != null; return currentCH; case READ_ALL_WRITE_ALL: assert pendingCH != null; return unionCH; case READ_NEW_WRITE_ALL: assert unionCH != null; return pendingCH; } return currentCH; }
Source:
public ProjectDetailEvent( Project projectSelected ) { this.projectSelected = projectSelected; }

Target:
public ProjectDetailEvent( Project projectSelected ) { checkNotNull( "projectSelected", projectSelected ); this.projectSelected = projectSelected; }
Source:
public String getPrimaryBroadcastAddress() { String primaryIp = getPrimaryIpv4HostAddress(); String broadcastAddress = null; if (primaryIp != null) { try { byte[] addr = InetAddress.getByName(primaryIp).getAddress(); Short prefix = getAllInterfaceAddresses().stream() .filter(a -> a.getAddress().getHostAddress().equals(primaryIp)).map(a -> a.getPrefix()) .findFirst().get().shortValue(); byte[] netmask = InetAddress.getByName(networkPrefixLengthToNetmask(prefix)).getAddress(); byte[] broadcast = new byte[] { (byte) (~netmask[0] | addr[0]), (byte) (~netmask[1] | addr[1]), (byte) (~netmask[2] | addr[2]), (byte) (~netmask[3] | addr[3]) }; broadcastAddress = InetAddress.getByAddress(broadcast).getHostAddress(); } catch (UnknownHostException ex) { LOGGER.error("Invalid IP address parameter: {}", ex.getMessage(), ex); } } if (broadcastAddress == null) { broadcastAddress = getFirstIpv4BroadcastAddress(); LOGGER.warn( "Could not find broadcast address of configured IP, using broadcast address of first interface instead", broadcastAddress); } return broadcastAddress; }

Target:
private String getPrimaryBroadcastAddress() { String primaryIp = getPrimaryIpv4HostAddress(); String broadcastAddress = null; if (primaryIp != null) { try { Short prefix = getAllInterfaceAddresses().stream() .filter(a -> a.getAddress().getHostAddress().equals(primaryIp)).map(a -> a.getPrefix()) .findFirst().get().shortValue(); broadcastAddress = getIpv4NetBroadcastAddress(primaryIp, prefix); } catch (IllegalArgumentException ex) { LOGGER.error("Invalid IP address parameter: {}", ex.getMessage(), ex); } } if (broadcastAddress == null) { broadcastAddress = getFirstIpv4BroadcastAddress(); LOGGER.warn( "Could not find broadcast address of primary IP, using broadcast address of first interface instead", broadcastAddress); } return broadcastAddress; }
Source:
public void handleSynchronizeTimeresponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSynchronizeReadsresponse for MessageType: {}", messageType); ResponseMessageResultType result = ResponseMessageResultType.OK; if (exception != null) { LOGGER.error("Device Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, result, exception, null), messageType); }

Target:
public void handleSynchronizeTimeresponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleSynchronizeReadsresponse for MessageType: {}", messageType); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Device Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(new ResponseMessage(correlationUid, organisationIdentification, deviceIdentification, result, exception, null), messageType); }
Source:
public ODocument onInstall(OrienteerWebApplication app, ODatabaseDocument db) { onUpdate(app, db, 0, getVersion()); OSchemaHelper helper = OSchemaHelper.bind(db); helper.oClass(WIDGET_OCLASS_NAME, OWidgetsModule.OCLASS_WIDGET) .oProperty(OPROPERTY_PIVOT_CUSTOM_SQL, OType.STRING, 200).assignVisualization("textarea"); return null; }

Target:
public ODocument onInstall(OrienteerWebApplication app, ODatabaseDocument db) { onUpdate(app, db, 0, getVersion()); return null; }
Source:
public int prepare(Xid xid) throws XAException { if (trace) { log.tracef("XaResource.prepare(%s)", xid); } if (currentXid == null) { throw new XAException(XAException.XAER_NOTA); } else if (!currentXid.equals(xid)) { throw new XAException(XAException.XAER_INVAL); } return internalPrepare(false); }

Target:
public int prepare(Xid xid) throws XAException { if (trace) { log.tracef("XaResource.prepare(%s)", xid); } assertStartInvoked(); assertSameXid(xid, XAException.XAER_INVAL); return internalPrepare(false); }
Source:
HeadContext(DefaultChannelPipeline pipeline) { super(pipeline, pipeline.channel.eventLoop(), HEAD_NAME, HeadContext.class); unsafe = pipeline.channel().unsafe(); setAddComplete(); }

Target:
HeadContext(DefaultChannelPipeline pipeline) { super(pipeline, HEAD_NAME, HeadContext.class); unsafe = pipeline.channel().unsafe(); setAddComplete(); }
Source:
public boolean start() throws Exception { ThrottledStepInfo info = new ThrottledStepInfo(getCategory()); ThrottledStepInfo parentInfo = getContext().get(ThrottledStepInfo.class); if (parentInfo != null) { Computer computer = getContext().get(Computer.class); if (computer != null && computer.getNode() != null) { parentInfo.setNode(computer.getNode().getNodeName()); } info.setParentInfo(parentInfo); } Run<?, ?> r = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); ThrottleJobProperty.DescriptorImpl descriptor = Jenkins.getActiveInstance().getDescriptorByType(ThrottleJobProperty.DescriptorImpl.class); descriptor.addThrottledPipelineForCategory(r.getExternalizableId(), getCategory(), listener); body = getContext().newBodyInvoker() .withContext(info) .withCallback(BodyExecutionCallback.wrap(getContext())) .start(); return false; }

Target:
public boolean start() throws Exception { Run<?, ?> r = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); FlowNode flowNode = getContext().get(FlowNode.class); ThrottleJobProperty.DescriptorImpl descriptor = ThrottleJobProperty.fetchDescriptor(); String runId = null; String flowNodeId = null; if (r != null && flowNode != null) { runId = r.getExternalizableId(); flowNodeId = flowNode.getId(); for (String category : validateCategories(descriptor, listener)) { descriptor.addThrottledPipelineForCategory(runId, flowNodeId, category, listener); } } getContext().newBodyInvoker() .withCallback(new Callback(runId, flowNodeId, getCategories())) .start(); return false; }
Source:
public void setUp() throws Exception { WebAppContext context; context = new WebAppContext("/Users/aled/repos/apache-asf/incubator-brooklyn/usage/rest-client/src/test/webapp", "/"); context.setExtraClasspath("/Users/aled/repos/apache-asf/incubator-brooklyn/usage/rest-client/target/test-rest-server/"); context.setAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, getManagementContext()); Server server = BrooklynRestApiLauncher.launcher() .managementContext(manager) .customContext(context) .start(); api = new BrooklynApi("http://localhost:" + server.getConnectors()[0].getPort() + "/"); }

Target:
public void setUp() throws Exception { WebAppContext context; context = new WebAppContext("src/test/webapp", "/"); context.setExtraClasspath("./target/test-rest-server/"); context.setAttribute(BrooklynServiceAttributes.BROOKLYN_MANAGEMENT_CONTEXT, getManagementContext()); Server server = BrooklynRestApiLauncher.launcher() .managementContext(manager) .customContext(context) .start(); api = new BrooklynApi("http://localhost:" + server.getConnectors()[0].getPort() + "/"); }