auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { if (crlByUrlEnabled && crlLocationUrl != null && crlLocationUrl.startsWith(HTTPS)) { try { SecureCxfClientFactory cxfClientFactory = factory.getSecureCxfClientFactory(crlLocationUrl, WebClient.class); WebClient client = cxfClientFactory.getWebClient(); Response response = client.get(); try (ByteArrayInputStream inputStream = IOUtils.loadIntoBAIS((InputStream) response.getEntity())) { File crlFile; byte[] buffer = new byte[inputStream.available()]; int read = inputStream.read(buffer); if (read > 0) { String localCrlPath; if (Strings.fromByteArray(buffer).contains("-----BEGIN")) { localCrlPath = crlFileLocation + PEM_CRL; crlFile = new File(crlFileLocation + PEM_CRL); } else { localCrlPath = crlFileLocation + DEM_CRL; crlFile = new File(localCrlPath); } OutputStream outStream = new FileOutputStream(crlFile); outStream.write(buffer); SecurityLogger.audit( "Copied the content of the CRl at to the local CRL at {}.", crlLocationUrl, localCrlPath); setCrlFileLocationInPropertiesFile(localCrlPath); } } } catch (IOException e) { LOGGER.warn("Unable to copy CRL to local CRL."); } } else { LOGGER.warn("No/bad response"); } }

Target:
public synchronized void run() { if (!crlByUrlEnabled || crlLocationUrl == null) { return; } if (!crlLocationUrl.startsWith(HTTPS)) { postErrorEvent("The provided URL was not an HTTPS URL."); return; } Object entity = getRemoteCrl(); if (!(entity instanceof InputStream)) { postErrorEvent("Unable to download the remote CRL."); return; } FileBackedOutputStream fileBackedOutputStream = null; try { ByteSource byteSource; try (InputStream entityStream = (InputStream) entity) { fileBackedOutputStream = new FileBackedOutputStream(FILE_BACKED_STREAM_THRESHOLD); IOUtils.copy(entityStream, fileBackedOutputStream); fileBackedOutputStream.close(); byteSource = fileBackedOutputStream.asByteSource(); } File crlFile = getCrlFile(byteSource); if (!crlIsValid(byteSource)) { postErrorEvent("An error occurred while validating the CRL."); return; } writeCrlToFile(byteSource, crlFile); } catch (IOException e) { LOGGER.warn("Unable to copy CRL to local CRL. {}", e.getMessage()); postErrorEvent("An error occurred while downloading the CRL."); } finally { if (fileBackedOutputStream != null) { try { fileBackedOutputStream.reset(); } catch (IOException e) { LOGGER.warn("Error occurred while deleting the temporary file. {}", e.getMessage()); } } } }
Source:
public T create(CreationalContext<T> creationalContext) { T instance = getProducer().produce(creationalContext); getProducer().inject(instance, creationalContext); if (!hasPostConstructCallback || beanManager.isContextActive(RequestScoped.class)) { getProducer().postConstruct(instance); } else { RequestContext context = getUnboundRequestContext(); try { context.activate(); FastEvent.of(Object.class, beanManager, Initialized.Literal.REQUEST).fire(this.getId()); getProducer().postConstruct(instance); } finally { FastEvent.of(Object.class, beanManager, BeforeDestroyed.Literal.REQUEST).fire(this.getId()); context.invalidate(); context.deactivate(); FastEvent.of(Object.class, beanManager, Destroyed.Literal.REQUEST).fire(this.getId()); } } return instance; }

Target:
public T create(CreationalContext<T> creationalContext) { T instance = getProducer().produce(creationalContext); getProducer().inject(instance, creationalContext); if (!hasPostConstructCallback || beanManager.isContextActive(RequestScoped.class)) { getProducer().postConstruct(instance); } else { RequestContext context = getUnboundRequestContext(); try { context.activate(); beanManager.fireRequestContextInitialized(getId()); getProducer().postConstruct(instance); } finally { beanManager.fireRequestContextBeforeDestroyed(getId()); context.invalidate(); context.deactivate(); beanManager.fireRequestContextDestroyed(getId()); } } return instance; }
Source:
protected void onManagedUpdate(float pSecondsElapsed) { Ship deadShip = null; for (Ship ship: ships) { Sprite shipSprite = ship.getSprite(); if (ship.getDirection() && (shipSprite.getX() < ( activity.getCamera().getXMin() - shipSprite.getWidth()))) { ship.missionDone(); Log.d("1log", "kill"); deadShip = ship; } else if (!ship.getDirection() && shipSprite.getX() > (activity.getCamera().getXMax())) { ship.missionDone(); Log.d("1log", "kill"); deadShip = ship; } } if (deadShip != null) { ships.remove(deadShip); } super.onManagedUpdate(pSecondsElapsed); }

