auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void checkFeaturesUnset(IdentifiedElement object) { Collection<EStructuralFeature> exceptions = Lists.newArrayList(); Collection<EStructuralFeature> stackOverFlows = Lists.newArrayList(); for (EStructuralFeature f : object.eClass().getEAllStructuralFeatures()) { if (f.isChangeable()) { try { object.eUnset(f); } catch (Exception e) { exceptions.add(f); e.printStackTrace(); } catch (StackOverflowError s) { stackOverFlows.add(f); } } } StringBuilder sb = new StringBuilder(); buildMessage(sb, "Error(s) occured on ", object, exceptions); buildMessage(sb, "StackOverFlow(s) occured on ", object, stackOverFlows); if (sb.length() != 0) { fail(sb.toString()); } }

Target:
private void checkFeaturesUnset(IdentifiedElement object) { Collection<EStructuralFeature> exceptions = Lists.newArrayList(); Collection<EStructuralFeature> stackOverFlows = Lists.newArrayList(); for (EStructuralFeature f : object.eClass().getEAllStructuralFeatures()) { if (f.isChangeable()) { try { object.eUnset(f); } catch (Exception e) { exceptions.add(f); e.printStackTrace(); } catch (StackOverflowError s) { stackOverFlows.add(f); } } } StringBuilder sb = new StringBuilder(); buildMessage(sb, "Error(s) occurred on ", object, exceptions); buildMessage(sb, "StackOverFlow(s) occurred on ", object, stackOverFlows); if (sb.length() != 0) { fail(sb.toString()); } }
Source:
public static GluuConfiguration asGluuConfiguration(OxdServerConfiguration configuration) { try { JsonNode node = configuration.getStorageConfiguration(); if (node != null) { return Jackson2.createJsonMapper().treeToValue(node, GluuConfiguration.class); } } catch (Exception e) { LOG.error("Failed to parse GluuConfiguration.", e); } return new GluuConfiguration(); }

Target:
public static Optional<GluuConfiguration> asGluuConfiguration(OxdServerConfiguration configuration) { try { JsonNode node = configuration.getStorageConfiguration(); if (node != null) { return Optional.ofNullable(Jackson2.createJsonMapper().treeToValue(node, GluuConfiguration.class)); } } catch (Exception e) { LOG.error("Failed to parse GluuConfiguration.", e); } return Optional.empty(); }
Source:
public Stat setData(String path, byte[] data, int version, long zxid, long time) throws KeeperException.NoNodeException { Stat s = new Stat(); DataNode n = nodes.get(path); if (n == null) { throw new KeeperException.NoNodeException(); } byte[] lastdata = null; synchronized (n) { lastdata = n.data; nodes.preChange(path, n); n.data = data; n.stat.setMtime(time); n.stat.setMzxid(zxid); n.stat.setVersion(version); n.copyStat(s); nodes.postChange(path, n); EphemeralType ephemeralType = EphemeralType.get(n.stat.getEphemeralOwner()); if (ephemeralType == EphemeralType.TTL) { TTLNode ttlNode = ttlMap.get(path); ttls.remove(ttlNode); ttlNode.setExpireTime(n.stat.getMtime() + ephemeralType.getValue(n.stat.getEphemeralOwner())); ttlMap.put(path, ttlNode); ttls.add(ttlNode); } } String lastPrefix = getMaxPrefixWithQuota(path); long dataBytes = data == null ? 0 : data.length; if (lastPrefix != null) { this.updateCountBytes(lastPrefix, dataBytes - (lastdata == null ? 0 : lastdata.length), 0); } nodeDataSize.addAndGet(getNodeSize(path, data) - getNodeSize(path, lastdata)); updateWriteStat(path, dataBytes); dataWatches.triggerWatch(path, EventType.NodeDataChanged); return s; }

Target:
public Stat setData(String path, byte[] data, int version, long zxid, long time) throws KeeperException.NoNodeException { Stat s = new Stat(); DataNode n = nodes.get(path); if (n == null) { throw new KeeperException.NoNodeException(); } byte[] lastdata = null; synchronized (n) { lastdata = n.data; nodes.preChange(path, n); n.data = data; n.stat.setMtime(time); n.stat.setMzxid(zxid); n.stat.setVersion(version); n.copyStat(s); nodes.postChange(path, n); EphemeralType ephemeralType = EphemeralType.get(n.stat.getEphemeralOwner()); if (ephemeralType == EphemeralType.TTL) { ttlManager.updateTTL(path, n); } } String lastPrefix = getMaxPrefixWithQuota(path); long dataBytes = data == null ? 0 : data.length; if (lastPrefix != null) { this.updateCountBytes(lastPrefix, dataBytes - (lastdata == null ? 0 : lastdata.length), 0); } nodeDataSize.addAndGet(getNodeSize(path, data) - getNodeSize(path, lastdata)); updateWriteStat(path, dataBytes); dataWatches.triggerWatch(path, EventType.NodeDataChanged); return s; }
Source:
public GoogleCloudStorageOptions build() { GoogleCloudStorageOptions instance = autoBuild(); checkArgument( instance.getMaxBytesRewrittenPerCall() <= 0 || instance.getMaxBytesRewrittenPerCall() % (1024 * 1024) == 0, "maxBytesRewrittenPerCall must be an integral multiple of 1 MiB (1048576), but was: %s", instance.getMaxBytesRewrittenPerCall()); checkArgument( instance.getProxyAddress() != null || (instance.getProxyUsername() == null && instance.getProxyPassword() == null), "if proxyAddress is null then proxyUsername and proxyPassword should be null too"); checkArgument( (instance.getProxyUsername() == null) == (instance.getProxyPassword() == null), "both proxyUsername and proxyPassword should be null or not null together"); checkArgument( instance.getEncryptionAlgorithm() != null || (instance.getEncryptionKey() == null && instance.getEncryptionKeyHash() == null), "encryptionAlgorithm, encryptionKey and encryptionKeyHash should be null or not null" + " together"); return instance; }

