auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void merge(ExecAggregator addend) throws StandardException { if(addend==null) return; DecimalBufferedSumAggregator other = (DecimalBufferedSumAggregator)addend; <START> if (other.isNull && other.position == 0){ <END> return; } if (!Objects.equals(other.sum, BigDecimal.ZERO)) { buffer[position] = other.sum; incrementPosition(); } for (int i = 0; i< other.position;i++) { buffer[position] = other.buffer[i]; incrementPosition(); } }</code><technical_language>do need add check of other.position == 0? other.isNull is enough represent other is empty</technical_language>

Target:
public void merge(ExecAggregator addend) throws StandardException { if(addend==null) return; DecimalBufferedSumAggregator other = (DecimalBufferedSumAggregator)addend; if (other.isNull){ return; } if (!Objects.equals(other.sum, BigDecimal.ZERO)) { buffer[position] = other.sum; incrementPosition(); } for (int i = 0; i< other.position;i++) { buffer[position] = other.buffer[i]; incrementPosition(); } }
Source:
<code>private MetricFamilySamples buildStatusGauge() { <START> String name = "jetty_responses"; <END> return new MetricFamilySamples( name, Type.GAUGE, "number of requests with response status", Arrays.asList( buildStatusSample(name, "1xx", statisticsHandler.getResponses1xx()), buildStatusSample(name, "2xx", statisticsHandler.getResponses2xx()), buildStatusSample(name, "3xx", statisticsHandler.getResponses3xx()), buildStatusSample(name, "4xx", statisticsHandler.getResponses4xx()), buildStatusSample(name, "5xx", statisticsHandler.getResponses5xx()) ) ); }</code><technical_language>This is once, inline</technical_language>

Target:
private MetricFamilySamples buildStatusGauge() { String name = "jetty_responses"; return new MetricFamilySamples( name, Type.GAUGE, "Number of requests with response status", Arrays.asList( buildStatusSample(name, "1xx", statisticsHandler.getResponses1xx()), buildStatusSample(name, "2xx", statisticsHandler.getResponses2xx()), buildStatusSample(name, "3xx", statisticsHandler.getResponses3xx()), buildStatusSample(name, "4xx", statisticsHandler.getResponses4xx()), buildStatusSample(name, "5xx", statisticsHandler.getResponses5xx()) ) ); }
Source:
<code>public void setConnectionNameStrategy(ConnectionNameStrategy connectionNameStrategy) { this.connectionNameStrategy = connectionNameStrategy; if (this.publisherConnectionFactory != null) { this.publisherConnectionFactory.setConnectionNameStrategy( <START> cf -> connectionNameStrategy + PUBLISHER_SUFFIX); <END> } }</code><technical_language>be: cf -> connectionNameStrategy.obtainNewConnectionName(cf) + PUBLISHER_SUFFIX);</technical_language>

Target:
public void setConnectionNameStrategy(ConnectionNameStrategy connectionNameStrategy) { this.connectionNameStrategy = connectionNameStrategy; if (this.publisherConnectionFactory != null) { this.publisherConnectionFactory.setConnectionNameStrategy( cf -> connectionNameStrategy.obtainNewConnectionName(cf) + PUBLISHER_SUFFIX); } }
Source:
<code>public static void setupViews(List<View> views) { DEFAULT_VIEWS.clear(); for(View view: views) { try { JSONObject json = new JSONObject(); <START> String srsName = view.getBundleByName("mapfull") <END> .getConfigJSON() .getJSONObject("mapOptions") .getString("srsName"); json.put("uuid", view.getUuid()); json.put("name", view.getName()); json.put("srsName", srsName); DEFAULT_VIEWS.add(json); } catch (JSONException e) { LOGGER.warn("Couldn't format default views for appsetup.env:", e.getMessage()); } } }</code><technical_language>This replaced View#getSrsName() added in #140</technical_language>

Target:
public static void setupViews(List<View> views) { DEFAULT_VIEWS.clear(); for(View view: views) { try { JSONObject json = new JSONObject(); json.put("uuid", view.getUuid()); json.put("name", view.getName()); json.put("srsName", view.getSrsName()); DEFAULT_VIEWS.add(json); } catch (JSONException e) { LOGGER.warn("Couldn't format default views for appsetup.env:", e.getMessage()); } } }
Source:
<code>private ModelBuildingRequest getModelBuildingRequest( InternalConfig config, File pomFile ) { ProjectBuildingRequest configuration = config.request; ModelBuildingRequest request = new DefaultModelBuildingRequest(); RequestTrace trace = RequestTrace.newChild( null, configuration ).newChild( request ); RepositorySystemSession repoSession; if ( Features.buildConsumer().isActive() ) { TransformerContext context = new TransformerContext() { @Override public String getUserProperty( String key ) { return config.session.getUserProperties().get( key ); } @Override public Model getRawModel( Path p ) { return config.modelPool.get( p ); } @Override public Model getRawModel( String groupId, String artifactId ) { <START> return config.modelPool.get( groupId, artifactId, null ); <END> } }; request.setTransformerContext( context ); repoSession = new DefaultRepositorySystemSession( config.session ) .setFileTransformerManager( a -> getTransformersForArtifact( a, context ) ); } else { repoSession = config.session; } ModelResolver resolver = new ProjectModelResolver( repoSession, trace, repoSystem, repositoryManager, config.repositories, configuration.getRepositoryMerging(), config.modelPool ); request.setValidationLevel( configuration.getValidationLevel() ); request.setProcessPlugins( configuration.isProcessPlugins() ); request.setProfiles( configuration.getProfiles() ); request.setActiveProfileIds( configuration.getActiveProfileIds() ); request.setInactiveProfileIds( configuration.getInactiveProfileIds() ); request.setSystemProperties( configuration.getSystemProperties() ); request.setUserProperties( configuration.getUserProperties() ); request.setBuildStartTime( configuration.getBuildStartTime() ); request.setModelResolver( resolver ); request.setModelCache( config.modelCache ); return request; }</code><technical_language>Stupid question: this pool need synchronized</technical_language>