Target:
protected void onManagedUpdate(float pSecondsElapsed) { Ship deadShip = null; for (Ship ship: ships) { Sprite shipSprite = ship.getSprite(); float maxX = activity.getCamera().getXMax(); float minX = activity.getCamera().getXMin() - shipSprite.getWidth(); if ( ship.getDirection() && (shipSprite.getX() < minX) || !ship.getDirection() && (shipSprite.getX() > maxX)) { ship.missionDone(); Log.d("1log", "kill"); deadShip = ship; } } if (deadShip != null) { ships.remove(deadShip); } super.onManagedUpdate(pSecondsElapsed); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean exceptionOccurred = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(); parameters.setSessionId(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.SESSION_ENGINE_SESSION_ID_KEY); } else { request.setAttribute(FiltersHelper.Constants.REQUEST_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } } catch (Exception ex) { exceptionOccurred = true; String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (!exceptionOccurred) { chain.doFilter(request, response); } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = true; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryParametersBase parameters = new VdcQueryParametersBase(engineSession); VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, parameters); if (!returnValue.getSucceeded()) { httpSession.removeAttribute(FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); } else { request.setAttribute(FiltersHelper.Constants.REQUEST_USER_KEY, returnValue.getReturnValue()); } } finally { ctx.close(); } } } } catch (Exception ex) { doFilter = false; String msg = String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage()); log.error(msg); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }
Source:
public static int countEachProduct(final MagicAmount amount, final MagicAmount eachCount, final MagicEvent event) { if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.XCost) { return eachCount.getPositiveAmount(event); } else if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.NegXCost) { return -eachCount.getPositiveAmount(event); } else { return amount.getPositiveAmount(event) * eachCount.getPositiveAmount(event); } }

Target:
public static int countEachProduct(final MagicAmount amount, final MagicAmount eachCount, final MagicEvent event) { if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.XCost) { return eachCount.getAmount(event); } else if (eachCount != MagicAmountFactory.One && amount == MagicAmountFactory.NegXCost) { return -eachCount.getAmount(event); } else { return amount.getAmount(event) * eachCount.getAmount(event); } }
Source:
void pageHeader() { doc.println("---"); doc.println("title: Client Properties"); doc.println("category: development"); doc.println("order: 9"); doc.println("---\n"); doc.println("<!-- WARNING: Do not edit this file. It is a generated file that is copied from Accumulo build (from core/target/generated-docs) -->\n"); doc.println("Below are properties set in `accumulo-client.properties` that configure Accumulo clients:\n"); doc.println("| Property | Default value | Description |"); doc.println("|----------|---------------|-------------|"); }

Target:
void pageHeader() { doc.println("---"); doc.println("title: Client Properties"); doc.println("category: development"); doc.println("order: 9"); doc.println("---\n"); doc.println("<!-- WARNING: Do not edit this file. It is a generated file that is copied from Accumulo build (from core/target/generated-docs) -->"); doc.println("<!-- Generated by : " + getClass().getName() + " -->\n"); doc.println("Below are properties set in `accumulo-client.properties` that configure Accumulo clients. All properties have been part of the API since 2.0.0 (unless otherwise specified):\n"); doc.println("| Property | Default value | Since | Description |"); doc.println("|----------|---------------|-------|-------------|"); }
Source:
public BigDecimal getValue() { return value; }

Target:
public BigDecimal getValue() { return this.value; }
Source:
private ObjectStream getPrologRules() { try { Repository git = gitMgr.openRepository(getProject().getNameKey()); try { ObjectId config = git.resolve(GitRepositoryManager.REF_CONFIG); ObjectId rules = git.resolve(config.getName() + ":submit_rules.pl"); if (rules == null) { return null; } ObjectLoader ldr = git.open(rules); if (ldr.getType() != Constants.OBJ_BLOB) { return null; } return ldr.openStream(); } finally { git.close(); } } catch (IOException gone) { return null; } }

Target:
private ObjectStream getPrologRules() throws IOException{ Repository git = gitMgr.openRepository(getProject().getNameKey()); try { ObjectId config = getConfig().getRevision(); ObjectId rules = git.resolve(config.getName() + ":rules.pl"); if (rules == null) { return null; } ObjectLoader ldr = git.open(rules); if (ldr.getType() != Constants.OBJ_BLOB) { return null; } return ldr.openStream(); } finally { git.close(); } }
Source:
private boolean changePushNotificationsStatus(IQ iq) throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException { final XMPPConnection connection = connection(); IQ responseIQ = null; PacketCollector responseIQCollector = connection.createPacketCollector(new IQReplyFilter(iq, connection)); try { connection.sendStanza(iq); responseIQ = responseIQCollector.nextResultOrThrow(); } finally { responseIQCollector.cancel(); } return responseIQ.getType() != Type.error; }

Target:
private boolean changePushNotificationsStatus(IQ iq) throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException { final XMPPConnection connection = connection(); IQ responseIQ = connection.createPacketCollectorAndSend(iq).nextResultOrThrow(); return responseIQ.getType() != Type.error; }
Source:
protected static String upload(TaskListener listener, CloudBlockBlob blob, FilePath src) throws StorageException, IOException, InterruptedException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); long startTime = System.currentTimeMillis(); try (InputStream inputStream = src.read()){ DigestInputStream digestInputStream = new DigestInputStream(inputStream, md); blob.upload(digestInputStream, src.length(), null, getBlobRequestOptions(), Utils.updateUserAgent()); } long endTime = System.currentTimeMillis(); listener.getLogger().println("Uploaded blob with uri " + blob.getUri() + " in " + getTime(endTime - startTime)); return DatatypeConverter.printHexBinary(md.digest()); }

Target:
protected static String upload(TaskListener listener, CloudBlockBlob blob, FilePath src) throws StorageException, IOException, InterruptedException { MessageDigest md = DigestUtils.getMd5Digest(); long startTime = System.currentTimeMillis(); try (InputStream inputStream = src.read(); DigestInputStream digestInputStream = new DigestInputStream(inputStream, md)){ blob.upload(digestInputStream, src.length(), null, getBlobRequestOptions(), Utils.updateUserAgent()); } long endTime = System.currentTimeMillis(); listener.getLogger().println("Uploaded blob with uri " + blob.getUri() + " in " + getTime(endTime - startTime)); return DatatypeConverter.printHexBinary(md.digest()); }
Source:
public void setUp() { mocks = new IotaTestMocks(); bridge = mocks.getBridge(); }