Target:
public GoogleCloudStorageOptions build() { GoogleCloudStorageOptions instance = autoBuild(); checkArgument( instance.getMaxBytesRewrittenPerCall() <= 0 || instance.getMaxBytesRewrittenPerCall() % (1024 * 1024) == 0, "maxBytesRewrittenPerCall must be an integral multiple of 1 MiB (1048576), but was: %s", instance.getMaxBytesRewrittenPerCall()); checkArgument( instance.getProxyAddress() != null || (instance.getProxyUsername() == null && instance.getProxyPassword() == null), "if proxyAddress is null then proxyUsername and proxyPassword should be null too"); checkArgument( (instance.getProxyUsername() == null) == (instance.getProxyPassword() == null), "both proxyUsername and proxyPassword should be null or not null together"); checkArgument( isAllEncryptionOptionsSetOrUnset(instance), "encryptionAlgorithm, encryptionKey and encryptionKeyHash should be null or not null" + " together"); return instance; }
Source:
public void testParsingSimpleDoc() throws IOException { try (InputStream irishSBXmlIn = IrishSentenceBankDocumentTest.class.getResourceAsStream("irishsentencebank-sample.xml");) { IrishSentenceBankDocument doc = IrishSentenceBankDocument.parse(irishSBXmlIn); List<IrishSentenceBankDocument.IrishSentenceBankSentence> sents = doc.getSentences(); Assert.assertEquals(2, sents.size()); IrishSentenceBankDocument.IrishSentenceBankSentence sent1 = sents.get(0); IrishSentenceBankDocument.IrishSentenceBankSentence sent2 = sents.get(1); Assert.assertEquals("A Dhia, tá mé ag iompar clainne!", sent1.getOriginal()); IrishSentenceBankDocument.IrishSentenceBankFlex[] flex = sent1.getFlex(); Assert.assertEquals(7, flex.length); Assert.assertEquals("A", flex[0].getSurface()); Assert.assertArrayEquals(new String[]{"a"}, flex[0].getFlex()); IrishSentenceBankDocument.IrishSentenceBankFlex[] flex2 = sent2.getFlex(); Assert.assertEquals("ón", flex2[4].getSurface()); Assert.assertArrayEquals(new String[]{"ó", "an"}, flex2[4].getFlex()); Assert.assertEquals("Excuse me, are you from the stone age?", sent2.getTranslation()); TokenSample ts = sent1.getTokenSample(); Span[] spans = ts.getTokenSpans(); Assert.assertEquals(9, spans.length); Assert.assertEquals(24, spans[7].getStart()); Assert.assertEquals(31, spans[7].getEnd()); Assert.assertEquals("clainne", ts.getText().substring(spans[7].getStart(), spans[7].getEnd())); } }

Target:
public void testParsingSimpleDoc() throws IOException { try (InputStream irishSBXmlIn = IrishSentenceBankDocumentTest.class.getResourceAsStream("irishsentencebank-sample.xml")) { IrishSentenceBankDocument doc = IrishSentenceBankDocument.parse(irishSBXmlIn); List<IrishSentenceBankDocument.IrishSentenceBankSentence> sents = doc.getSentences(); Assert.assertEquals(2, sents.size()); IrishSentenceBankDocument.IrishSentenceBankSentence sent1 = sents.get(0); IrishSentenceBankDocument.IrishSentenceBankSentence sent2 = sents.get(1); Assert.assertEquals("A Dhia, tá mé ag iompar clainne!", sent1.getOriginal()); IrishSentenceBankDocument.IrishSentenceBankFlex[] flex = sent1.getFlex(); Assert.assertEquals(7, flex.length); Assert.assertEquals("A", flex[0].getSurface()); Assert.assertArrayEquals(new String[]{"a"}, flex[0].getFlex()); IrishSentenceBankDocument.IrishSentenceBankFlex[] flex2 = sent2.getFlex(); Assert.assertEquals("ón", flex2[4].getSurface()); Assert.assertArrayEquals(new String[]{"ó", "an"}, flex2[4].getFlex()); Assert.assertEquals("Excuse me, are you from the stone age?", sent2.getTranslation()); TokenSample ts = sent1.getTokenSample(); Span[] spans = ts.getTokenSpans(); Assert.assertEquals(9, spans.length); Assert.assertEquals(24, spans[7].getStart()); Assert.assertEquals(31, spans[7].getEnd()); Assert.assertEquals("clainne", ts.getText().substring(spans[7].getStart(), spans[7].getEnd())); } }
Source:
public void testSeek() { boolean result = fIterator.seek(1L); assertTrue(result); CtfTmfEvent event = fIterator.getCurrentEvent(); assertEquals("sys_socketcall", event.getName()); assertEquals(Long.valueOf(17), event.getContent().getFieldValue(Long.class, "call")); result = fIterator.seek(Long.MAX_VALUE); assertFalse(result); assertNull(fIterator.getCurrentEvent()); assertEquals(0L, fIterator.getCurrentTimestamp()); assertFalse(fIterator.advance()); result = fIterator.seek(new CtfLocationInfo(1332160882440133097L, 0L)); CtfTmfEvent middleEvent = fIterator.getCurrentEvent(); assertNotNull(middleEvent); assertEquals(1332170682440133097L, middleEvent.getTimestamp().toNanos()); assertEquals(1332170682440133097L, fIterator.getCurrentTimestamp()); result = fIterator.seek(CtfLocation.INVALID_LOCATION); assertEquals(event, fIterator.getCurrentEvent()); }

Target:
public void testSeek() { CtfTmfTrace trace = CtfTmfTestTraceUtils.getTrace(CtfTestTrace.TRACE2); try (CtfIterator iterator = (CtfIterator) trace.createIterator()) { assertTrue(iterator.seek(1L)); CtfTmfEvent event = iterator.getCurrentEvent(); assertEquals("sched_stat_runtime", event.getName()); assertEquals(Long.valueOf(2175), event.getContent().getFieldValue(Long.class, "tid")); assertFalse(iterator.seek(Long.MAX_VALUE)); assertNull(iterator.getCurrentEvent()); assertEquals(0L, iterator.getCurrentTimestamp()); assertFalse(iterator.advance()); assertTrue(iterator.seek(new CtfLocationInfo(1331668250328561095L, 0L))); CtfTmfEvent middleEvent = iterator.getCurrentEvent(); assertNotNull(middleEvent); assertEquals(1331668250328561095L, middleEvent.getTimestamp().toNanos()); assertEquals(1331668250328561095L, iterator.getCurrentTimestamp()); assertTrue(iterator.seek(new CtfLocationInfo(1331668247328921944L, 1L))); CtfTmfEvent doubleEvent = iterator.getCurrentEvent(); assertNotNull(doubleEvent); assertEquals(1331668247328921944L, doubleEvent.getTimestamp().toNanos()); assertEquals(1331668247328921944L, iterator.getCurrentTimestamp()); assertEquals("sched_switch", doubleEvent.getName()); assertFalse(iterator.seek(CtfLocation.INVALID_LOCATION)); assertEquals(doubleEvent, iterator.getCurrentEvent()); } trace.dispose(); }
Source:
public void filter(ContainerRequestContext requestContext) throws IOException { final String authorization = requestContext.getHeaderString("Authorization"); final String method = requestContext.getMethod(); String accountId = getAccountId(requestContext); try { rateLimiter.checkRateOf(accountId, method + "-" + authorization, method); } catch (RateLimitException e) { LOGGER.info("Rate limit reached for current service and account [{}]. Sending response '429 Too Many Requests'", accountId); setTooManyRequestsError(); } }