Target:
private ModelBuildingRequest getModelBuildingRequest( InternalConfig config, File pomFile ) { ProjectBuildingRequest configuration = config.request; ModelBuildingRequest request = new DefaultModelBuildingRequest(); RequestTrace trace = RequestTrace.newChild( null, configuration ).newChild( request ); ModelResolver resolver = new ProjectModelResolver( config.session, trace, repoSystem, repositoryManager, config.repositories, configuration.getRepositoryMerging(), config.modelPool ); request.setValidationLevel( configuration.getValidationLevel() ); request.setProcessPlugins( configuration.isProcessPlugins() ); request.setProfiles( configuration.getProfiles() ); request.setActiveProfileIds( configuration.getActiveProfileIds() ); request.setInactiveProfileIds( configuration.getInactiveProfileIds() ); request.setSystemProperties( configuration.getSystemProperties() ); request.setUserProperties( configuration.getUserProperties() ); request.setBuildStartTime( configuration.getBuildStartTime() ); request.setModelResolver( resolver ); request.setModelCache( config.modelCache ); request.setTransformerContext( (TransformerContext) config.session.getData().get( TransformerContext.KEY ) ); return request; }
Source:
<code>public VectorizedParquetRecordReader( org.apache.hadoop.mapred.InputSplit oldInputSplit, JobConf conf) { try { serDeStats = new SerDeStats(); projectionPusher = new ProjectionPusher(); initialize(oldInputSplit, conf); colsToInclude = ColumnProjectionUtils.getReadColumnIDs(conf); rbCtx = Utilities.getVectorizedRowBatchCtx(conf); } catch (IOException e) { <START> e.printStackTrace(); <END> } catch (InterruptedException e) { e.printStackTrace(); } }</code><technical_language>throw exception here</technical_language>

Target:
public VectorizedParquetRecordReader( org.apache.hadoop.mapred.InputSplit oldInputSplit, JobConf conf) { try { serDeStats = new SerDeStats(); projectionPusher = new ProjectionPusher(); initialize(getSplit(oldInputSplit, conf), conf); colsToInclude = ColumnProjectionUtils.getReadColumnIDs(conf); rbCtx = Utilities.getVectorizedRowBatchCtx(conf); } catch (Throwable e) { LOG.error("Failed to create the vectorized reader due to exception " + e); throw new RuntimeException(e); } }
Source:
<code>public void cleanupBefore(long txid) { SortedMap<Long, Object> toDelete = _curr.headMap(txid); for(long tx: new HashSet<Long>(toDelete.keySet())) { _curr.remove(tx); try { _state.delete(txPath(tx)); } catch(RuntimeException e) { <START> if(!(e.getCause() instanceof KeeperException.NoNodeException)) { <END> throw e; } } } }</code><technical_language>replace this logic similar exception-cause? function in Clojure. more robust checking level deep in exception stack</technical_language>

Target:
public void cleanupBefore(long txid) { SortedMap<Long, Object> toDelete = _curr.headMap(txid); for(long tx: new HashSet<Long>(toDelete.keySet())) { _curr.remove(tx); try { _state.delete(txPath(tx)); } catch(RuntimeException e) { if(!Utils.exceptionCauseIsInstanceOf(KeeperException.NoNodeException.class, e)) { throw e; } } } }
Source:
<code><START> public boolean equals(Object o) <END> { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GroupTopNFunction that = (GroupTopNFunction) o; if (limit != that.limit) { return false; } if (granularity != null ? !granularity.equals(that.granularity) : that.granularity != null) { return false; } if (!ordering.equals(that.ordering)) { return false; } return true; }</code><technical_language>is this anywhere</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GroupTopNFunction that = (GroupTopNFunction) o; if (limit != that.limit || limitPerGroup != that.limitPerGroup) { return false; } if (granularity != that.granularity) { return false; } if (!ordering.equals(that.ordering)) { return false; } return true; }
Source:
<code>private static String formatLinks(final String txt) { final String marker = "]("; final String html = "=\""; final StringBuilder result = new StringBuilder(); final Matcher matcher = MarkdownTxtmark.LINK.matcher(txt); int start = 0; while (matcher.find(start)) { result.append(txt.substring(start, matcher.start())); final String prefix = txt.substring( <START> Math.max(0, matcher.start() - 2), <END> matcher.start() ); final String suffix = txt.substring( matcher.end(), Math.min(txt.length(), matcher.end() + 2) ); final String uri = matcher.group(); if (marker.equals(suffix) || marker.equals(prefix) || html.equals(prefix)) { result.append(uri); } else { result.append(String.format("[%1$s](%1$s)", uri)); } start = matcher.end(); } result.append(txt.substring(start)); return result.toString(); }</code><technical_language>@dmzaytsev is "2" in this case</technical_language>

Target:
private static String formatLinks(final String txt) { final StringBuffer result = new StringBuffer(); final Matcher matcher = MarkdownTxtmark.LINK.matcher(txt); while (matcher.find()) { matcher.appendReplacement( result, String.format("[%1$s](%1$s)", matcher.group()) ); } matcher.appendTail(result); return result.toString(); }
Source:
<code><START> private Resource minShareStarvation() { <END> Resource desiredShare = Resources.min(policy.getResourceCalculator(), scheduler.getClusterResource(), getMinShare(), getDemand()); Resource starvation = Resources.subtract(desiredShare, getResourceUsage()); boolean starved = Resources.greaterThan(policy.getResourceCalculator(), scheduler.getClusterResource(), starvation, none()); long now = scheduler.getClock().getTime(); if (!starved) { setLastTimeAtMinShare(now); } if (starved && (now - lastTimeAtMinShare > getMinSharePreemptionTimeout())) { return starvation; } else { return Resources.clone(Resources.none()); } }</code><technical_language>This convoluted. not: {code} boolean starved = false; Resource starvation = none(); if (Resources.greaterThan(policy.getResourceCalculator(), scheduler.getClusterResource(), getDemand(), getMinShare())) { starvation = Resources.subtract(getMinShare(), getResourceUsage()); starved = Resources.greaterThan(policy.getResourceCalculator(), scheduler.getClusterResource(), starvation, none()); } {code} Nets out thing, logic hard (for me) follow</technical_language>