Target:
public void setUp() { mocks = new IotaTestMocks(); bridge = mocks.initializeBridge(); }
Source:
public String raw() { return title + "\n" + abstractContent; }

Target:
public String raw() { return raw; }
Source:
private void notifyStart(AbstractBuild build, String message) { AbstractProject<?, ?> project = build.getProject(); AbstractBuild<?, ?> lastBuild = project.getLastBuild(); if (lastBuild != null) { AbstractBuild<?, ?> previousBuild = lastBuild.getPreviousCompletedBuild(); if (previousBuild == null) { getSlack(build).publish(message, "good", listener); } else { getSlack(build).publish(message, getBuildColor(previousBuild), listener); } } else { getSlack(build).publish(message, "good", listener); } }

Target:
private void notifyStart(AbstractBuild build, String message) { AbstractProject<?, ?> project = build.getProject(); AbstractBuild<?, ?> lastBuild = project.getLastBuild(); if (lastBuild != null) { AbstractBuild<?, ?> previousBuild = lastBuild.getPreviousCompletedBuild(); if (previousBuild == null) { getSlack(build).publish(message, "good"); } else { getSlack(build).publish(message, getBuildColor(previousBuild)); } } else { getSlack(build).publish(message, "good"); } }
Source:
public static <T> ResolvedObservers<T> of(Set<ObserverMethod<? super T>> observers) { if (observers.isEmpty()) { return (ResolvedObservers<T>) EMPTY; } boolean metadataRequired = false; List<ObserverMethod<? super T>> immediateObservers = new ArrayList<ObserverMethod<? super T>>(); List<ObserverMethod<? super T>> transactionObservers = new ArrayList<ObserverMethod<? super T>>(); for (ObserverMethod<? super T> observer : observers) { if (TransactionPhase.IN_PROGRESS == observer.getTransactionPhase()) { immediateObservers.add(observer); } else { transactionObservers.add(observer); } if (!metadataRequired && Observers.isEventMetadataRequired(observer)) { metadataRequired = true; } } return new ResolvedObservers<T>(immediateObservers, transactionObservers, metadataRequired); }

Target:
public static <T> ResolvedObservers<T> of(Set<ObserverMethod<? super T>> observers) { if (observers.isEmpty()) { return (ResolvedObservers<T>) EMPTY; } boolean metadataRequired = false; List<ObserverMethod<? super T>> immediateObservers = new ArrayList<ObserverMethod<? super T>>(); List<ObserverMethod<? super T>> transactionObservers = new ArrayList<ObserverMethod<? super T>>(); for (ObserverMethod<? super T> observer : observers) { if (TransactionPhase.IN_PROGRESS == observer.getTransactionPhase()) { immediateObservers.add(observer); } else { transactionObservers.add(observer); } if (!metadataRequired && Observers.isEventMetadataRequired(observer)) { metadataRequired = true; } } return new ResolvedObservers<T>(copyOf(immediateObservers), copyOf(transactionObservers), metadataRequired); }
Source:
public void validate_commands_both_dispatched_and_handled() { commandBus.register(createProjectHandler); commandBus.register(new AddTaskDispatcher()); assertAreSupportedCommands(true, CreateProject.class, AddTask.class); }

Target:
public void validate_commands_both_dispatched_and_handled() { commandBus.register(createProjectHandler); commandBus.register(new AddTaskDispatcher()); assertSupported(CreateProject.class, AddTask.class); }
Source:
public static void testGetActivitiesForEntity() throws MambuApiException { System.out.println("\nIn testGetActivitiesForEntity"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 10; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); Class<Client> mambuEntity = Client.class; String entityId = "8ad3e12340719f2b0140878460884524"; List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate, mambuEntity, entityId); if (jsonActivities == null) { System.out.println("Error - API returned NULL for Entity=" + mambuEntity.getSimpleName() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total activities for Entity " + mambuEntity.getSimpleName() + " returned=" + jsonActivities.size() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); String name = jsonActivity.getClientName(); System.out.println(activity.getType() + "\tEntity Name=" + name + "\tID =" + activity.getTransactionId() + "\tNotes=" + activity.getNotes() + "\tTimestamp=" + activity.getTimestamp()); } return; }

Target:
public static void testGetActivitiesForEntity() throws MambuApiException { System.out.println("\nIn testGetActivitiesForEntity"); ActivitiesService activitiesService = MambuAPIFactory.getActivitiesService(); Date toDate = new Date(); long timeNow = toDate.getTime(); int forNumberOfDays = 10; long activiTiesForMsecInterval = 1000 * 60 * 60 * 24 * forNumberOfDays; long timeBefore = timeNow - activiTiesForMsecInterval; Date fromDate = new Date(timeBefore); Class<Client> mambuEntity = Client.class; String entityId = clientKeyWithActivities; List<JSONActivity> jsonActivities = activitiesService.getActivities(fromDate, toDate, mambuEntity, entityId); if (jsonActivities == null) { System.out.println("Error - API returned NULL for Entity=" + mambuEntity.getSimpleName() + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); return; } System.out.println("Total " + jsonActivities.size() + " activities returned for Entity " + mambuEntity.getSimpleName() + " withId= " + entityId + " =" + "\tFrom Date=" + fromDate.toString() + "\tTo Date =" + toDate.toString()); for (JSONActivity jsonActivity : jsonActivities) { Activity activity = jsonActivity.getActivity(); String name = jsonActivity.getClientName(); System.out.println(activity.getType() + "\tEntity Name=" + name + "\tID =" + activity.getTransactionId() + "\tNotes=" + activity.getNotes() + "\tTimestamp=" + activity.getTimestamp()); } }
Source:
private static void cleanExpandDirectory(String jarFile) throws IOException { File directoryToClean; String oneJarExpandDir = System.getProperty(ONEJAR_EXPAND_DIR_PROPERTY); if (oneJarExpandDir == null) { String jar = new File(jarFile).getName().replaceFirst("\\.[^\\.]*$", ""); directoryToClean = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), jar); } else { directoryToClean = new File(oneJarExpandDir); } FileUtils.deleteQuietly(directoryToClean); }