Target:
public void filter(ContainerRequestContext requestContext) throws IOException { final String authorization = requestContext.getHeaderString("Authorization"); final String method = requestContext.getMethod(); String accountId = getAccountId(requestContext); try { rateLimiter.checkRateOf(accountId, method + "-" + authorization, method); } catch (RateLimitException e) { LOGGER.info("Rate limit reached for current service [account - {}, method - {}]. Sending response '429 Too Many Requests'", accountId, method); setTooManyRequestsError(); } }
Source:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { conn = ((JdbcSchema) db).getConnection(); dialect = ((JdbcSchema) db).getDialect(); Map<String, PrimaryKey> corrections = findPKUpdates(); if (corrections.isEmpty()) { return; } ui.message("Wrong Primary Key Column Order Detected"); ui.message("The following tables are affected:"); ui.message(Joiner.on(", ").join(corrections.keySet())); if (ui.yesno(true, "Fix primary keys column order")) { ui.message("fixing primary keys..."); JdbcExecutor executor = new JdbcExecutor(conn); try { for (Map.Entry<String, PrimaryKey> c : corrections.entrySet()) { ui.message(String.format(" table: %s ... ", c.getKey())); recreatePK(executor, c.getKey(), c.getValue(), ui); ui.message("done"); } ui.message("done"); } finally { executor.close(); } } }

Target:
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException { conn = ((JdbcSchema) db).getConnection(); dialect = ((JdbcSchema) db).getDialect(); Map<String, PrimaryKey> corrections = findPKUpdates(); if (corrections.isEmpty()) { return; } ui.message("Wrong Primary Key Column Order Detected"); ui.message("The following tables are affected:"); ui.message(Joiner.on(", ").join(corrections.keySet())); ui.message("fixing primary keys..."); JdbcExecutor executor = new JdbcExecutor(conn); try { for (Map.Entry<String, PrimaryKey> c : corrections.entrySet()) { ui.message(String.format(" table: %s ... ", c.getKey())); recreatePK(executor, c.getKey(), c.getValue(), ui); ui.message("done"); } ui.message("done"); } finally { executor.close(); } }
Source:
public String getName() { return this.id; }

Target:
public String getName() { return this.translation.get(); }
Source:
public WriteResult<org.atlasapi.segment.Segment, org.atlasapi.segment.Segment> migrateLegacySegment(Id legacyId) throws UnresolvedLegacySegmentException { log.trace("Attempting to resolve legacy segment with ID: in Deer first", legacyId); Iterable<Segment> segments = segmentStore.resolveSegments(ImmutableList.of(legacyId)); Optional<Segment> existingSegment = Optional.fromNullable(Iterables.getOnlyElement(segments, null)); if (existingSegment.isPresent()) { log.trace("Legacy segment already present in Deer, returning..."); return WriteResult.<org.atlasapi.segment.Segment, org.atlasapi.segment.Segment>unwritten(existingSegment.get()) .withPrevious(existingSegment.get()) .build(); } org.atlasapi.media.segment.Segment owlSegment = resolveLegacySegment(legacyId); Segment deerSegment = legacySegmentTransformer.createDescribed(owlSegment); return segmentStore.writeSegment(deerSegment); }

Target:
public WriteResult<Segment, Segment> migrateLegacySegment(Id legacyId) throws UnresolvedLegacySegmentException { log.trace("Attempting to resolve legacy segment with ID: in Deer first", legacyId); Iterable<Segment> segments = segmentStore.resolveSegments(ImmutableList.of(legacyId)); Optional<Segment> existingSegment = Optional.fromNullable(Iterables.getOnlyElement(segments, null)); if (existingSegment.isPresent()) { log.trace("Legacy segment already present in Deer, returning..."); return WriteResult.<org.atlasapi.segment.Segment, org.atlasapi.segment.Segment>unwritten(existingSegment.get()) .withPrevious(existingSegment.get()) .build(); } org.atlasapi.media.segment.Segment owlSegment = resolveLegacySegment(legacyId); Segment deerSegment = legacySegmentTransformer.createDescribed(owlSegment); return segmentStore.writeSegment(deerSegment); }
Source:
public void setCorrelationId(String correlationId) { if (correlationId == null) { this.correlationId = Guid.NewGuid().toString(); } else if (correlationId.length() <= 100) { this.correlationId = correlationId; } else { this.correlationId = correlationId.substring(0, 100); } }

Target:
public void setCorrelationId(String correlationId) { this.correlationId = correlationId; }
Source:
private static Method findGetter(String propertyName, Object target) { String capitalized = propertyName.substring(0, 1).toUpperCase(ENGLISH) + propertyName.substring(1); Method getter = findMethod("get" + capitalized, target); if (getter != null && !Modifier.isStatic(getter.getModifiers())) return getter; if (bareNamePropertyMethods) { getter = findMethod(propertyName, target); if (getter != null && !Modifier.isStatic(getter.getModifiers())) return getter; } Method isAccessor = findMethod("is" + capitalized, target); return (isAccessor != null && !Modifier.isStatic(isAccessor.getModifiers())) ? isAccessor: null; }

Target:
private static Method findGetter(String propertyName, Object target) { String capitalized = propertyName.substring(0, 1).toUpperCase(ENGLISH) + propertyName.substring(1); Method getter = findMethod("get" + capitalized, target); if (isValidGetter(getter)) return getter; if (bareNamePropertyMethods) { getter = findMethod(propertyName, target); if (isValidGetter(getter)) return getter; } Method isAccessor = findMethod("is" + capitalized, target); return (isValidGetter(isAccessor)) ? isAccessor: null; }
Source:
protected void publishToMessageProcessor(CarbonMessage cMsg) { if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceRequestReceiving(cMsg); } CarbonMessageProcessor carbonMessageProcessor = HTTPTransportContextHolder.getInstance() .getMessageProcessor(); if (carbonMessageProcessor != null) { try { carbonMessageProcessor.receive(cMsg, new ResponseCallback(this.ctx)); } catch (Exception e) { LOGGER.error("Error while submitting CarbonMessage to CarbonMessageProcessor.", e); } } else { LOGGER.error("Cannot find registered MessageProcessor to forward the message."); } }