Target:
private Resource minShareStarvation() { Resource desiredShare = Resources.min(policy.getResourceCalculator(), scheduler.getClusterResource(), getMinShare(), getDemand()); Resource starvation = Resources.subtract(desiredShare, getResourceUsage()); boolean starved = !Resources.isNone(starvation); long now = scheduler.getClock().getTime(); if (!starved) { setLastTimeAtMinShare(now); } if (now - lastTimeAtMinShare < getMinSharePreemptionTimeout()) { starvation = Resources.clone(Resources.none()); } return starvation; }
Source:
<code>private byte[] randomBytes(final long seed) { final MersenneTwisterFast r = new MersenneTwisterFast(seed); <START> final byte[] ldata = new byte[2938740]; <END> for (int i = 0; i < ldata.length; i++) { ldata[i] = r.nextByte(); } return ldata; }</code><technical_language>underscore in numeric constant above, here. consistent</technical_language>

Target:
private byte[] randomBytes(final long seed) { final MersenneTwisterFast r = new MersenneTwisterFast(seed); final byte[] ldata = new byte[TEST_SIZE]; for (int i = 0; i < ldata.length; i++) { ldata[i] = r.nextByte(); } return ldata; }
Source:
<code>public String toString() { <START> Iterable<String> parameterIndexii = Iterables.transform(positionList, new Function<Integer, String>() { <END> @Override public String apply(Integer input) { return String.format("+%d", input); } }); return "check " + type.getPrettyPrintableName() + "(" + Joiner.on(", ").join(parameterIndexii) + ")"; }</code><technical_language>indexii? indices</technical_language>

Target:
public String toString() { Iterable<String> parameterIndices = Iterables.transform(positionList, new Function<Integer, String>() { @Override public String apply(Integer input) { return String.format("+%d", input); } }); return "check " + type.getPrettyPrintableName() + "(" + Joiner.on(", ").join(parameterIndices) + ")"; }
Source:
<code>public void setSanStorageModel(SanStorageModel sanStorageModel) { super.setSanStorageModel(sanStorageModel); sanStorageModel.getLunSelectionChangedEvent().getListeners().clear(); sanStorageModel.getLunSelectionChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { String description = getDescription().getEntity(); if (description == null || description.isEmpty() || (!description.isEmpty() && descriptionDerivedFromLunId)) { LunModel selectedLunModel = ((ValueEventArgs<LunModel>) args).getValue(); if (selectedLunModel.getLunId() != null) { <START> String newDescription = selectedLunModel.getLunId().substring(selectedLunModel.getLunId().length() - 4); <END> getDescription().setEntity(newDescription); descriptionDerivedFromLunId = true; } } } }); }</code><technical_language>characters is arbitrary decision. shove lun ID there, configurable</technical_language>

Target:
public void setSanStorageModel(SanStorageModel sanStorageModel) { super.setSanStorageModel(sanStorageModel); sanStorageModel.getLunSelectionChangedEvent().getListeners().clear(); sanStorageModel.getLunSelectionChangedEvent().addListener(new IEventListener() { @Override public void eventRaised(Event ev, Object sender, EventArgs args) { String description = getDescription().getEntity(); if (description == null || description.isEmpty() || (!description.isEmpty() && descriptionDerivedFromLunId)) { LunModel selectedLunModel = ((ValueEventArgs<LunModel>) args).getValue(); if (selectedLunModel.getLunId() != null) { int numOfChars = (Integer) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.PopulateDirectLUNDiskDescriptionWithLUNId); if (numOfChars == 0) { return; } String newDescription; if (numOfChars <= -1 || numOfChars >= selectedLunModel.getLunId().length()) { newDescription = selectedLunModel.getLunId(); } else { newDescription = selectedLunModel.getLunId().substring(selectedLunModel.getLunId().length() - numOfChars); } getDescription().setEntity(newDescription); descriptionDerivedFromLunId = true; } } } }); }
Source:
<code>private Boolean hasIdPermission(Collection<Permission> permissions, Long id) { for (Permission p : permissions) { <START> if (p.id != null && p.id.longValue() == id) { return true; } <END> } return false; }</code><technical_language>Single return method please</technical_language>

Target:
private Boolean hasIdPermission(Collection<Permission> permissions, Long id) { boolean hasIdPermission = false; for (Permission p : permissions) { if (p.id != null && p.id.longValue() == id) { hasIdPermission = true; break; } } return hasIdPermission; }
Source:
<code><START> public void set(long uuid, VKmer thisReadSequence, VKmer mateReadSequence) { <END> value = uuid; if (thisReadSequence == null) { this.thisReadSequence = null; } else { this.thisReadSequence.setAsCopy(thisReadSequence); } if (mateReadSequence == null) { this.mateReadSequence = null; } else { this.mateReadSequence.setAsCopy(mateReadSequence); } }</code><technical_language>set thisReadSequence mateReadSequence in ReadHead, right? set(long uuid) for kmers ReadHead</technical_language>