Target:
private void cleanExpandDirectory(String jarFile) { File directoryToClean; String oneJarExpandDir = System.getProperty(ONEJAR_EXPAND_DIR_PROPERTY); if (oneJarExpandDir == null) { String jar = new File(jarFile).getName().replaceFirst(LAST_DOT_AND_AFTER, ""); directoryToClean = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value(), jar); } else { directoryToClean = new File(oneJarExpandDir); } FileUtils.deleteQuietly(directoryToClean); }
Source:
static Cleanable forResultSet(final ResultSet rs) { return () -> rs.close(); }

Target:
static Cleanable forResultSet(final ResultSet rs) { return rs::close; }
Source:
private void validateServiceCatalogEntries(LinkedHashMap endpointConfig) { Map<String, Boolean> productionEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_PRODUCTION_ENDPOINTS); Map<String, Boolean> sandboxEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_SANDBOX_ENDPOINTS); Map<String, Boolean> productionFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_PRODUCTION_FAILOVERS); Map<String, Boolean> sandboxFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_SANDBOX_FAILOVERS); if (!productionEndpointStatus.get("hasEndpoints") && !sandboxEndpointStatus.get("hasEndpoints")) { RestApiUtil.handleBadRequest("At least one endpoint from Production Endpoint or " + "Sandbox Endpoint must be defined.", log); } if (!(productionEndpointStatus.get("validCatalogEndpoints") && sandboxEndpointStatus.get("validCatalogEndpoints") && productionFailoverStatus.get("validCatalogEndpoints") && sandboxFailoverStatus.get("validCatalogEndpoints"))) { RestApiUtil.handleBadRequest("'id' is missing in Service Catalog type endpoints", log); } }

Target:
private void validateServiceCatalogEntries(LinkedHashMap endpointConfig) { Map<String, Boolean> productionEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_PRODUCTION_ENDPOINTS); Map<String, Boolean> sandboxEndpointStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.API_DATA_SANDBOX_ENDPOINTS); Map<String, Boolean> productionFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_PRODUCTION_FAILOVERS); Map<String, Boolean> sandboxFailoverStatus = validateServiceCatalogEndpoint(endpointConfig, APIConstants.ENDPOINT_SANDBOX_FAILOVERS); if (!productionEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_HAS_ENDPOINTS) && !sandboxEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_HAS_ENDPOINTS)) { RestApiUtil.handleBadRequest("At least one endpoint from Production Endpoint or " + "Sandbox Endpoint must be defined.", log); } if (!(productionEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS) && sandboxEndpointStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS) && productionFailoverStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS) && sandboxFailoverStatus.get(APIConstants.API_ENDPOINT_CONFIG_VALID_CATALOG_ENDPOINTS))) { RestApiUtil.handleBadRequest("'id' is missing in Service Catalog type endpoints", log); } }
Source:
public Set<Capability> getCapabilities(FileSystem fs, Path path) throws AccessControlException { if (logger.isDebugEnabled()) logger.debug("path:" + path.toUri().getPath()); DataFileStream<Object> avroDataStream = null; try { avroDataStream = getAvroDataStream(fs, path); Schema schema = avroDataStream.getSchema(); return (schema != null) ? EnumSet.of(Capability.READ, Capability.SCHEMA) : EnumSet.noneOf(Capability.class); } catch (AccessControlException e) { throw e; } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug(path.toUri().getPath() + " is not an avro file."); logger.debug("Error in getting avro schema: " + e.getLocalizedMessage()); } return EnumSet.noneOf(Capability.class); } finally { try { if (avroDataStream != null) { avroDataStream.close(); } } catch (IOException e) { logger.error(e); } } }

Target:
public Set<Capability> getCapabilities(FileSystem fs, Path path) throws AccessControlException { if (logger.isDebugEnabled()) { logger.debug("path:" + path.toUri().getPath()); } DataFileStream<Object> avroDataStream = null; try { avroDataStream = getAvroDataStream(fs, path); Schema schema = avroDataStream.getSchema(); return (schema != null) ? EnumSet.of(Capability.READ, Capability.SCHEMA) : EnumSet.noneOf(Capability.class); } catch (AccessControlException e) { throw e; } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug(path.toUri().getPath() + " is not an avro file."); logger.debug("Error in getting avro schema: ", e); } return EnumSet.noneOf(Capability.class); } finally { try { if (avroDataStream != null) { avroDataStream.close(); } } catch (IOException e) { logger.error(e); } } }
Source:
private static void ensurePositive(float value, String name) { if (value <= 0) { throw new IllegalArgumentException(format("Value of '%s' must be positive.", name)); } }