Target:
protected void publishToMessageProcessor(CarbonMessage cMsg) { if (HTTPTransportContextHolder.getInstance().getHandlerExecutor() != null) { HTTPTransportContextHolder.getInstance().getHandlerExecutor().executeAtSourceRequestReceiving(cMsg); } CarbonMessageProcessor carbonMessageProcessor = HTTPTransportContextHolder.getInstance() .getMessageProcessor(); if (carbonMessageProcessor != null) { try { carbonMessageProcessor.receive(cMsg, null); } catch (Exception e) { logger.error("Error while submitting CarbonMessage to CarbonMessageProcessor.", e); ctx.channel().close(); } } else { logger.error("Cannot find registered MessageProcessor to forward the message."); ctx.channel().close(); } }
Source:
public Order addTicketToOrder(Long orderId, TicketType type, boolean pickupService, boolean chMember) { Order order = getOrderById(orderId); if (!order.getStatus().equals(OrderStatus.ANONYMOUS) && !order.getStatus().equals(OrderStatus.ASSIGNED)) { throw new ImmutableOrderException(orderId); } if (order.getTickets().size() >= ORDER_LIMIT) { throw new IllegalStateException("Order limit reached"); } Ticket ticket; if (order.getUser() != null) { ticket = ticketService.requestTicketOfType(order.getUser(), type, pickupService, chMember); } else { ticket = ticketService.requestTicketOfType(type, pickupService, chMember); } order.addTicket(ticket); return orderRepository.save(order); }

Target:
public Order addTicketToOrder(Long orderId, TicketType type, boolean pickupService, boolean chMember) { Order order = getOrderById(orderId); if (!(order.getStatus().equals(OrderStatus.ANONYMOUS) || order.getStatus().equals(OrderStatus.ASSIGNED))) { throw new ImmutableOrderException(orderId); } if (order.getTickets().size() >= ORDER_LIMIT) { throw new IllegalStateException("Order limit reached"); } Ticket ticket; if (order.getUser() != null) { ticket = ticketService.requestTicketOfType(order.getUser(), type, pickupService, chMember); } else { ticket = ticketService.requestTicketOfType(type, pickupService, chMember); } order.addTicket(ticket); return orderRepository.save(order); }
Source:
void setCurrentPacket(StreamInputPacketIndexEntry currentPacket) throws CTFReaderException { StreamInputPacketIndexEntry prevPacket = null; fCurrentPacket = currentPacket; if (fCurrentPacket != null) { ByteBuffer bb = null; try { bb = fStreamInputReader.getStreamInput().getByteBufferAt( fCurrentPacket.getOffsetBytes(), (fCurrentPacket.getPacketSizeBits() + 7) / 8); } catch (IOException e) { throw new CTFReaderException(e.getMessage(), e); } fBitBuffer = new BitBuffer(bb); if (fTracePacketHeaderDecl != null) { fCurrentTracePacketHeaderDef = getTracePacketHeaderDefinition(fBitBuffer); } if (fStreamPacketContextDecl != null) { fCurrentStreamPacketContextDef = getStreamPacketContextDefinition(fBitBuffer); if (getCurrentPacket().getTarget() != null) { fCurrentCpu = (int) getCurrentPacket().getTargetId(); } fLostEventsInThisPacket = (int) getCurrentPacket().getLostEvents(); if (fLostEventsInThisPacket != 0) { fHasLost = true; long lostEventsStartTime; int index = fStreamInputReader.getStreamInput().getIndex().getEntries().indexOf(currentPacket); if (index == 0) { lostEventsStartTime = currentPacket.getTimestampBegin() + 1; } else { prevPacket = fStreamInputReader.getStreamInput().getIndex().getEntries().get(index - 1); lostEventsStartTime = prevPacket.getTimestampEnd(); } fLostEventsDuration = Math.abs(lostEventsStartTime - currentPacket.getTimestampBegin()); } } fLastTimestamp = currentPacket.getTimestampBegin(); } else { fBitBuffer = BitBuffer.EMPTY_BITBUFFER; fLastTimestamp = 0; } }

Target:
void setCurrentPacket(StreamInputPacketIndexEntry currentPacket) throws CTFReaderException { StreamInputPacketIndexEntry prevPacket = null; fCurrentPacket = currentPacket; if (fCurrentPacket != null) { ByteBuffer bb = null; try { bb = fStreamInputReader.getStreamInput().getByteBufferAt( fCurrentPacket.getOffsetBytes(), (fCurrentPacket.getPacketSizeBits() + 7) / 8); } catch (IOException e) { throw new CTFReaderException(e.getMessage(), e); } BitBuffer bitBuffer = new BitBuffer(bb); fBitBuffer = bitBuffer; if (fTracePacketHeaderDecl != null) { fCurrentTracePacketHeaderDef = getTracePacketHeaderDefinition(bitBuffer); } if (fStreamPacketContextDecl != null) { fCurrentStreamPacketContextDef = getStreamPacketContextDefinition(bitBuffer); if (getCurrentPacket().getTarget() != null) { fCurrentCpu = (int) getCurrentPacket().getTargetId(); } fLostEventsInThisPacket = (int) getCurrentPacket().getLostEvents(); if (fLostEventsInThisPacket != 0) { fHasLost = true; long lostEventsStartTime; int index = fStreamInputReader.getStreamInput().getIndex().getEntries().indexOf(currentPacket); if (index == 0) { lostEventsStartTime = currentPacket.getTimestampBegin() + 1; } else { prevPacket = fStreamInputReader.getStreamInput().getIndex().getEntries().get(index - 1); lostEventsStartTime = prevPacket.getTimestampEnd(); } fLostEventsDuration = Math.abs(lostEventsStartTime - currentPacket.getTimestampBegin()); } } fLastTimestamp = currentPacket.getTimestampBegin(); } else { fBitBuffer = null; fLastTimestamp = 0; } }
Source:
public static Integer strcmp(String s0, String s1) { return s0.compareTo(s1); }