Target:
public void set(long uuid, VKmer thisReadSequence, VKmer mateReadSequence) { value = uuid; if (thisReadSequence == null) { throw new IllegalArgumentException("thisReadSequence can not be null!"); } getThisReadSequence().setAsCopy(thisReadSequence); if (mateReadSequence == null) { this.mateReadSequence = null; } else { getMateReadSequence().setAsCopy(mateReadSequence); } }
Source:
<code>private static <M> OperatorImpl<M, ?> createOperatorImpl(MessageStreamImpl<M> source, OperatorSpec operatorSpec, Config config, TaskContext context) { if (operatorSpec instanceof StreamOperatorSpec) { StreamOperatorSpec<M, ?> streamOpSpec = (StreamOperatorSpec<M, ?>) operatorSpec; return new StreamOperatorImpl<>(streamOpSpec, source, config, context); } else if (operatorSpec instanceof SinkOperatorSpec) { return new SinkOperatorImpl<>((SinkOperatorSpec<M>) operatorSpec, config, context); } else if (operatorSpec instanceof WindowOperatorSpec) { <START> return new WindowOperatorImpl((WindowOperatorSpec<M, ?, ?>) operatorSpec); <END> } else if (operatorSpec instanceof PartialJoinOperatorSpec) { return new PartialJoinOperatorImpl<>((PartialJoinOperatorSpec) operatorSpec, source, config, context); } throw new IllegalArgumentException( String.format("Unsupported OperatorSpec: %s", operatorSpec.getClass().getName())); }</code><technical_language>So, closing door for user-defined context in window? i.e. if fold function refers a hashMap is initialized in task context? allowed user-defined context in map/flatMap/filter/join, I window? Is harm done in allowing optional init() function in window well</technical_language>

Target:
private <M> OperatorImpl<M, ?> createOperatorImpl(MessageStreamImpl<M> source, OperatorSpec operatorSpec, Config config, TaskContext context) { if (operatorSpec instanceof StreamOperatorSpec) { StreamOperatorSpec<M, ?> streamOpSpec = (StreamOperatorSpec<M, ?>) operatorSpec; return new StreamOperatorImpl<>(streamOpSpec, source, config, context); } else if (operatorSpec instanceof SinkOperatorSpec) { return new SinkOperatorImpl<>((SinkOperatorSpec<M>) operatorSpec, config, context); } else if (operatorSpec instanceof WindowOperatorSpec) { return new WindowOperatorImpl((WindowOperatorSpec<M, ?, ?>) operatorSpec, clock); } else if (operatorSpec instanceof PartialJoinOperatorSpec) { return new PartialJoinOperatorImpl<>((PartialJoinOperatorSpec) operatorSpec, source, config, context); } throw new IllegalArgumentException( String.format("Unsupported OperatorSpec: %s", operatorSpec.getClass().getName())); }
Source:
<code>public Object decode(Response response, Type type) throws IOException { if (response.status() == 404) return Util.emptyValueOf(type); if (response.body() == null) return null; if (!(type instanceof Class)) { throw new UnsupportedOperationException( "JAXB only supports decoding raw types. Found " + type); } try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setFeature("<LINK_1>", false); saxParserFactory.setFeature("<LINK_3>", false); saxParserFactory.setFeature("<LINK_0>", false); saxParserFactory.setFeature("<LINK_2>", false); Source source = new SAXSource(saxParserFactory.newSAXParser().getXMLReader(), new InputSource(response.body().asInputStream())); Unmarshaller unmarshaller = jaxbContextFactory.createUnmarshaller((Class) type); return unmarshaller.unmarshal(source); } catch (JAXBException e) { throw new DecodeException(e.toString(), e); } catch (ParserConfigurationException e) { throw new DecodeException(e.toString(), e); <START> } catch (SAXNotRecognizedException e) { <END> throw new DecodeException(e.toString(), e); } catch (SAXNotSupportedException e) { throw new DecodeException(e.toString(), e); } catch (SAXException e) { throw new DecodeException(e.toString(), e); } finally { if (response.body() != null) { response.body().close(); } } }</code><technical_language>SAXNotRecognizedException SAXNotSupportedException subtypes of SAXException, catches imports removed (to reduce clutter)</technical_language>

Target:
public Object decode(Response response, Type type) throws IOException { if (response.status() == 404) return Util.emptyValueOf(type); if (response.body() == null) return null; if (!(type instanceof Class)) { throw new UnsupportedOperationException( "JAXB only supports decoding raw types. Found " + type); } try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setFeature("<LINK_1>", false); saxParserFactory.setFeature("<LINK_3>", false); saxParserFactory.setFeature("<LINK_0>", false); saxParserFactory.setFeature("<LINK_2>", false); Source source = new SAXSource(saxParserFactory.newSAXParser().getXMLReader(), new InputSource(response.body().asInputStream())); Unmarshaller unmarshaller = jaxbContextFactory.createUnmarshaller((Class) type); return unmarshaller.unmarshal(source); } catch (JAXBException e) { throw new DecodeException(e.toString(), e); } catch (ParserConfigurationException e) { throw new DecodeException(e.toString(), e); } catch (SAXException e) { throw new DecodeException(e.toString(), e); } finally { if (response.body() != null) { response.body().close(); } } }
Source:
<code>public void endpointTest() throws Exception { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(URL); try { int statusCode = client.executeMethod(method); assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode); String response = method.getResponseBodyAsString(); assertTrue("Unexpected response body", response.contains("hello world")); <START> assertTrue(checkLogMessage(2000, "SLF4J: Failed to load class")); <END> } finally { method.releaseConnection(); } }</code><technical_language>decide 2000? assuming some sort of time limit if find message 2 seconds test passes? test class loaded successfully in a more explicit manner, for is Log message is logged</technical_language>

Target:
public void endpointTest() throws Exception { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(URL); try { int statusCode = client.executeMethod(method); assertEquals("HTTP GET failed", HttpStatus.SC_OK, statusCode); String response = method.getResponseBodyAsString(); assertTrue("Unexpected response body", response.contains("hello world")); assertTrue(checkLogMessage(2000, "SLF4J: Failed to load class")); assertFalse(checkLogMessage(2000, "SLF4J Logger is ready for messages.")); } finally { method.releaseConnection(); } }
Source:
<code>public void run() { try { jmsClientConnector.send(message, null, jmsProperties); } catch (ClientConnectorException e) { <START> log.error("Error sending the JMS message: ", e); <END> } }</code><technical_language>add message log</technical_language>