Target:
private static void ensurePositive(float value, String name) { if (value <= 0) { throw new DeveloperError("Value of '%s' must be positive.", name); } }
Source:
public void setMTUOverrideSupported(boolean mtuOverrideSupported) { if (!mtuOverrideSupported) { getHasMtu().setChangeProhibitionReason(ConstantsManager.getInstance().getMessages() .mtuOverrideNotSupported(getSelectedDc().getcompatibility_version().toString())); getHasMtu().setIsChangable(false); getHasMtu().setEntity(false); } else { if (this.mtuOverrideSupported != mtuOverrideSupported) { initMtu(); } getHasMtu().setIsChangable(true); } this.mtuOverrideSupported = mtuOverrideSupported; }

Target:
public void setMTUOverrideSupported(boolean mtuOverrideSupported) { this.mtuOverrideSupported = mtuOverrideSupported; updateMtuSelectorsVisibility(); }
Source:
void addPredecessor(PhpCfgBlock predecessor) { this.predecessors.add(predecessor); }

Target:
void addPredecessor(PhpCfgBlock predecessor) { predecessors.add(predecessor); }
Source:
private <T, O extends AbstractOptions<O>> Call getFindCoordinatorCall(ConsumerGroupOperationContext<T, O> context, Supplier<Call> nextCall) { return new Call("findCoordinator", context.deadline(), new LeastLoadedNodeProvider()) { @Override FindCoordinatorRequest.Builder createRequest(int timeoutMs) { return new FindCoordinatorRequest.Builder( new FindCoordinatorRequestData() .setKeyType(CoordinatorType.GROUP.id()) .setKey(context.groupId())); } @Override void handleResponse(AbstractResponse abstractResponse) { final FindCoordinatorResponse response = (FindCoordinatorResponse) abstractResponse; if (handleGroupRequestError(response.error(), context.future())) return; context.node(response.node()); runnable.call(nextCall.get(), time.milliseconds()); } @Override void handleFailure(Throwable throwable) { context.future().completeExceptionally(throwable); } }; }

Target:
private <T, O extends AbstractOptions<O>> Call getFindCoordinatorCall(ConsumerGroupOperationContext<T, O> context, Supplier<Call> nextCall) { return new Call("findCoordinator", context.deadline(), new LeastLoadedNodeProvider()) { @Override FindCoordinatorRequest.Builder createRequest(int timeoutMs) { return new FindCoordinatorRequest.Builder( new FindCoordinatorRequestData() .setKeyType(CoordinatorType.GROUP.id()) .setKey(context.groupId())); } @Override void handleResponse(AbstractResponse abstractResponse) { final FindCoordinatorResponse response = (FindCoordinatorResponse) abstractResponse; if (handleGroupRequestError(response.error(), context.future())) return; context.setNode(response.node()); runnable.call(nextCall.get(), time.milliseconds()); } @Override void handleFailure(Throwable throwable) { context.future().completeExceptionally(throwable); } }; }
Source:
public Status scan(final String table, final String startkey, final int recordcount, final Set<String> fields, final Vector<HashMap<String, ByteIterator>> result) { try { if (!COLUMN_FAMILIES.containsKey(table)) { createColumnFamily(table); } final ColumnFamilyHandle cf = COLUMN_FAMILIES.get(table).getHandle(); try(final RocksIterator iterator = rocksDb.newIterator(cf)) { int iterations = 0; for (iterator.seek(startkey.getBytes(UTF_8)); iterator.isValid() && iterations < recordcount; iterator.next()) { final HashMap<String, ByteIterator> values = new HashMap<>(); deserializeValues(iterator.value(), fields, values); result.add(values); iterations++; } } return Status.OK; } catch(final RocksDBException e) { e.printStackTrace(); return Status.ERROR; } }

Target:
public Status scan(final String table, final String startkey, final int recordcount, final Set<String> fields, final Vector<HashMap<String, ByteIterator>> result) { try { if (!COLUMN_FAMILIES.containsKey(table)) { createColumnFamily(table); } final ColumnFamilyHandle cf = COLUMN_FAMILIES.get(table).getHandle(); try(final RocksIterator iterator = rocksDb.newIterator(cf)) { int iterations = 0; for (iterator.seek(startkey.getBytes(UTF_8)); iterator.isValid() && iterations < recordcount; iterator.next()) { final HashMap<String, ByteIterator> values = new HashMap<>(); deserializeValues(iterator.value(), fields, values); result.add(values); iterations++; } } return Status.OK; } catch(final RocksDBException e) { LOGGER.error(e.getMessage(), e); return Status.ERROR; } }
Source:
public void testSourceTopicsWithGlobalTopics() { builder.setApplicationId("X"); builder.addSource(null, "source-1", null, null, null, "topic-1"); builder.addSource(null, "source-2", null, null, null, "topic-2"); builder.addGlobalStore(new MockKeyValueStoreBuilder("global-store", false).withLoggingDisabled(), "globalSource", null, null, null, "globalTopic", "global-processor", new MockProcessorSupplier()); final Pattern expectedPattern = Pattern.compile("topic-1|topic-2"); assertEquals(expectedPattern.pattern(), builder.sourceTopicPattern().pattern()); }