Target:
public static int strcmp(String s0, String s1) { return s0.compareTo(s1); }
Source:
public void testExecutorsShutDown() throws Exception { Path scanPath = new Path(dir.getAbsolutePath()); mkdirs = fileSys.mkdirs(scanPath); Path[] dirs = new Path[] {scanPath}; final LocatedFileStatusFetcher fetcher = new LocatedFileStatusFetcher(conf, dirs, true, new PathFilter() { @Override public boolean accept(Path path) { return true; } }, true); Thread t = new Thread() { @Override public void run() { try { fetcher.getFileStatuses(); } catch (Exception e) { Assert.assertTrue(e instanceof InterruptedException); } } }; t.start(); Thread.sleep(TIME_FOR_SLEEP / 2); t.interrupt(); t.join(); Assert.assertTrue(fetcher.getListeningExecutorService().isShutdown()); }

Target:
public void testExecutorsShutDown() throws Exception { Path scanPath = new Path(dir.getAbsolutePath()); mkdirs = fileSys.mkdirs(scanPath); Path[] dirs = new Path[] {scanPath}; final LocatedFileStatusFetcher fetcher = new LocatedFileStatusFetcher(conf, dirs, true, new PathFilter() { @Override public boolean accept(Path path) { return true; } }, true); Thread t = new Thread() { @Override public void run() { try { fetcher.getFileStatuses(); } catch (Exception e) { Assert.assertTrue(e instanceof InterruptedException); } } }; t.start(); LATCH.await(); t.interrupt(); t.join(); Assert.assertTrue("The executor service should have been shut down", fetcher.getListeningExecutorService().isShutdown()); }
Source:
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { if (context.isResourceServiceRestartAllowed()) { AccessLogAdd.INSTANCE.performRuntime(context, operation, model); } else { context.revertReloadRequired(); } }

Target:
protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { AccessLogAdd.INSTANCE.performRuntime(context, operation, model); }
Source:
public static void setChromeOptions(WebDriverConfiguration configuration, DesiredCapabilities capabilities) { ChromeOptions chromeOptions = new ChromeOptions(); String browser = configuration.getBrowser().toLowerCase(); if (browser.equals("chromeheadless")) { chromeOptions.addArguments("--headless"); } CapabilitiesOptionsMapper.mapCapabilities(chromeOptions, capabilities, BROWSER_CAPABILITIES); String binary = (String) capabilities.getCapability("chrome.binary"); if (Validate.nonEmpty(binary)) { chromeOptions.setBinary(binary); } capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); String printChromeOptions = (String) capabilities.getCapability(CHROME_PRINT_OPTIONS); if (Validate.nonEmpty(printChromeOptions) && Boolean.valueOf(printChromeOptions.trim())) { try { StringBuffer chromeOptionsLog = new StringBuffer("\n"); chromeOptionsLog.append("======== Chrome options =========").append("\n"); chromeOptionsLog.append(chromeOptions.toJson().toString()).append("\n"); chromeOptionsLog.append("===== End of Chrome options ====="); log.info(chromeOptionsLog.toString()); } catch (IOException e) { log.warning("Something bad happened during printing chrome options: "); log.warning(e.getMessage()); } } }

Target:
public void setChromeOptions(WebDriverConfiguration configuration, DesiredCapabilities capabilities) { ChromeOptions chromeOptions = new ChromeOptions(); String browser = configuration.getBrowser().toLowerCase(); if (browser.equals("chromeheadless")) { chromeOptions.addArguments("--headless"); } CapabilitiesOptionsMapper.mapCapabilities(chromeOptions, capabilities, BROWSER_CAPABILITIES); String binary = (String) capabilities.getCapability("chrome.binary"); if (Validate.nonEmpty(binary)) { chromeOptions.setBinary(binary); } capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); String printChromeOptions = (String) capabilities.getCapability(CHROME_PRINT_OPTIONS); if (Validate.nonEmpty(printChromeOptions) && Boolean.valueOf(printChromeOptions.trim())) { try { StringBuffer chromeOptionsLog = new StringBuffer("\n"); chromeOptionsLog.append("======== Chrome options =========").append("\n"); chromeOptionsLog.append(chromeOptions.toJson().toString()).append("\n"); chromeOptionsLog.append("===== End of Chrome options ====="); log.info(chromeOptionsLog.toString()); } catch (IOException e) { log.warning("Something bad happened during printing chrome options: "); log.warning(e.getMessage()); } } }
Source:
public void setStringValue(BaseElement element, String value) { FeatureMap.Entry extension = extensionOf( DOCUMENT_ROOT__META_DATA, metaDataOf(value)); getExtensionElements(element).add(extension); }

Target:
protected void setStringValue(BaseElement element, String value) { FeatureMap.Entry extension = extensionOf( DOCUMENT_ROOT__META_DATA, metaDataOf(value)); getExtensionElements(element).add(extension); }
Source:
private static HashMap<ResourceType, Double> getResourcePercentage( String val) throws AllocationConfigurationException { HashMap<ResourceType, Double> resourcePercentage = new HashMap<>(); String[] strings = val.split(","); if (strings.length == 1) { double percentage = findPercentage(strings[0], ""); for (ResourceType resourceType: ResourceType.values()) { resourcePercentage.put(resourceType, percentage/100); } } else { double memPercentage = findPercentage(val, "memory"); double vcorePercentage = findPercentage(val, "vcore"); resourcePercentage.put(ResourceType.MEMORY, memPercentage/100); resourcePercentage.put(ResourceType.CPU, vcorePercentage/100); } return resourcePercentage; }

Target:
private static double[] getResourcePercentage( String val) throws AllocationConfigurationException { double[] resourcePercentage = new double[ResourceType.values().length]; String[] strings = val.split(","); if (strings.length == 1) { double percentage = findPercentage(strings[0], ""); for (int i = 0; i < ResourceType.values().length; i++) { resourcePercentage[i] = percentage/100; } } else { resourcePercentage[0] = findPercentage(val, "memory")/100; resourcePercentage[1] = findPercentage(val, "cpu")/100; } return resourcePercentage; }
Source:
protected void executeCommand() { List<Cluster> clusters = getClustersWithOvsSwitchType(getNetwork().getId()); checkValidDefaultProvider(clusters); List<Cluster> clustersWithOVS = getClustersWithValidDefaultProvider(clusters); createListOfClustersByProvider(clustersWithOVS); List<Guid> providerIds = new ArrayList<>(listOfClustersByProvider.keySet()); IntStream.range(0, providerIds.size()) .forEach(i -> runAutodefineForOneProvider(providerIds.get(i), i)); setSucceeded(true); }