Target:
public void run() { try { jmsClientConnector.send(message, null, jmsProperties); } catch (ClientConnectorException e) { log.error("Error sending JMS message: ", e); } }
Source:
<code>public void testIterableSliceExpectedSingle() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); String data = "aaaaaaaaaabbbbbbbbbbccccc"; Payload payload = new InputStreamPayload(new ByteArrayInputStream(data.getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 25).iterator(); assertTrue(iter.hasNext(), "Not enough results"); <START> assertEquals(new String(ByteStreams.toByteArray(iter.next())), data); <END> assertFalse(iter.hasNext()); }</code><technical_language>TestNG ["actual, expected"](<LINK_0> (as here) "expected, actual"</technical_language>

Target:
public void testIterableSliceExpectedSingle() throws IOException { PayloadSlicer slicer = new BasePayloadSlicer(); String contents = "aaaaaaaaaabbbbbbbbbbccccc"; Payload payload = new InputStreamPayload(new ByteArrayInputStream(contents.getBytes(Charsets.US_ASCII))); Iterator<Payload> iter = slicer.slice(payload, 25).iterator(); assertTrue(iter.hasNext(), "Not enough results"); assertEquals(new String(ByteStreams.toByteArray(iter.next())), contents); assertFalse(iter.hasNext()); }
Source:
<code>public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws CryptoException { setName(name); setIsSecure(isSecure); if (!isSecure && StringUtils.isNotEmpty(encryptedValue)) { errors().add(ENCRYPTEDVALUE, "You may specify encrypted value only when option 'secure' is true."); } if (StringUtils.isNotEmpty(value) && StringUtils.isNotEmpty(encryptedValue)) { addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError(ENCRYPTEDVALUE, "You may only specify `value` or `encrypted_value`, not both!"); } <START> if (StringUtils.isNotEmpty(encryptedValue)) { <END> setEncryptedValue(encryptedValue); } if (isSecure) { if (value != null) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } } else { setValue(new VariableValueConfig(value)); } }</code><technical_language>[StringUtils.isNotEmpty](<LINK_0> return true for " " strings well. [StringUtils.isNotBlank](<LINK_1> a choice. WDYT</technical_language>

Target:
public void deserialize(String name, String value, boolean isSecure, String encryptedValue) throws CryptoException { setName(name); setIsSecure(isSecure); if (!isSecure && StringUtils.isNotBlank(encryptedValue)) { errors().add(ENCRYPTEDVALUE, "You may specify encrypted value only when option 'secure' is true."); } if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(encryptedValue)) { addError("value", "You may only specify `value` or `encrypted_value`, not both!"); addError(ENCRYPTEDVALUE, "You may only specify `value` or `encrypted_value`, not both!"); } if (StringUtils.isNotBlank(encryptedValue)) { setEncryptedValue(encryptedValue); } if (isSecure) { if (value != null) { setEncryptedValue(new EncryptedVariableValueConfig(new GoCipher().encrypt(value))); } } else { setValue(new VariableValueConfig(value)); } }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(this) <START> .add("_bytes", _bytes) <END> .add("_scheduledFor", _scheduledFor) .add("_generatedAt", _generatedAt) .add("_format", _format) .toString(); }</code><technical_language>include underscores in field names</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("bytes", _bytes) .add("scheduledFor", _scheduledFor) .add("generatedAt", _generatedAt) .add("format", _format) .toString(); }
Source:
<code>public void testIsConditionValidWhenHeaderIsValid() throws Exception { final ConditionCol52 conditionCol1 = fakeConditionCol52("header1"); final ConditionCol52 conditionCol2 = fakeConditionCol52("header2"); final Validator validator = new Validator(fakeCompositeColumn(conditionCol1, conditionCol2)); <START> assertFalse(validator.isConditionValid(conditionCol2)); <END> }</code><technical_language>In context of GUVNOR-2821 I expect assertTrue here, please update fakeConditionCol52 method achieve this? if point</technical_language>

Target:
public void testIsConditionValidWhenHeaderIsValid() throws Exception { final ConditionCol52 conditionCol1 = fakeConditionCol52("header1"); final ConditionCol52 conditionCol2 = fakeConditionCol52("header2"); final Validator validator = new Validator(fakeCompositeColumn(conditionCol1, conditionCol2)); assertTrue(validator.isConditionValid(conditionCol2)); }
Source:
<code>private void closeProducer(final long timeout, final TimeUnit timeUnit) { if (producer != null) { final Thread closeThread = new Log4jThread(new Runnable() { @Override public void run() { if (producer != null) { producer.close(); } } }, "KafkaManager-CloseThread"); closeThread.setDaemon(true); closeThread.start(); try { closeThread.join(timeUnit.toMillis(timeout)); <START> } catch (final InterruptedException ignore) { <END> } } }</code><technical_language>reset interrupt flag catching this</technical_language>

Target:
private void closeProducer(final long timeout, final TimeUnit timeUnit) { if (producer != null) { final Thread closeThread = new Log4jThread(new Runnable() { @Override public void run() { if (producer != null) { producer.close(); } } }, "KafkaManager-CloseThread"); closeThread.setDaemon(true); closeThread.start(); try { closeThread.join(timeUnit.toMillis(timeout)); } catch (final InterruptedException ignore) { Thread.currentThread().interrupt(); } } }
Source:
<code>public void testGetCustomPeriod404() throws InterruptedException, ParseException { server.enqueue( new MockResponse().setResponseCode(404)); GenericDateQueryOptions options = new GenericDateQueryOptions(); String startStr = "11-11-2012"; String endStr = "11-11-2013"; DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date end = dateFormat.parse(endStr); Date start = dateFormat.parse(startStr); options.CustomPeriod(start, end); MonitoringCenter result = monitoringCenterApi().get("serverId", options); assertEquals(result, null); assertEquals(server.getRequestCount(), 1); <START> assertSent(server, "GET", "/monitoring_center/serverId?period=CUSTOM&start_date=" + URLEncoder.encode(FormatDateToISO8601(start)) + "&end_date=" + URLEncoder.encode(FormatDateToISO8601(end))); <END> }</code><technical_language>expected dates</technical_language>