Target:
public void testSourceTopicsWithGlobalTopics() { builder.setApplicationId("X"); builder.addSource(null, "source-1", null, null, null, "topic-1"); builder.addSource(null, "source-2", null, null, null, "topic-2"); builder.addGlobalStore( new MockKeyValueStoreBuilder("global-store", false).withLoggingDisabled(), "globalSource", null, null, null, "globalTopic", "global-processor", new MockProcessorSupplier()); final Pattern expectedPattern = Pattern.compile("topic-1|topic-2"); assertThat(builder.sourceTopicPattern().pattern(), equalTo(expectedPattern.pattern())); }
Source:
private void parse() throws IOException { stream.mark(0); try { final byte[] formatIdentifier = new byte[BPM_IDENTIFIER.length()]; for (int i = 0; i < formatIdentifier.length; i++) { formatIdentifier[i] = parseByte(); } final String identifier = new String(formatIdentifier); setIdentifier(identifier); if (!identifier.equals(BPM_IDENTIFIER)) { throw new PicardException("Invalid identifier '" + identifier + "' for BPM file"); } setFileVersion(parseByte()); if (getFileVersion() != 1) { throw new PicardException("Unknown BPM version (" + getFileVersion() + ")"); } int version = parseInt(); final int versionFlag = 0x1000; if ((version & versionFlag) == versionFlag) { version ^= versionFlag; } if (version > 5 || version < 3) { throw new PicardException("Unsupported BPM version (" + version + ")"); } manifestName = parseString(); if (version > 1) { controlConfig = parseString(); } numLoci = parseInt(); readData(); } finally { stream.close(); } }

Target:
private void parse() throws IOException { try { final byte[] formatIdentifier = new byte[BPM_IDENTIFIER.length()]; for (int i = 0; i < formatIdentifier.length; i++) { formatIdentifier[i] = parseByte(); } final String identifier = new String(formatIdentifier); setIdentifier(identifier); if (!identifier.equals(BPM_IDENTIFIER)) { throw new PicardException("Invalid identifier '" + identifier + "' for BPM file"); } setFileVersion(parseByte()); if (getFileVersion() != 1) { throw new PicardException("Unknown BPM version (" + getFileVersion() + ")"); } int version = parseInt(); final int versionFlag = 0x1000; if ((version & versionFlag) == versionFlag) { version ^= versionFlag; } if (version > 5 || version < 3) { throw new PicardException("Unsupported BPM version (" + version + ")"); } manifestName = parseString(); controlConfig = parseString(); numLoci = parseInt(); readData(); } finally { stream.close(); } }
Source:
private void validateBindArguments(boolean hasPoolQuantities, String poolIdString, Integer quantity, String[] productIds, List<String> fromPools, Date entitleDate, Consumer consumer, boolean async) { short parameters = 0; if (consumer.getType().isType(ConsumerTypeEnum.SHARE) && StringUtils.isBlank(poolIdString)) { throw new BadRequestException(i18n.tr("Share consumers must be bound to a specific pool")); } if (hasPoolQuantities) { parameters++; } if (poolIdString != null) { parameters++; } if (ArrayUtils.isNotEmpty(productIds) || CollectionUtils.isNotEmpty(fromPools) || entitleDate != null) { parameters++; } if (parameters > 1) { throw new BadRequestException(i18n.tr("Cannot bind by multiple parameters.")); } if (hasPoolQuantities) { if (quantity != null) { throw new BadRequestException( i18n.tr("Cannot specify a single quantity when binding a batch of " + " exact pools. Please specify a quantity for each pool")); } else if (!async) { throw new BadRequestException(i18n.tr("Batch bind can only be performed asynchronously")); } } if (poolIdString == null && quantity != null) { throw new BadRequestException(i18n.tr("Cannot specify a quantity when auto-binding.")); } }

Target:
private void validateBindArguments(boolean hasPoolQuantities, String poolIdString, Integer quantity, String[] productIds, List<String> fromPools, Date entitleDate, Consumer consumer, boolean async) { short parameters = 0; if (consumer.isShare() && StringUtils.isBlank(poolIdString) && !hasPoolQuantities) { throw new BadRequestException(i18n.tr("Share consumers must be bound to a specific pool")); } if (hasPoolQuantities) { parameters++; } if (poolIdString != null) { parameters++; } if (ArrayUtils.isNotEmpty(productIds) || CollectionUtils.isNotEmpty(fromPools) || entitleDate != null) { parameters++; } if (parameters > 1) { throw new BadRequestException(i18n.tr("Cannot bind by multiple parameters.")); } if (hasPoolQuantities) { if (quantity != null) { throw new BadRequestException( i18n.tr("Cannot specify a single quantity when binding a batch of " + " exact pools. Please specify a quantity for each pool")); } else if (!async) { throw new BadRequestException(i18n.tr("Batch bind can only be performed asynchronously")); } } if (poolIdString == null && quantity != null) { throw new BadRequestException(i18n.tr("Cannot specify a quantity when auto-binding.")); } }
Source:
public Object evaluate(Object feature) { String arg0; JSONObject arg1; try { arg0 = getExpression(0).evaluate(feature, String.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function mbHas argument #1 - expected type String"); } try { arg1 = getExpression(1).evaluate(feature, JSONObject.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function mbHas argument #0 - expected type JSONObject"); } return arg1.containsKey(arg0); }

Target:
public Object evaluate(Object feature) { String arg0; JSONObject arg1; try { arg0 = getExpression(0).evaluate(feature, String.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function \"has\" argument #1 - expected type String"); } try { arg1 = getExpression(1).evaluate(feature, JSONObject.class); } catch (Exception e) { throw new IllegalArgumentException( "Filter Function problem for function \"has\" argument #0 - expected type JSONObject"); } return arg1.containsKey(arg0); }
Source:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; reversePatchSetOrder = false; showUsernameInReviewCategory = false; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; relativeDateInChangeTable = true; }

Target:
public void resetToDefaults() { maximumPageSize = DEFAULT_PAGESIZE; showSiteHeader = true; useFlashClipboard = true; copySelfOnEmail = false; reversePatchSetOrder = false; showUsernameInReviewCategory = false; downloadUrl = null; downloadCommand = null; dateFormat = null; timeFormat = null; relativeDateInChangeTable = false; }
Source:
public void testGroupImageMessageRequest() { try { Id groupId = new Id(12); Group g = new Group("", groupId, new ArrayList<Id>(), YieldsApplication.getDefaultGroupImage()); Id senderId = new Id(11); String text = "Apple pie is best pie !"; Bitmap newImage = YieldsApplication.getDefaultGroupImage(); ImageContent imageContent = new ImageContent(newImage, text); String imageEncoded = ImageSerialization.serializeImage(newImage, 800); ServerRequest serverRequest = RequestBuilder.nodeMessageRequest(senderId, groupId, Group.GroupVisibility.PRIVATE, imageContent, new Date()); JSONObject json = new JSONObject(serverRequest.message()); assertEquals(json.getString(RequestBuilder.Fields.KIND.getValue()), ServiceRequest.RequestKind.GROUP_MESSAGE.getValue()); assertEquals(json.getJSONObject("metadata").getString("client"), senderId .getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.NID.getValue()), groupId.getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT_TYPE.getValue()), imageContent.getType().toString().toLowerCase()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.TEXT.getValue()), text); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT.getValue()), imageEncoded); } catch (JSONException e) { fail("Request was not built correctly !"); } }