Target:
protected void executeCommand() { List<Cluster> clustersWithOvs = getClustersWithOvsSwitchType(getNetwork().getId()); checkValidDefaultProvider(clustersWithOvs); List<Cluster> clustersWithProvider = getClustersWithValidDefaultProvider(clustersWithOvs); createListOfClustersByProvider(clustersWithProvider); List<Guid> providerIds = new ArrayList<>(clustersByProvider.keySet()); IntStream.range(0, providerIds.size()) .forEach(i -> runAutodefineForOneProvider(providerIds.get(i), i)); setSucceeded(true); }
Source:
public ModelAndView contextJSONLD(@RequestParam(value = "callback", required = false) String callback) { String jsonld = null; try { jsonld = com.github.jsonldjava.utils.JsonUtils.toString(jsonldContext); } catch (IOException e) { LOG.error("Error in Json serialization", e); } return JsonUtils.toJson(jsonld, callback); }

Target:
public ModelAndView contextJSONLD(@RequestParam(value = "callback", required = false) String callback) throws IOException { String jsonld = com.github.jsonldjava.utils.JsonUtils.toString(jsonldContext); return JsonUtils.toJson(jsonld, callback); }
Source:
protected Map<Object,Object> buildEntityConfig(Map<?, ?> config) { if (config==null) return ImmutableMap.of(); Map<Object, Object> orig = (Map<Object, Object>)config.get("brooklyn.config"); Map<Object, Object> result = Maps.newLinkedHashMap(); if (orig != null) { for (Map.Entry<?, ?> entry : orig.entrySet()) { Object key = entry.getKey(); if (key instanceof ConfigKey) result.put((ConfigKey)key, entry.getValue()); else if (key instanceof HasConfigKey) result.put((HasConfigKey)key, entry.getValue()); else result.put(ConfigKeys.newConfigKey(Object.class, key.toString()), entry.getValue()); } } return (result == null) ? ImmutableMap.<Object,Object>of() : result; }

Target:
protected Map<Object,Object> buildEntityConfig(Map<?, ?> config) { if (config==null) return ImmutableMap.of(); Map<Object, Object> orig = (Map<Object, Object>)config.get("brooklyn.config"); Map<Object, Object> result = Maps.newLinkedHashMap(); if (orig != null) { for (Map.Entry<?, ?> entry : orig.entrySet()) { Object key = entry.getKey(); if (key instanceof ConfigKey) result.put((ConfigKey)key, entry.getValue()); else if (key instanceof HasConfigKey) result.put((HasConfigKey)key, entry.getValue()); else result.put(ConfigKeys.newConfigKey(Object.class, key.toString()), entry.getValue()); } } return result; }
Source:
public void testGetAll() throws Exception { assertMisses(0); assertHits(0); assert 0 == advanced.getStats().getHits(); assertAttributeValue("HitRatio", 0); cache.put("key", "value"); assertMisses(0); assertHits(0); assertAttributeValue("HitRatio", 0); Set<String> keySet = new HashSet<>(); keySet.add("key"); keySet.add("key1"); advanced.getAll(keySet); assertMisses(1); assertHits(1); assertAttributeValue("HitRatio", 0.5f); }

Target:
public void testGetAll() throws Exception { assertEquals(0, advanced.getStats().getMisses()); assertEquals(0, advanced.getStats().getHits()); String hitRatioString = server.getAttribute(mgmtInterceptor, "HitRatio").toString(); Float hitRatio = Float.parseFloat(hitRatioString); assertEquals(0f, hitRatio); cache.put("key", "value"); assertEquals(0, advanced.getStats().getMisses()); assertEquals(0, advanced.getStats().getHits()); hitRatioString = server.getAttribute(mgmtInterceptor, "HitRatio").toString(); hitRatio = Float.parseFloat(hitRatioString); assertEquals(0f, hitRatio); Set<String> keySet = new HashSet<>(); keySet.add("key"); keySet.add("key1"); advanced.getAll(keySet); assertEquals(1, advanced.getStats().getMisses()); assertEquals(1, advanced.getStats().getHits()); hitRatioString = server.getAttribute(mgmtInterceptor, "HitRatio").toString(); hitRatio = Float.parseFloat(hitRatioString); assertEquals(0.5f, hitRatio); }
Source:
private static MetricRegistry createMetricRegistry() { LOG.info("Creating Metric Registry for Phoenix Global Metrics"); MetricRegistryInfo registryInfo = new MetricRegistryInfo("PHOENIX", "Phoenix Global Metrics", "phoenix", "Phoenix,sub=PHOENIX", true); return MetricRegistries.global().create(registryInfo); }

Target:
private static MetricRegistry createMetricRegistry() { LOG.info("Creating Metric Registry for Phoenix Global Metrics"); MetricRegistryInfo registryInfo = new MetricRegistryInfo("PHOENIX", "Phoenix Client Metrics", "phoenix", "Phoenix,sub=CLIENT", true); return MetricRegistries.global().create(registryInfo); }
Source:
private boolean isSet(ReferenceChange diff, boolean mergeRightToLeft) { if (diff.getKind() != DifferenceKind.CHANGE) { return false; } final EObject container = getContainer(diff, mergeRightToLeft); boolean isSet = false; if (container != null && diff.getReference() != null) { isSet = !ComparisonUtil.isEqualToDefault(container, diff.getReference()); } return isSet; }

Target:
private boolean isSet(ReferenceChange diff, boolean mergeRightToLeft) { if (diff.getKind() != DifferenceKind.CHANGE) { return false; } boolean isSet = false; final Match match = diff.getMatch(); final EObject container; if (diff.getSource() == DifferenceSource.LEFT) { container = match.getLeft(); } else { container = match.getRight(); } if (container == null) { isSet = isRejecting(diff, mergeRightToLeft); } else { if (!ReferenceUtil.safeEIsSet(container, diff.getReference())) { isSet = isRejecting(diff, mergeRightToLeft); } else { if (isRejecting(diff, mergeRightToLeft)) { final EObject originContainer; if (match.getComparison().isThreeWay()) { originContainer = match.getOrigin(); } else if (mergeRightToLeft) { originContainer = match.getRight(); } else { originContainer = match.getLeft(); } isSet = originContainer != null && ReferenceUtil.safeEIsSet(originContainer, diff.getReference()); } else { isSet = true; } } } return isSet; }
Source:
private void initCacheConfig(Map conf) { Preconditions.checkNotNull(conf.get("topology.monitoring.latencies.map.maxSize"), "expected configuration to contain maxSize for latency map."); Preconditions.checkNotNull(conf.get("topology.monitoring.latencies.map.maxTimeSeconds"), "expected configuration to contain maxTimeSeconds for latency map."); Preconditions.checkNotNull(conf.get("topology.monitoring.latencies.map.maxConcurrency"), "expected configuration to contain maxConcurrency for latency map."); maxSize = (long) conf.get("topology.monitoring.latencies.map.maxSize"); maxTime = (long) conf.get("topology.monitoring.latencies.map.maxTimeSeconds"); maxConcurrency = Ints.checkedCast((long) conf.get("topology.monitoring.latencies.map.maxConcurrency")); }