Target:
public void testGetCustomPeriod404() throws InterruptedException, ParseException { server.enqueue( new MockResponse().setResponseCode(404)); GenericDateQueryOptions options = new GenericDateQueryOptions(); String startStr = "11-11-2012"; String endStr = "11-11-2013"; DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date end = dateFormat.parse(endStr); Date start = dateFormat.parse(startStr); options.customPeriod(start, end); MonitoringCenter result = monitoringCenterApi().get("serverId", options); assertEquals(result, null); assertEquals(server.getRequestCount(), 1); assertSent(server, "GET", "/monitoring_center/serverId?period=CUSTOM&start_date=2012-11-11T00%3A00%3A00Z&end_date=2013-11-11T00%3A00%3A00Z"); }
Source:
<code>private Sets.SetView<VariableReferenceExpression> extractInliningTargets(ProjectNode parent, ProjectNode child, Context context) { Set<VariableReferenceExpression> childOutputSet = ImmutableSet.copyOf(child.getOutputVariables()); Map<VariableReferenceExpression, Long> dependencies = parent.getAssignments() .getExpressions().stream() .flatMap(expression -> SymbolsExtractor.extractAllVariable(expression, context.getSymbolAllocator().getTypes()).stream()) .filter(childOutputSet::contains) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); Set<VariableReferenceExpression> constants = dependencies.keySet().stream() .filter(input -> child.getAssignments().get(input) instanceof Literal) .collect(toSet()); Set<VariableReferenceExpression> tryArguments = parent.getAssignments() .getExpressions().stream() .flatMap(expression -> extractTryArguments(expression, context.getSymbolAllocator().getTypes()).stream()) .collect(toSet()); Set<VariableReferenceExpression> singletons = dependencies.entrySet().stream() .filter(entry -> entry.getValue() == 1) .filter(entry -> !tryArguments.contains(entry.getKey())) <START> .filter(entry -> !isIdentity(child.getAssignments(), entry.getKey())) END> .map(Map.Entry::getKey) .collect(toSet()); return Sets.union(singletons, constants); }</code><technical_language>space is needed "//". do linter capture IIRC</technical_language>

Target:
private Sets.SetView<VariableReferenceExpression> extractInliningTargets(ProjectNode parent, ProjectNode child, Context context) { Set<VariableReferenceExpression> childOutputSet = ImmutableSet.copyOf(child.getOutputVariables()); Map<VariableReferenceExpression, Long> dependencies = parent.getAssignments() .getExpressions() .stream() .map(OriginalExpressionUtils::castToExpression) .flatMap(expression -> SymbolsExtractor.extractAll(expression).stream()) .map(symbol -> variable(symbol.getName(), context.getSymbolAllocator().getTypes().get(symbol))) .filter(childOutputSet::contains) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); Set<VariableReferenceExpression> constants = dependencies.keySet().stream() .filter(input -> castToExpression(child.getAssignments().get(input)) instanceof Literal) .collect(toSet()); Set<VariableReferenceExpression> tryArguments = parent.getAssignments() .getExpressions().stream() .flatMap(expression -> extractTryArguments(castToExpression(expression), context.getSymbolAllocator().getTypes()).stream()) .collect(toSet()); Set<VariableReferenceExpression> singletons = dependencies.entrySet().stream() .filter(entry -> entry.getValue() == 1) .filter(entry -> !tryArguments.contains(entry.getKey())) .filter(entry -> !isIdentity(child.getAssignments(), entry.getKey())) .map(Map.Entry::getKey) .collect(toSet()); return Sets.union(singletons, constants); }
Source:
<code>protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { JdbcSchema jdbc = (JdbcSchema) db; SystemConfig sc = db.systemConfig().get(new SystemConfig.Key()); Statement s = jdbc.getConnection().createStatement(); try { ResultSet r; r = s.executeQuery("SELECT name FROM projects WHERE project_id = 0"); try { if (!r.next()) { throw new OrmException("Cannot read old wild project"); } sc.wildProjectName = new Project.NameKey(r.getString(1)); } finally { r.close(); } if (jdbc.getDialect() instanceof DialectMySQL) { try { s.execute("DROP FUNCTION nextval_project_id"); } catch (SQLException se) { <START> ui.message("Warning: could not delete function nextval_project_id"); <END> } } else if (jdbc.getDialect() instanceof DialectH2) { s.execute("ALTER TABLE projects DROP CONSTRAINT" + " IF EXISTS CONSTRAINT_F3"); } } finally { s.close(); } db.systemConfig().update(Collections.singleton(sc)); }</code><technical_language>Style-nit: I prefer "warning: ...". more consistent report "error: ..." "fatal: ..." in command line based code</technical_language>

Target:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { JdbcSchema jdbc = (JdbcSchema) db; SystemConfig sc = db.systemConfig().get(new SystemConfig.Key()); Statement s = jdbc.getConnection().createStatement(); try { ResultSet r; r = s.executeQuery("SELECT name FROM projects WHERE project_id = 0"); try { if (!r.next()) { throw new OrmException("Cannot read old wild project"); } sc.wildProjectName = new Project.NameKey(r.getString(1)); } finally { r.close(); } if (jdbc.getDialect() instanceof DialectMySQL) { try { s.execute("DROP FUNCTION nextval_project_id"); } catch (SQLException se) { ui.message("warning: could not delete function nextval_project_id"); } } else if (jdbc.getDialect() instanceof DialectH2) { s.execute("ALTER TABLE projects DROP CONSTRAINT" + " IF EXISTS CONSTRAINT_F3"); } } finally { s.close(); } db.systemConfig().update(Collections.singleton(sc)); }
Source:
<code>protected Map<Locator, List<IMetric>> generateEnumForTenants() throws Exception { Map<Locator, List<IMetric>> locatorToMetrics = new HashMap<Locator, List<IMetric>>(); long startTime = System.currentTimeMillis(); <START> final Locator locator1 = Locator.createLocatorFromPathComponents(TENANT1, "my", "enum", "values"); <END> final Locator locator2 = Locator.createLocatorFromPathComponents(TENANT2, "my", "enum", "values"); List<IMetric> metrics = new ArrayList<IMetric>(); PreaggregatedMetric metric = getEnumMetric(locator1, startTime - DELTA_MS); metrics.add(metric); locatorToMetrics.put(locator1, metrics); metric = getEnumMetric(locator2, startTime); metrics = new ArrayList<IMetric>(); metrics.add(metric); locatorToMetrics.put(locator2, metrics); MetadataCache.getInstance().put(locator1, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator1, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); MetadataCache.getInstance().put(locator2, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator2, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); return locatorToMetrics; }</code><technical_language>put test name in metric name</technical_language>