Target:
public void testGroupImageMessageRequest() { try { Id groupId = new Id(12); Group g = new Group("", groupId, new ArrayList<Id>(), YieldsApplication.getDefaultGroupImage()); Id senderId = new Id(11); String text = "Apple pie is best pie !"; Bitmap newImage = YieldsApplication.getDefaultGroupImage(); ImageContent imageContent = new ImageContent(newImage, text); String imageEncoded = ImageSerialization.serializeImage(newImage, ImageSerialization.SIZE_IMAGE); ServerRequest serverRequest = RequestBuilder.nodeMessageRequest(senderId, groupId, Group.GroupVisibility.PRIVATE, imageContent, new Date()); JSONObject json = new JSONObject(serverRequest.message()); assertEquals(json.getString(RequestBuilder.Fields.KIND.getValue()), ServiceRequest.RequestKind.GROUP_MESSAGE.getValue()); assertEquals(json.getJSONObject("metadata").getString("client"), senderId .getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.NID.getValue()), groupId.getId().toString()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT_TYPE.getValue()), imageContent.getType().toString().toLowerCase()); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.TEXT.getValue()), text); assertEquals(json.getJSONObject("message").getString(RequestBuilder.Fields.CONTENT.getValue()), imageEncoded); } catch (JSONException e) { fail("Request was not built correctly !"); } }
Source:
boolean wouldPushProject(Project.NameKey project) { if (projectMatch != null) { if (isRE(projectMatch)) { return (new RegExp(projectMatch, RegExp.NONE)). toAutomaton().run(project.get()); } else if (projectMatch.endsWith("/*")) { return project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1)); } else { return project.get().equals(projectMatch); } } return true; }

Target:
boolean wouldPushProject(Project.NameKey project) { if (projects.length < 1) { return true; } for (final String projectMatch : projects) { if (isRE(projectMatch)) { if ((new RegExp(projectMatch, RegExp.NONE)). toAutomaton().run(project.get())) return true; } else if (projectMatch.endsWith("/*")) { if (project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1))) return true; } else if (project.get().equals(projectMatch)) { return true; } } return false; }
Source:
public void testCount() { SWTBotNatTable nattable = bot.nattable(); assertEquals("Twenty four rows are visible", 24, nattable.rowCount()); assertEquals("Two columns are visible", 2, nattable.columnCount()); assertEquals("Total thirty two rows are created", 32, nattable.preferredRowCount()); assertEquals("Total two columns are created", 2, nattable.preferredColumnCount()); }

Target:
public void testCount() { SWTBotNatTable nattable = bot.nattable(); int rowCount = nattable.rowCount(); int totalRowCount = nattable.preferredRowCount(); assertThat(rowCount, allOf(lessThan(totalRowCount), greaterThanOrEqualTo(14))); assertEquals("Two columns are visible", 2, nattable.columnCount()); assertEquals("Total thirty two rows are created", 32, totalRowCount); assertEquals("Total two columns are created", 2, nattable.preferredColumnCount()); }
Source:
private void addMessageToMap(String classPackageName, IdentifierTree classNameTree) { AnalyzerMessageReporter reporter = (AnalyzerMessageReporter) context; AnalyzerMessage analyzerMessage = reporter.createAnalyzerMessage(this, classNameTree, String.format(MESSAGE_FORMAT, classNameTree)); messagesPerClassPrefix.computeIfAbsent(classPackageName, k -> new ArrayList<>()).add(analyzerMessage); }

Target:
private void addMessageToMap(String classPackageName, IdentifierTree classNameTree) { DefaultJavaFileScannerContext defaultContext = (DefaultJavaFileScannerContext) context; AnalyzerMessage analyzerMessage = defaultContext.createAnalyzerMessage(this, classNameTree, String.format(MESSAGE_FORMAT, classNameTree.name())); messagesPerPackage.computeIfAbsent(classPackageName, k -> new ArrayList<>()).add(analyzerMessage); }
Source:
public String toString() { return "FileWrittenEvent [remoteHandle=" + this.remoteHandle + ", file=" + this.file + ", dataLen=" + this.dataLen + ", cause=" + this.cause + ", clientAddress=" + getSession().getClientAddress() + "]"; }