Target:
private void initCacheConfig(Map conf) { Object maxSizeConf = conf.get("topology.monitoring.latencies.map.maxSize"); Object maxTimeConf = conf.get("topology.monitoring.latencies.map.maxTimeSeconds"); Object maxConcurrencyConf = conf.get("topology.monitoring.latencies.map.maxConcurrency"); maxSize = (maxSizeConf == null ? MAX_SIZE_DEFAULT : (long) maxConcurrencyConf); maxTime = (maxTimeConf == null ? MAX_TIME_DEFAULT : (long) maxConcurrencyConf); maxConcurrency = (maxConcurrencyConf == null ? MAX_CONCURRENCY_DEFAULT: Ints.checkedCast((long)maxConcurrencyConf)); }
Source:
Set<String> listFilenames(RepositoryPath path) throws IOException; default Set<String> getEntriesNames(final ArchiveInputStream archiveInputStream) throws IOException { final Set<String> result = new HashSet<>(); ArchiveEntry entry; while ((entry = archiveInputStream.getNextEntry()) != null) { result.add(entry.getName()); } return result; }

Target:
Set<String> listFilenames(RepositoryPath path) throws IOException; default Set<String> getEntryNames(final ArchiveInputStream archiveInputStream) throws IOException { final Set<String> result = new HashSet<>(); ArchiveEntry entry; while ((entry = archiveInputStream.getNextEntry()) != null) { result.add(entry.getName()); } return result; }
Source:
public NonConcurrentSingleton(Recorder recorder) throws InterruptedException { recorder.record(getClass()); LOG.info("Child1 start"); TimeUnit.SECONDS.sleep(1); LOG.info("Child1 end"); }

Target:
public NonConcurrentSingleton(Recorder recorder) throws InterruptedException { recorder.record(getClass()); LOG.info("NonConcurrentSingleton start"); TimeUnit.SECONDS.sleep(1); LOG.info("NonConcurrentSingleton end"); }
Source:
public void createConfigurationSource(String dest) throws FileNotFoundException, UnsupportedEncodingException { StringBuilder source = new StringBuilder(""); source.append(PrivateFunctionalTemplates.include(RuntimeTemplates.RuntimeHeaderName)); source.append(PrivateFunctionalTemplates.include(GenerationNames.FileNames.TypesFilePath)); source.append("\n\n"); List<String> templateParams = new ArrayList<String>(); templateParams.add(ConfiguratedThreadedRuntimeName); source.append(GenerationTemplates.usingTemplateType(RuntimeTemplates.UsingRuntimePtr, RuntimeTemplates.RuntimePtrType, templateParams)); source.append(GenerationTemplates.usingTemplateType(RuntimeTemplates.UsingRuntimeType, RuntimeTemplates.RuntimeInterfaceName, templateParams)); source.append("\n\n"); source.append(GenerationTemplates.putNamespace( FunctionTemplates.simpleFunctionDecl(RuntimeTemplates.UsingRuntimePtr, CreatorFunction) + ";", NamespaceName)); CppExporterUtils.writeOutSource(dest, GenerationTemplates.headerName(ConfigurationFile), CppExporterUtils.format(HeaderTemplates.headerGuard(source.toString(), ConfigurationFile))); CppExporterUtils.writeOutSource(dest, GenerationTemplates.sourceName(ConfigurationFile), CppExporterUtils.format(createDeplyomentFunctionDefinition())); }

Target:
public void createConfigurationSource(String dest) throws FileNotFoundException, UnsupportedEncodingException { StringBuilder source = new StringBuilder(""); source.append(PrivateFunctionalTemplates.include(RuntimeTemplates.RuntimeHeaderName)); source.append(PrivateFunctionalTemplates.include(GenerationNames.FileNames.TypesFilePath)); source.append("\n\n"); List<String> templateParams = new ArrayList<String>(); templateParams.add(ConfiguratedThreadedRuntimeName); source.append(GenerationTemplates.usingTemplateType(RuntimeTemplates.UsingRuntimePtr, RuntimeTemplates.RuntimePtrType, templateParams)); source.append(GenerationTemplates.usingTemplateType(RuntimeTemplates.UsingRuntimeType, RuntimeTemplates.RuntimeInterfaceName, templateParams)); source.append("\n\n"); source.append(GenerationTemplates.putNamespace( FunctionTemplates.simpleFunctionDecl(RuntimeTemplates.UsingRuntimePtr, CreatorFunction) + ";", NamespaceName)); CppExporterUtils.writeOutSource(dest, GenerationTemplates.headerName(ConfigurationFile), CppExporterUtils.format(HeaderTemplates.headerGuard(source.toString(), ConfigurationFile))); CppExporterUtils.writeOutSource(dest, GenerationTemplates.sourceName(ConfigurationFile), CppExporterUtils.format(createDeploymentFunctionDefinition())); }
Source:
public double priceFromCurvesWithZSpread( ResolvedBill bill, LegalEntityDiscountingProvider provider, LocalDate settlementDate, double zSpread, CompoundedRateType compoundedRateType, int periodsPerYear) { ArgChecker.isTrue(settlementDate.isBefore(bill.getNotional().getDate()), "settlement date must be before maturity date"); ArgChecker.isTrue(!settlementDate.isBefore(provider.getValuationDate()), "settlement date must be on or after valuation date"); IssuerCurveDiscountFactors discountFactors = provider.issuerCurveDiscountFactors( bill.getLegalEntityId(), bill.getCurrency()); double dfMaturity = discountFactors.getDiscountFactors() .discountFactorWithSpread(bill.getNotional().getDate(), zSpread, compoundedRateType, periodsPerYear); RepoCurveDiscountFactors discountFactorsRepo = provider.repoCurveDiscountFactors(bill.getSecurityId(), bill.getLegalEntityId(), bill.getCurrency()); double dfRepoSettle = discountFactorsRepo.discountFactor(settlementDate); double price = dfMaturity / dfRepoSettle; return price; }