Target:
protected Map<Locator, List<IMetric>> generateEnumForTenants() throws Exception { Map<Locator, List<IMetric>> locatorToMetrics = new HashMap<Locator, List<IMetric>>(); long startTime = System.currentTimeMillis(); final Locator locator1 = Locator.createLocatorFromPathComponents(TENANT1, getClass().getSimpleName(), "my", "enum", "values"); final Locator locator2 = Locator.createLocatorFromPathComponents(TENANT2, getClass().getSimpleName(), "my", "enum", "values"); List<IMetric> metrics = new ArrayList<IMetric>(); PreaggregatedMetric metric = getEnumMetric(locator1, startTime - DELTA_MS); metrics.add(metric); locatorToMetrics.put(locator1, metrics); metric = getEnumMetric(locator2, startTime); metrics = new ArrayList<IMetric>(); metrics.add(metric); locatorToMetrics.put(locator2, metrics); MetadataCache.getInstance().put(locator1, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator1, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); MetadataCache.getInstance().put(locator2, MetricMetadata.TYPE.name().toLowerCase(), null); MetadataCache.getInstance().put(locator2, MetricMetadata.ROLLUP_TYPE.name().toLowerCase(), RollupType.ENUM.toString()); return locatorToMetrics; }
Source:
<code>private String getCrlFilePath() { String filePath = config.getString(ConfigProperties.CRL_FILE_PATH); if (filePath == null) { <START> throw new IseException("CRL file path not defined in config file"); <END> } return filePath; }</code><technical_language>IseException is a REST exception. throw a ConfigurationException instead</technical_language>

Target:
private String getCrlFilePath() throws ConfigurationException { String filePath = config.getString(ConfigProperties.CRL_FILE_PATH); if (filePath == null) { throw new ConfigurationException("CRL file path not defined in config file"); } return filePath; }
Source:
<code>public PapyrusEditorFixture openTable(IMultiDiagramEditor editor, final String name) { activate(editor); try { ModelSet modelSet = ServiceUtils.getInstance().getModelSet(editor.getServicesRegistry()); PapyrusNattableModel notation = (PapyrusNattableModel) modelSet.getModel(PapyrusNattableModel.MODEL_ID); Table table = notation.getTable(name); ServiceUtils.getInstance().getIPageManager(editor.getServicesRegistry()).openPage(table); flushDisplayEvents(); <START> activateDiagram(editor, <END> name); } catch (Exception e) { throw new IllegalStateException("Cannot initialize test", e); } return this; }</code><technical_language>this activateTable(...)</technical_language>

Target:
public PapyrusEditorFixture openTable(IMultiDiagramEditor editor, final String name) { activate(editor); try { ModelSet modelSet = ServiceUtils.getInstance().getModelSet(editor.getServicesRegistry()); PapyrusNattableModel notation = (PapyrusNattableModel) modelSet.getModel(PapyrusNattableModel.MODEL_ID); Table table = notation.getTable(name); ServiceUtils.getInstance().getIPageManager(editor.getServicesRegistry()).openPage(table); flushDisplayEvents(); activateTable(editor, name); } catch (Exception e) { throw new IllegalStateException("Cannot initialize test", e); } return this; }
Source:
<code>private void analyzeReplStatus(ASTNode ast) throws SemanticException { initReplStatus(ast); String dbNameOrPattern = replScope.getDbName(); String replLastId = getReplStatus(dbNameOrPattern); prepareReturnValues(Collections.singletonList(replLastId), "last_repl_id#string"); setFetchTask(createFetchTask("last_repl_id#string")); <START> LOG.debug("ReplicationSemanticAnalyzer.analyzeReplStatus: writing repl.last.id={} out to {}", <END> replLastId, ctx.getResFile(), conf); }</code><technical_language>do want print full conf ? if want provide a String representation of additional placeholder in message put values</technical_language>

Target:
private void analyzeReplStatus(ASTNode ast) throws SemanticException { initReplStatus(ast); String dbNameOrPattern = replScope.getDbName(); String replLastId = getReplStatus(dbNameOrPattern); prepareReturnValues(Collections.singletonList(replLastId), "last_repl_id#string"); setFetchTask(createFetchTask("last_repl_id#string")); LOG.debug("ReplicationSemanticAnalyzer.analyzeReplStatus: writing repl.last.id={} out to using configuration {}", replLastId, ctx.getResFile(), conf); }
Source:
<code><START> protected static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, <END> KeyManagerFactory kmf, String keyStore) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf, keyStore); }</code><technical_language>@SplotyCode this package-private remove @deprecated tag</technical_language>

Target:
static KeyManagerFactory buildKeyManagerFactory(File certChainFile, File keyFile, String keyPassword, KeyManagerFactory kmf, String keyStore) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, CertificateException, KeyException, IOException { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } return buildKeyManagerFactory(certChainFile, algorithm, keyFile, keyPassword, kmf, keyStore); }
Source:
<code>public CqlResult execute_cql3_query(ByteBuffer query, Compression compression, ConsistencyLevel consistency) <START> throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, <END> TException { return checkLimitAndCall(() -> super.execute_cql3_query(query, compression, consistency)); }</code><technical_language>prefer serializing if avoid</technical_language>