Target:
public String toString() { return "FileWrittenEvent [remoteHandle=" + this.remoteHandle + ", file=" + this.file + ", dataLen=" + this.dataLen + (this.cause == null ? "" : ", cause=" + this.cause) + ", clientAddress=" + getSession().getClientAddress() + "]"; }
Source:
protected void ExecuteVmCommand() { this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); List<VmNetworkInterface> interfaces = DbFacade.getInstance().getVmNetworkInterfaceDAO() .getAllForVm(getParameters().getVmId()); VmNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface i) { return i.getId().equals(getParameters().getInterfaceId()); } }); if (iface != null) { MacPoolManager.getInstance().freeMac(iface.getMacAddress()); _interfaceName = iface.getName(); String interType = VmInterfaceType.forValue(iface.getType()).getInterfaceTranslation().toString(); if (interType != null) { AddCustomValue("InterfaceType", interType); } } DbFacade.getInstance().getVmNetworkInterfaceDAO().remove(getParameters().getInterfaceId()); DbFacade.getInstance().getVmNetworkStatisticsDAO().remove(getParameters().getInterfaceId()); DbFacade.getInstance() .getVmDeviceDAO() .remove(new VmDeviceId(getParameters().getInterfaceId(), getParameters().getVmId())); setSucceeded(true); }

Target:
protected void ExecuteVmCommand() { this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); List<VmNetworkInterface> interfaces = DbFacade.getInstance().getVmNetworkInterfaceDAO() .getAllForVm(getParameters().getVmId()); VmNetworkInterface iface = LinqUtils.firstOrNull(interfaces, new Predicate<VmNetworkInterface>() { @Override public boolean eval(VmNetworkInterface i) { return i.getId().equals(getParameters().getInterfaceId()); } }); if (iface != null) { MacPoolManager.getInstance().freeMac(iface.getMacAddress()); _interfaceName = iface.getName(); String interType = VmInterfaceType.forValue(iface.getType()).getInterfaceTranslation().toString(); if (interType != null) { AddCustomValue("InterfaceType", interType); } } DbFacade dbFacade = DbFacade.getInstance(); dbFacade.getVmNetworkInterfaceDAO().remove(getParameters().getInterfaceId()); dbFacade.getVmNetworkStatisticsDAO().remove(getParameters().getInterfaceId()); dbFacade.getVmDeviceDAO() .remove(new VmDeviceId(getParameters().getInterfaceId(), getParameters().getVmId())); setSucceeded(true); }
Source:
public Collection<DefaultIssue> create(Component component) { try (DbSession session = dbClient.openSession(false)) { return shortBranchComponentsWithIssues.getUuids(component.getKey()) .stream() .flatMap(uuid -> dbClient.issueDao().selectResolvedOrConfirmedByComponentUuid(session, uuid).stream()) .map(IssueDto::toDefaultIssue) .collect(Collectors.toList()); } }

Target:
public Collection<DefaultIssue> create(Component component) { Set<String> uuids = shortBranchComponentsWithIssues.getUuids(component.getKey()); if (uuids.isEmpty()) { return Collections.emptyList(); } try (DbSession session = dbClient.openSession(false)) { return uuids .stream() .flatMap(uuid -> dbClient.issueDao().selectResolvedOrConfirmedByComponentUuid(session, uuid).stream()) .map(IssueDto::toDefaultIssue) .collect(Collectors.toList()); } }
Source:
public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } if (dataNodeRemoteReplicaInfosPerDC.size() == 0) { logger.warn("Number of Datacenters to replicate from is 0, not starting any replica threads"); return; } assignReplicasToThreadPool(); for (List<ReplicaThread> replicaThreads : replicaThreadPools.values()) { for (ReplicaThread thread : replicaThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting replica thread " + thread.getName()); replicaThread.start(); } } replicationMetrics.trackLiveThreadsCount(replicaThreadPools, dataNodeId.getDatacenterName()); this.scheduler.schedule("replica token persistor", persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication"); } }

Target:
public void start() throws ReplicationException { try { for (String mountPath : partitionGroupedByMountPath.keySet()) { readFromFileAndPersistIfNecessary(mountPath); } if (dataNodeRemoteReplicaInfosPerDC.size() == 0) { logger.warn("Number of Datacenters to replicate from is 0, not starting any replica threads"); return; } assignReplicasToThreadPool(); replicationMetrics.trackLiveThreadsCount(replicaThreadPools, dataNodeId.getDatacenterName()); for (List<ReplicaThread> replicaThreads : replicaThreadPools.values()) { for (ReplicaThread thread : replicaThreads) { Thread replicaThread = Utils.newThread(thread.getName(), thread, false); logger.info("Starting replica thread " + thread.getName()); replicaThread.start(); } } this.scheduler.schedule("replica token persistor", persistor, replicationConfig.replicationTokenFlushDelaySeconds, replicationConfig.replicationTokenFlushIntervalSeconds, TimeUnit.SECONDS); } catch (IOException e) { logger.error("IO error while starting replication"); } }
Source:
public static ByteBuffer deepCloneBuffer(ByteBuffer buffer) { int offset = buffer.position(); int size = buffer.remaining(); byte[] duplicate = new byte[size]; for (int i = 0; i < size; i++) { duplicate[i] = buffer.get(i + offset); } return ByteBuffer.wrap(duplicate); }

Target:
private static ByteBuffer deepCloneBuffer(ByteBuffer buffer) { int offset = buffer.position(); int size = buffer.remaining(); byte[] duplicate = new byte[size]; for (int i = 0; i < size; i++) { duplicate[i] = buffer.get(i + offset); } return ByteBuffer.wrap(duplicate); }