Target:
public double priceFromCurvesWithZSpread( ResolvedBill bill, LegalEntityDiscountingProvider provider, LocalDate settlementDate, double zSpread, CompoundedRateType compoundedRateType, int periodsPerYear) { ArgChecker.inOrderNotEqual(settlementDate, bill.getNotional().getDate(), "settlementDate", "endDate"); ArgChecker.inOrderOrEqual(provider.getValuationDate(), settlementDate, "valuationDate", "settlementDate"); IssuerCurveDiscountFactors discountFactors = provider.issuerCurveDiscountFactors( bill.getLegalEntityId(), bill.getCurrency()); double dfMaturity = discountFactors.getDiscountFactors() .discountFactorWithSpread(bill.getNotional().getDate(), zSpread, compoundedRateType, periodsPerYear); RepoCurveDiscountFactors discountFactorsRepo = provider.repoCurveDiscountFactors(bill.getSecurityId(), bill.getLegalEntityId(), bill.getCurrency()); double dfRepoSettle = discountFactorsRepo.discountFactor(settlementDate); return dfMaturity / dfRepoSettle; }
Source:
private RequestModelGenerator<?> getTemplateModelGenerator(final Ds3Request ds3Request) { if (isBulkRequest(ds3Request)) { return new BulkRequestGenerator(); } else if (isPhysicalPlacementRequest(ds3Request)) { return new PhysicalPlacementRequestGenerator(); } else if (isCreateObjectRequest(ds3Request)) { return new CreateObjectRequestGenerator(); } else if (isCreateNotificationRequest(ds3Request)) { return new CreateNotificationRequestGenerator(); } else if (isGetNotificationRequest(ds3Request) || isDeleteNotificationRequest(ds3Request)) { return new NotificationRequestGenerator(); } return new BaseRequestGenerator(); }

Target:
private static RequestModelGenerator<?> getTemplateModelGenerator(final Ds3Request ds3Request) { if (isBulkRequest(ds3Request)) { return new BulkRequestGenerator(); } else if (isPhysicalPlacementRequest(ds3Request)) { return new PhysicalPlacementRequestGenerator(); } else if (isCreateObjectRequest(ds3Request)) { return new CreateObjectRequestGenerator(); } else if (isCreateNotificationRequest(ds3Request)) { return new CreateNotificationRequestGenerator(); } else if (isGetNotificationRequest(ds3Request) || isDeleteNotificationRequest(ds3Request)) { return new NotificationRequestGenerator(); } return new BaseRequestGenerator(); }
Source:
private void handleGetContainerAcl(HttpServletResponse response, BlobStore blobStore, String containerName) throws IOException, S3Exception { if (!blobStore.containerExists(containerName)) { throw new S3Exception(S3ErrorCode.NO_SUCH_BUCKET); } response.setCharacterEncoding(UTF_8); try (Writer writer = response.getWriter()) { response.setContentType(XML_CONTENT_TYPE); XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter( writer); xml.writeStartDocument(); xml.writeStartElement("AccessControlPolicy"); xml.writeDefaultNamespace(AWS_XMLNS); writeOwnerStanza(xml); xml.writeStartElement("AccessControlList"); xml.writeStartElement("Grant"); xml.writeStartElement("Grantee"); xml.writeNamespace("xsi", "<LINK_1>"); xml.writeAttribute("xsi:type", "CanonicalUser"); writeSimpleElement(xml, "ID", FAKE_OWNER_ID); writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME); xml.writeEndElement(); writeSimpleElement(xml, "Permission", "FULL_CONTROL"); xml.writeEndElement(); if (ContainerAccess.PUBLIC_READ .equals(blobStore.getContainerAccess(containerName))) { xml.writeStartElement("Grant"); xml.writeStartElement("Grantee"); xml.writeNamespace("xsi", "<LINK_1>"); xml.writeAttribute("xsi:type", "Group"); writeSimpleElement(xml, "URI", "<LINK_0>"); xml.writeEndElement(); writeSimpleElement(xml, "Permission", "READ"); xml.writeEndElement(); } xml.writeEndElement(); xml.writeEndElement(); xml.flush(); } catch (XMLStreamException xse) { throw new IOException(xse); } }

Target:
private void handleGetContainerAcl(HttpServletResponse response, BlobStore blobStore, String containerName) throws IOException, S3Exception { if (!blobStore.containerExists(containerName)) { throw new S3Exception(S3ErrorCode.NO_SUCH_BUCKET); } ContainerAccess access = blobStore.getContainerAccess(containerName); response.setCharacterEncoding(UTF_8); try (Writer writer = response.getWriter()) { response.setContentType(XML_CONTENT_TYPE); XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter( writer); xml.writeStartDocument(); xml.writeStartElement("AccessControlPolicy"); xml.writeDefaultNamespace(AWS_XMLNS); writeOwnerStanza(xml); xml.writeStartElement("AccessControlList"); xml.writeStartElement("Grant"); xml.writeStartElement("Grantee"); xml.writeNamespace("xsi", "<LINK_1>"); xml.writeAttribute("xsi:type", "CanonicalUser"); writeSimpleElement(xml, "ID", FAKE_OWNER_ID); writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME); xml.writeEndElement(); writeSimpleElement(xml, "Permission", "FULL_CONTROL"); xml.writeEndElement(); if (access == ContainerAccess.PUBLIC_READ) { xml.writeStartElement("Grant"); xml.writeStartElement("Grantee"); xml.writeNamespace("xsi", "<LINK_1>"); xml.writeAttribute("xsi:type", "Group"); writeSimpleElement(xml, "URI", "<LINK_0>"); xml.writeEndElement(); writeSimpleElement(xml, "Permission", "READ"); xml.writeEndElement(); } xml.writeEndElement(); xml.writeEndElement(); xml.flush(); } catch (XMLStreamException xse) { throw new IOException(xse); } }
Source:
public ImageData getImageDataFor(ImageDescriptor descriptor) { if (descriptorToImageData.containsKey(descriptor)) { return descriptorToImageData.get(descriptor); } return null; }

Target:
public ImageData getImageDataFor(ImageDescriptor descriptor) { return descriptorToImageData.get(descriptor); }