Target:
public CqlResult execute_cql3_query(ByteBuffer query, Compression compression, ConsistencyLevel consistency) throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException { qosClient.checkLimit(); CqlResult cqlResult = delegate.execute_cql3_query(query, compression, consistency); recordBytesRead(ThriftObjectSizeUtils.getCqlResultSize(cqlResult)); return cqlResult; }
Source:
<code>public void updateAvailableUserActions(GameBean game) throws GameException { <START> boolean isMandatory = false; <END> List<String> actionsList = new ArrayList<String>(); List<GameUserActions> actionCode = new ArrayList<GameUserActions>(); switch (game.getStage()) { case PREPARATION: List<List<String>> initialBuildingsSet = getInitialBuildingsSetFromJson(game.getInitialBuildingsSet()); for (GameUserBean gameUser : game.getGameUsers()) { if (gameUser.getMoveOrder() == game.getCurrentMove()) { actionCode = getActionCodeInPreparationStage(game, initialBuildingsSet); } if (!actionCode.isEmpty()) { actionsList.add("{\"code\": \"" + actionCode.get(0).toString() + "\", \"params\": {}}"); gameUser.setAvailableActions("{\"list\": [" + actionsList.get(0) + "], \"isMandatory\": true}"); } else { gameUser.setAvailableActions("{\"list\": [], \"isMandatory\": false}"); } actionCode.clear(); actionsList.clear(); } break; case MAIN: for (GameUserBean gameUser : game.getGameUsers()) { if (gameUser.getMoveOrder() == game.getCurrentMove()) { gameUser.setAvailableActions("{\"list\": [], \"isMandatory\": false}"); } else { gameUser.setAvailableActions("{\"list\": [], \"isMandatory\": false}"); } } break; default: log.debug("Cannot recognize current game stage: {}", game.getStage()); throw new GameException(ERROR_CODE_ERROR); } }</code><technical_language>deleted</technical_language>

Target:
public void updateAvailableUserActions(GameBean game) throws GameException { switch (game.getStage()) { case PREPARATION: preparationStageUtil.updateAvailableUserActions(game); break; case MAIN: break; default: log.debug("Cannot recognize current game stage: {}", game.getStage()); throw new GameException(ERROR_CODE_ERROR); } }
Source:
<code>public void testSimpleJoin() throws InterruptedException { m_rejoinLog.info("testSimpleJoin"); long[] seeds = new long[] {0L, 0L, 0L, 0L, 0L}; final int clusterSize = 5; final int killSize = 2; constructCluster(clusterSize, seeds); while (!getNodesInState(NodeState.START).isEmpty()) { Thread.sleep(50); } <START> FuzzTestState state = new FuzzTestState(0L, m_nodes.keySet()); <END> int nextid = clusterSize; for (int i = 0; i < 8; ++i) { for (int k = 0; k < killSize; ++k){ if ((k % 2) == 1) { state.killRandomLink(); } else { state.killRandomNode(); } } state.setUpExpectations(); state.expect(); state.pruneDeadNodes(); int nodes2join = clusterSize - m_nodes.size(); for (int j = 0; j < nodes2join; j++) { int rejoinHostId = nextid++; state.joinNode(rejoinHostId, 0L); } state.settleMesh(); } }</code><technical_language>0L seed for FuzzTestState always</technical_language>

Target:
public void testSimpleJoin() throws InterruptedException { m_rejoinLog.info("testSimpleJoin"); long[] seeds = new long[] {0L, 0L, 0L, 0L, 0L}; final int clusterSize = 5; final int killSize = 2; constructCluster(clusterSize, seeds); while (!getNodesInState(NodeState.START).isEmpty()) { Thread.sleep(50); } long seed = System.currentTimeMillis(); System.out.println("Fuzz State Seed: " + seed); FuzzTestState state = new FuzzTestState(seed, m_nodes.keySet()); int nextid = clusterSize; for (int i = 0; i < 8; ++i) { for (int k = 0; k < killSize; ++k){ if ((k % 2) == 1) { state.killRandomLink(); } else { state.killRandomNode(); } } state.setUpExpectations(); state.expect(); state.pruneDeadNodes(); int nodes2join = clusterSize - m_nodes.size(); for (int j = 0; j < nodes2join; j++) { int rejoinHostId = nextid++; state.joinNode(rejoinHostId, 0L); } state.settleMesh(); } }
Source:
<code>public void handleMessage(Message msg) { try { if (msg.arg2 > INTERNALLY_RESERVED_COMMAND_MAX_USED && msg.arg2 <= INTERNALLY_RESERVED_COMMAND_MAX) { throw new RuntimeException("ReplicationService received an EXTRA_COMMAND " + "using an id in the range reserved for internal use. Custom commands " + "must" + <START> " use an id above " + INTERNALLY_RESERVED_COMMAND_MAX); <END> } switch (msg.arg2) { case COMMAND_START_REPLICATION: startReplications(); break; case COMMAND_STOP_REPLICATION: stopReplications(); break; default: break; } } finally { Intent intent = msg.getData().getParcelable(EXTRA_INTENT); WakefulBroadcastReceiver.completeWakefulIntent(intent); notifyOperationStarted(msg.arg2); } }</code><technical_language>prefer combine this previous line</technical_language>

Target:
public void handleMessage(Message msg) { try { if (msg.arg2 > INTERNALLY_RESERVED_COMMAND_MAX_USED && msg.arg2 <= INTERNALLY_RESERVED_COMMAND_MAX) { throw new RuntimeException("ReplicationService received an EXTRA_COMMAND " + "using an id in the range reserved for internal use. Custom commands " + "must use an id above " + INTERNALLY_RESERVED_COMMAND_MAX); } switch (msg.arg2) { case COMMAND_START_REPLICATION: startReplications(); break; case COMMAND_STOP_REPLICATION: stopReplications(); break; default: break; } } finally { Intent intent = msg.getData().getParcelable(EXTRA_INTENT); WakefulBroadcastReceiver.completeWakefulIntent(intent); notifyOperationStarted(msg.arg2); } }