auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Override public void run(@Nonnull JDefinedClassOrInterface type) throws Exception { if (!(type instanceof JDefinedClass) || TypeToBeEmittedMarker.isToBeEmitted(type.getSuperClass())) { return; } State state = new State(); trackOverridingChains((JDefinedClass) type, state); for (JMethod method : state.effectivelyFinalMethods) { if (!method.isAbstract() && !method.isFinal()) { assert !method.isStatic() && !method.isPrivate() && !(method instanceof JConstructor); EffectivelyFinalMethodMarker.markAsEffectivelyFinal(method); if (!preserveReflections) { method.setFinal(); tracer.getStatistic(METHODS_FINALIZED).incValue(); } } } }

Target:
@Override public void run(@Nonnull JDefinedClassOrInterface type) throws Exception { JClass superClass = type.getSuperClass(); if (!(type instanceof JDefinedClass) || superClass == null || TypeToBeEmittedMarker.isToBeEmitted(superClass)) { return; } State state = new State(); trackOverridingChains((JDefinedClass) type, state); for (JMethod method : state.effectivelyFinalMethods) { if (!method.isAbstract() && !method.isFinal()) { assert !method.isStatic() && !method.isPrivate() && !(method instanceof JConstructor); EffectivelyFinalMethodMarker.markAsEffectivelyFinal(method); if (!preserveReflections) { method.setFinal(); tracer.getStatistic(METHODS_FINALIZED).incValue(); } } } }
Source:
public static int parseSize(final String propertyKey, final String sizeString) { final Matcher matcher = SIZE_REGEX.matcher(sizeString); if (!matcher.matches()) { throw new IllegalArgumentException(String.format(PARSE_SIZE_VALUE_FAILURE_FORMAT, sizeString, propertyKey)); } final int value = Integer.valueOf(matcher.group("value")); final String magnitude = matcher.group("magnitude"); if (magnitude != null) { switch (magnitude) { case "k": return value * 1024; case "m": return value * 1024 * 1024; case "g": return value * 1024 * 1024 * 1024; default: throw new IllegalArgumentException( String.format(PARSE_SIZE_MAGNITUDE_FAILURE_FORMAT, sizeString, propertyKey, magnitude)); } } else { return value; } }

Target:
public static long parseSize(final String propertyKey, final String sizeString) { final char lastCharacter = sizeString.charAt(sizeString.length() - 1); final long value; if (Character.isDigit(lastCharacter)) { return Long.valueOf(sizeString); } else { value = Long.valueOf(sizeString.substring(0, sizeString.length() - 1)); } switch (lastCharacter) { case 'k': case 'K': if (MAX_K_VALUE <= value) { throw new ConfigurationException("Value " + value + lastCharacter + " would overflow maximum long."); } return value * 1024; case 'm': case 'M': if (MAX_M_VALUE <= value) { throw new ConfigurationException("Value " + value + lastCharacter + " would overflow maximum long."); } return value * 1024 * 1024; case 'g': case 'G': if (MAX_G_VALUE <= value) { throw new ConfigurationException("Value " + value + lastCharacter + " would overflow maximum long."); } return value * 1024 * 1024 * 1024; default: throw new ConfigurationException( "Couldn't parse value: " + sizeString + " for property " + propertyKey + ". " + "Trailing character should be one of k, m, or g, but was " + lastCharacter); } }
Source:
private static Map<String, Object> parseArgs(String[] args) throws Exception { if(args.length < 1) { throw new ExitException("Please provide module.", 0); } return new ParametersParser( ExtensionsToolExecutor.class.getResourceAsStream("arguments.properties.in") ).parse(args); }

Target:
private static Map<String, Object> parseArgs(String[] args) throws Exception { if(args.length < 1) { throw new ExitException("Please provide module.", 0); } return new ParametersParser( ExtensionsToolExecutor.class.getResourceAsStream("arguments.properties") ).parse("core", args); }
Source:
public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); }

Target:
public void onReceive(Context context, Intent intent) { ((MainApplication) context.getApplicationContext()).getInjector().injectMembers(this); super.onReceive(context, intent); }
Source:
public static BoolToken matchable(Term subject, Term pattern, TermContext context) { PatternMatcher matcher = new PatternMatcher(context); try { matcher.match(subject, pattern); } catch (PatternMatchingFailure e) { return BoolToken.FALSE; } return BoolToken.TRUE; }

Target:
public static BoolToken matchable(Term subject, Term pattern, TermContext context) { return PatternMatcher.matchable(subject, pattern, context) ? BoolToken.TRUE : BoolToken.FALSE; }
Source:
public void createUnauthorizedEPersonNoAdminRights() throws Exception { context.turnOffAuthorisationSystem(); MetadataFieldRest metadataFieldRest = new MetadataFieldRest(); metadataFieldRest.setElement(ELEMENT); metadataFieldRest.setQualifier(QUALIFIER); metadataFieldRest.setScopeNote(SCOPE_NOTE); String token = getAuthToken(eperson.getEmail(), password); getClient(token) .perform(post("/api/core/metadatafields") .param("schemaId", metadataSchema.getID() + "") .content(new ObjectMapper().writeValueAsBytes(metadataFieldRest)) .contentType(contentType)) .andExpect(status().isForbidden()); }

Target:
public void createUnauthorizedEPersonNoAdminRights() throws Exception { MetadataFieldRest metadataFieldRest = new MetadataFieldRest(); metadataFieldRest.setElement(ELEMENT); metadataFieldRest.setQualifier(QUALIFIER); metadataFieldRest.setScopeNote(SCOPE_NOTE); String token = getAuthToken(eperson.getEmail(), password); getClient(token) .perform(post("/api/core/metadatafields") .param("schemaId", metadataSchema.getID() + "") .content(new ObjectMapper().writeValueAsBytes(metadataFieldRest)) .contentType(contentType)) .andExpect(status().isForbidden()); }
Source:
protected void assertOwnershipAndNonOwnership(Object key, boolean allowL1) { for (Cache cache : caches) { Object keyToBeChecked = cache.getAdvancedCache().getKeyDataConversion().getEncoder().toStorage(key); DataContainer dc = cache.getAdvancedCache().getDataContainer(); InternalCacheEntry ice = dc.get(keyToBeChecked); if (isOwner(cache, keyToBeChecked)) { assertNotNull(ice); assertTrue(ice instanceof ImmortalCacheEntry); } else { if (allowL1) { assertTrue("ice is null or L1Entry", ice == null || ice.isL1Entry()); } else { eventuallyEquals("Fail on non-owner cache " + addressOf(cache) + ": dc.get(" + key + ")", null, () -> dc.get(keyToBeChecked)); } } } }

Target:
protected void assertOwnershipAndNonOwnership(Object key, boolean allowL1) { for (Cache cache : caches) { Object keyToBeChecked = cache.getAdvancedCache().getKeyDataConversion().toStorage(key); DataContainer dc = cache.getAdvancedCache().getDataContainer(); InternalCacheEntry ice = dc.get(keyToBeChecked); if (isOwner(cache, keyToBeChecked)) { assertNotNull(ice); assertTrue(ice instanceof ImmortalCacheEntry); } else { if (allowL1) { assertTrue("ice is null or L1Entry", ice == null || ice.isL1Entry()); } else { eventuallyEquals("Fail on non-owner cache " + addressOf(cache) + ": dc.get(" + key + ")", null, () -> dc.get(keyToBeChecked)); } } } }
Source:
public void run() { if (job == null) { return; } FolderComputation<?> computation = job.getComputation(); long delay = System.currentTimeMillis() - computation.getTimestamp().getTimeInMillis(); if (delay < interval) { return; } job.scheduleBuild(0, new TimerTrigger.TimerTriggerCause()); }

Target:
public void run() { if (job == null) { return; } long now = System.currentTimeMillis(); FolderComputation<?> computation = job.getComputation(); if (computation != null) { long delay = now - computation.getTimestamp().getTimeInMillis(); if (delay < interval) { LOGGER.log(Level.FINE, "Too early to reschedule {0} based on last computation", job); return; } } if (now - lastTriggered < interval) { LOGGER.log(Level.FINE, "Too early to reschedule {0} based on last triggering", job); return; } if (job.scheduleBuild(0, new TimerTrigger.TimerTriggerCause())) { lastTriggered = now; } else { LOGGER.log(Level.WARNING, "Queue refused to schedule {0}", job); } }
Source:
public void recordTermination() { try { throw new RuntimeException(String.format("Termination requested by %s", Thread.currentThread())); } catch (RuntimeException e) { terminatedBy.add(e); } }

Target:
public void recordTermination() { StaplerRequest request = Stapler.getCurrentRequest(); if (request != null) { terminatedBy.add(new TerminationRequest( String.format("Termination requested at %s by %s [id=%d] from HTTP request for %s", new Date(), Thread.currentThread(), Thread.currentThread().getId(), request.getRequestURL() ) )); } else { terminatedBy.add(new TerminationRequest( String.format("Termination requested at %s by %s [id=%d]", new Date(), Thread.currentThread(), Thread.currentThread().getId() ) )); } }
Source:
public void testSetDIOSuccess() throws Exception { ATCommandResponse mockedResponse = Mockito.mock(ATCommandResponse.class); Mockito.when(mockedResponse.getResponseStatus()).thenReturn(ATCommandStatus.OK); Mockito.doReturn(mockedResponse).when(xbeeDevice).sendATCommand((ATCommand)Mockito.any()); try { xbeeDevice.setDIOValue(IOLine.DIO0_AD0, IOValue.HIGH); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } }

Target:
public void testSetDIOSuccess() throws InvalidOperatingModeException, XBeeException { ATCommandResponse mockedResponse = Mockito.mock(ATCommandResponse.class); Mockito.when(mockedResponse.getResponseStatus()).thenReturn(ATCommandStatus.OK); Mockito.doReturn(mockedResponse).when(xbeeDevice).sendATCommand((ATCommand)Mockito.any()); xbeeDevice.setDIOValue(IOLine.DIO0_AD0, IOValue.HIGH); }
Source:
ProxyConfiguration(ProxyAuthenticationType authentication, Proxy proxyAddress, String username, String password) { Objects.requireNonNull(authentication); this.authentication = authentication; this.proxyAddress = proxyAddress; if (username != null && password != null) { this.credentials = new PasswordAuthentication(username, password.toCharArray()); } else { logger.asInformational().log("Username or Password is NULL."); this.credentials = null; } }

Target:
ProxyConfiguration(ProxyAuthenticationType authentication, Proxy proxyAddress, String username, String password) { Objects.requireNonNull(authentication); this.authentication = authentication; this.proxyAddress = proxyAddress; if (username != null && password != null) { this.credentials = new PasswordAuthentication(username, password.toCharArray()); } else { logger.asInformational().log("Username or password is null. Using system-wide authentication."); this.credentials = null; } }
Source:
private void verifyCachesAndGroups(IgniteEx ig) { Map<String, DynamicCacheDescriptor> caches = ig.context().cache().cacheDescriptors(); assertEquals(3, caches.size()); assertTrue(caches.keySet().contains(GridCacheUtils.UTILITY_CACHE_NAME)); assertTrue(caches.keySet().contains(STATIC_CACHE_NAME_0)); assertTrue(caches.keySet().contains(DYNAMIC_CACHE_NAME_0)); Map<Integer, CacheGroupDescriptor> groups = ig.context().cache().cacheGroupDescriptors(); assertEquals(2, groups.size()); boolean defaultGroupFound = false; boolean mixedCachesGroupFound = false; for (CacheGroupDescriptor grpDesc : groups.values()) { if (grpDesc.cacheOrGroupName().equals(GridCacheUtils.UTILITY_CACHE_NAME)) defaultGroupFound = true; else if (grpDesc.cacheOrGroupName().equals(MIXED_CACHES_GROUP_NAME_0)) mixedCachesGroupFound = true; } assertTrue(defaultGroupFound && mixedCachesGroupFound); }

Target:
private void verifyCachesAndGroups(IgniteEx ig) { Map<String, DynamicCacheDescriptor> caches = ig.context().cache().cacheDescriptors(); assertEquals(3, caches.size()); assertTrue(caches.keySet().contains(GridCacheUtils.UTILITY_CACHE_NAME)); assertTrue(caches.keySet().contains(STATIC_CACHE_NAME_0)); assertTrue(caches.keySet().contains(DYNAMIC_CACHE_NAME_0)); Map<Integer, CacheGroupDescriptor> groups = ig.context().cache().cacheGroupDescriptors(); assertEquals(2, groups.size()); boolean defaultGroupFound = false; boolean mixedCachesGroupFound = false; for (CacheGroupDescriptor grpDesc : groups.values()) { if (grpDesc.cacheOrGroupName().equals(GridCacheUtils.UTILITY_CACHE_NAME)) defaultGroupFound = true; else if (grpDesc.cacheOrGroupName().equals(MIXED_CACHES_GROUP_NAME_0)) mixedCachesGroupFound = true; } assertTrue(String.format("Default group found: %b, mixed group found: %b", defaultGroupFound, mixedCachesGroupFound), defaultGroupFound && mixedCachesGroupFound); }
Source:
private static void copyFileFromPackage(final Context context, final int resourceId, final String target) { try { final FileOutputStream outputStream = context.openFileOutput(target, 0); final InputStream inputStream = context.getResources().openRawResource(resourceId); Util.copyStream(inputStream, outputStream); outputStream.flush(); outputStream.close(); inputStream.close(); Lg.i("created ", target); } catch (final FileNotFoundException e) { Lg.ex(e, "FileNotFoundException: failed to create: ", target); } catch (final IOException e) { Lg.ex(e, "IOException: failed to create: ", target); } }

Target:
private static void copyFileFromPackage(final Context context, final int resourceId, final String target) { try { final FileOutputStream outputStream = context.openFileOutput(target, 0); final InputStream inputStream = context.getResources().openRawResource(resourceId); Util.copyStream(inputStream, outputStream); outputStream.flush(); outputStream.close(); inputStream.close(); Lg.i("created ", target); } catch (final IOException e) { Lg.ex(e, "IOException: failed to create: ", target); } }
Source:
public boolean removeRoot(InternalRegion rootRgn) { String regionName = rootRgn.getName(); InternalRegion found = rootRegions.get(regionName); if (found == rootRgn) { InternalRegion previous = rootRegions.remove(regionName); Assert.assertTrue(previous == rootRgn); return true; } return false; }

Target:
public boolean removeRoot(InternalRegion rootRgn) { String regionName = rootRgn.getName(); return rootRegions.remove(regionName, rootRgn); }
Source:
public int purgeBlobs(List<CloudBlobMetadata> blobMetadataList) throws CloudStorageException { int numPurged = 0; for (CloudBlobMetadata blobMetadata : blobMetadataList) { purgeBlob(blobMetadata); numPurged++; } logger.info("Purged blobs", numPurged); return numPurged; }

Target:
public int purgeBlobs(List<CloudBlobMetadata> blobMetadataList) throws CloudStorageException { int numPurged = 0; for (CloudBlobMetadata blobMetadata : blobMetadataList) { if (purgeBlob(blobMetadata)) { numPurged++; } } logger.info("Purged blobs", numPurged); return numPurged; }
Source:
public void coupleMbusDevice(final DeviceMessageMetadata deviceMessageMetadata, final CoupleMbusDeviceRequestData requestData) throws FunctionalException { final String deviceIdentification = deviceMessageMetadata.getDeviceIdentification(); final String mbusDeviceIdentification = requestData.getMbusDeviceIdentification(); LOGGER.debug("coupleMbusDevice for organisationIdentification: for gateway: {}, m-bus device ", deviceMessageMetadata.getOrganisationIdentification(), deviceIdentification, mbusDeviceIdentification); try { final SmartMeter gatewayDevice = this.domainHelperService.findSmartMeter(deviceIdentification); final SmartMeter gasMeterDevice = this.domainHelperService.findSmartMeter(mbusDeviceIdentification); this.checkGasMeter(gasMeterDevice); final MbusChannelElementsDto mbusChannelElementsDto = this.makeMbusChannelElementsDto(gasMeterDevice); final RequestMessage requestMessage = new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), gatewayDevice.getIpAddress(), mbusChannelElementsDto); this.osgpCoreRequestMessageSender.send(requestMessage, deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); } catch (final FunctionalException ex) { throw ex; } }

Target:
public void coupleMbusDevice(final DeviceMessageMetadata deviceMessageMetadata, final CoupleMbusDeviceRequestData requestData) throws FunctionalException { final String deviceIdentification = deviceMessageMetadata.getDeviceIdentification(); final String mbusDeviceIdentification = requestData.getMbusDeviceIdentification(); LOGGER.debug("coupleMbusDevice for organizationIdentification: for gateway: {}, m-bus device ", deviceMessageMetadata.getOrganisationIdentification(), deviceIdentification, mbusDeviceIdentification); try { final SmartMeter gatewayDevice = this.domainHelperService.findSmartMeter(deviceIdentification); final SmartMeter mbusDevice = this.domainHelperService.findSmartMeter(mbusDeviceIdentification); this.checkAndHandleInactiveMbusDevice(mbusDevice); this.checkAndHandleIfGivenMBusAlreadyCoupled(mbusDevice); final MbusChannelElementsDto mbusChannelElementsDto = this.makeMbusChannelElementsDto(mbusDevice); final RequestMessage requestMessage = new RequestMessage(deviceMessageMetadata.getCorrelationUid(), deviceMessageMetadata.getOrganisationIdentification(), deviceMessageMetadata.getDeviceIdentification(), gatewayDevice.getIpAddress(), mbusChannelElementsDto); this.osgpCoreRequestMessageSender.send(requestMessage, deviceMessageMetadata.getMessageType(), deviceMessageMetadata.getMessagePriority(), deviceMessageMetadata.getScheduleTime()); } catch (final FunctionalException ex) { throw ex; } }
Source:
public ParsedColInfo toTVE(int indx, int diff) { TupleValueExpression exp = new TupleValueExpression(tableName, tableAlias, columnName, alias, expression, indx); exp.setDifferentiator(diff); expression = exp; return this; }

Target:
public ParsedColInfo toTVE(int indx, int diff) { TupleValueExpression exp = new TupleValueExpression(m_tableName, m_tableAlias, m_columnName, m_alias, m_expression, indx); exp.setDifferentiator(diff); m_expression = exp; return this; }
Source:
public SolNames() { planets = new ArrayList<String>(); systems = new ArrayList<String>(); final Set<ResourceUrn> planetNameConfigs = Assets.getAssetHelper().list(Json.class, "[a-zA-Z0-9]*:planetNamesConfig"); for (ResourceUrn planetNameConfig : planetNameConfigs) { planets.addAll(readList(planetNameConfig.toString())); } final Set<ResourceUrn> systemNameConfigs = Assets.getAssetHelper().list(Json.class, "[a-zA-Z0-9]*:systemNamesConfig"); for (ResourceUrn systemNameConfig : systemNameConfigs) { systems.addAll(readList(systemNameConfig.toString())); } }

Target:
public SolNames() { planets = new HashMap<String, ArrayList<String>>(); systems = new ArrayList<String>(); final Set<ResourceUrn> planetNameConfigs = Assets.getAssetHelper().list(Json.class, "[a-zA-Z0-9]*:planetNamesConfig"); for (ResourceUrn planetNameConfig : planetNameConfigs) { planets.put(planetNameConfig.getModuleName().toString(), readList(planetNameConfig.toString())); } final Set<ResourceUrn> systemNameConfigs = Assets.getAssetHelper().list(Json.class, "[a-zA-Z0-9]*:systemNamesConfig"); for (ResourceUrn systemNameConfig : systemNameConfigs) { systems.addAll(readList(systemNameConfig.toString())); } }
Source:
public CombinedConfiguration loadDefaultConfiguration() throws ConfigurationException { final URL configUrl; String name = System.getProperty(CONFIG_URL); if (name != null) { try { configUrl = new URL(name); } catch (MalformedURLException e) { throw new ConfigurationException("Invalid value of '" + name + "' for '" + CONFIG_URL + "'. Must be a valid URL."); } } else { File configFile = new File(configDir, "ambra.xml"); try { configUrl = configFile.toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return loadConfiguration(configUrl); }

Target:
public CombinedConfiguration loadDefaultConfiguration() throws ConfigurationException { final URL configUrl; String configUrlProperty = System.getProperty(CONFIG_URL_PROPERTY_NAME); if (configUrlProperty != null) { try { configUrl = new URL(configUrlProperty); } catch (MalformedURLException e) { throw new ConfigurationException("Invalid value of '" + configUrlProperty + "' for '" + CONFIG_URL_PROPERTY_NAME + "'. Must be a valid URL."); } } else { File configFile = new File(configDir, "ambra.xml"); try { configUrl = configFile.toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } } return loadConfiguration(configUrl); }
Source:
public Consumer createConsumer(Processor processor) throws Exception { return new TelegramConsumer(this, processor); }

Target:
public Consumer createConsumer(Processor processor) throws Exception { TelegramConsumer consumer = new TelegramConsumer(this, processor); configureConsumer(consumer); return consumer; }
Source:
public void loadCommand(HttpServletRequest request, HttpSession session) { try { this.validate(); scheme = request.getScheme(); serverPort = request.getServerPort(); serverName = request.getServerName(); contextPath = request.getContextPath(); isSecure = request.isSecure(); String coreAsString = request.getParameter("idCoreFacility"); if (coreAsString != null && coreAsString.length() > 0) { try { idCoreFacility = Integer.valueOf(coreAsString); } catch(NumberFormatException ex) { idCoreFacility = null; } } else { idCoreFacility = null; } } catch (Exception e) { log.error(e.getClass().toString() + ": " , e); e.printStackTrace(); } }

Target:
public void loadCommand(HttpServletRequest request, HttpSession session) { try { this.validate(); scheme = request.getScheme(); serverPort = request.getServerPort(); serverName = request.getServerName(); contextPath = request.getContextPath(); isSecure = request.isSecure(); String coreAsString = request.getParameter("idCoreFacility"); if (coreAsString != null && coreAsString.length() > 0) { try { idCoreFacility = Integer.valueOf(coreAsString); } catch(NumberFormatException ex) { idCoreFacility = null; } } else { idCoreFacility = null; } } catch (Exception e) { LOG.error(e.getClass().toString() + ": " , e); } }
Source:
private void processTuple(Object in) { if (!inputClass.isAssignableFrom(in.getClass())) { throw new RuntimeException( "Unexpected tuple received. Received class: " + in.getClass() + ". Expected class: " + inputClass.getClass()); } Object out; try { out = outputClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Failed to create new object", e); } for (Map.Entry<PojoUtils.Setter, Expression> entry : transformationMap.entrySet()) { PojoUtils.Setter set = entry.getKey(); Expression expr = entry.getValue(); set.set(out, expr.execute(in)); } output.emit(out); }

Target:
protected void processTuple(Object in) { if (!inputClass.isAssignableFrom(in.getClass())) { throw new RuntimeException( "Unexpected tuple received. Received class: " + in.getClass() + ". Expected class: " + inputClass.getClass()); } Object out; try { out = outputClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Failed to create new object", e); } for (Map.Entry<PojoUtils.Setter, Expression> entry : transformationMap.entrySet()) { PojoUtils.Setter set = entry.getKey(); Expression expr = entry.getValue(); set.set(out, expr.execute(in)); } output.emit(out); }
Source:
public ActionResult execute() throws EntityNotFoundException { try { Part image = extractProfilePicture(); byte[] imageData = new byte[(int) image.getSize()]; try (InputStream is = image.getInputStream()) { is.read(imageData); } String pictureKey = GoogleCloudStorageHelper.writeImageDataToGcs(userInfo.id, imageData); logic.updateStudentProfilePicture(userInfo.id, pictureKey); PostStudentProfileResults dataFormat = new PostStudentProfileResults(Const.StatusMessages.STUDENT_PROFILE_PICTURE_SAVED, pictureKey); return new JsonResult(dataFormat); } catch (IllegalArgumentException | IOException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_BAD_REQUEST); } }

Target:
public ActionResult execute() { try { Part image = req.getPart("studentprofilephoto"); if (image == null) { throw new InvalidHttpRequestBodyException(Const.StatusMessages.STUDENT_PROFILE_NO_PICTURE_GIVEN); } if (image.getSize() > Const.SystemParams.MAX_PROFILE_PIC_SIZE) { throw new InvalidHttpRequestBodyException(Const.StatusMessages.STUDENT_PROFILE_PIC_TOO_LARGE); } if (!image.getContentType().startsWith("image/")) { throw new InvalidHttpRequestBodyException(Const.StatusMessages.STUDENT_PROFILE_NOT_A_PICTURE); } byte[] imageData = new byte[(int) image.getSize()]; try (InputStream is = image.getInputStream()) { is.read(imageData); } String pictureKey = GoogleCloudStorageHelper.writeImageDataToGcs(userInfo.id, imageData); logic.updateOrCreateStudentProfile( StudentProfileAttributes.updateOptionsBuilder(userInfo.id) .withPictureKey(pictureKey) .build()); StudentProfilePictureResults dataFormat = new StudentProfilePictureResults(pictureKey); return new JsonResult(dataFormat); } catch (InvalidParametersException ipe) { throw new InvalidHttpRequestBodyException(ipe.getMessage(), ipe); } catch (ServletException | IOException e) { return new JsonResult(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Source:
private static void wait(WaitForEnum waitFor) throws BlockStoreException { final CountDownLatch latch = new CountDownLatch(1); setup(); switch (waitFor) { case EVER: break; case WALLET_TX: wallet.addEventListener(new AbstractWalletEventListener() { private void handleTx(Transaction tx) { System.out.println(tx.getHashAsString()); latch.countDown(); } @Override public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { super.onCoinsReceived(wallet, tx, prevBalance, newBalance); handleTx(tx); } @Override public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { super.onCoinsSent(wallet, tx, prevBalance, newBalance); handleTx(tx); } }); break; case BLOCK: peers.addDataEventListener(new AbstractPeerDataEventListener() { @Override public void onBlocksDownloaded(Peer peer, AbstractBlockHeader block, int blocksLeft) { if (latch.getCount() == 0) return; System.out.println(block.getHashAsString()); latch.countDown(); } }); break; case BALANCE: if (condition.matchBitcoins(wallet.getBalance(Wallet.BalanceType.ESTIMATED))) { latch.countDown(); break; } wallet.addEventListener(new AbstractWalletEventListener() { @Override public synchronized void onChange() { super.onChange(); saveWallet(walletFile); Coin balance = wallet.getBalance(Wallet.BalanceType.ESTIMATED); if (condition.matchBitcoins(balance)) { System.out.println(balance.toFriendlyString()); latch.countDown(); } } }); break; } if (!peers.isRunning()) peers.startAsync(); try { latch.await(); } catch (InterruptedException e) { } }

Target:
private static void wait(WaitForEnum waitFor) throws BlockStoreException { final CountDownLatch latch = new CountDownLatch(1); setup(); switch (waitFor) { case EVER: break; case WALLET_TX: wallet.addCoinsReceivedEventListener(new WalletCoinsReceivedEventListener() { @Override public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println(tx.getHashAsString()); latch.countDown(); } }); wallet.addCoinsSentEventListener(new WalletCoinsSentEventListener() { @Override public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { System.out.println(tx.getHashAsString()); latch.countDown(); } }); break; case BLOCK: peers.addBlocksDownloadedEventListener(new BlocksDownloadedEventListener() { @Override public void onBlocksDownloaded(Peer peer, AbstractBlock block, int blocksLeft) { if (latch.getCount() == 0) return; System.out.println(block.getHashAsString()); latch.countDown(); } }); break; case BALANCE: if (condition.matchBitcoins(wallet.getBalance(Wallet.BalanceType.ESTIMATED))) { latch.countDown(); break; } final WalletEventListener listener = new WalletEventListener(latch); wallet.addCoinsReceivedEventListener(listener); wallet.addCoinsSentEventListener(listener); wallet.addChangeEventListener(listener); wallet.addReorganizeEventListener(listener); break; } if (!peers.isRunning()) peers.startAsync(); try { latch.await(); } catch (InterruptedException e) { } }
Source:
public int addVariableValue(String value){ variableValues.add(value); return (variableValues.size() - 1); }

Target:
int addVariableValue(String value){ variableValues.add(value); return (variableValues.size() - 1); }
Source:
public QuartzSchedulerService(ZeppelinConfiguration zeppelinConfiguration, Notebook notebook) throws SchedulerException { this.zeppelinConfiguration = zeppelinConfiguration; this.notebook = notebook; this.scheduler = new StdSchedulerFactory().getScheduler(); this.scheduler.start(); Thread loadingNotesThread = new Thread(){ @Override public void run() { LOGGER.info("Starting init cronjobs"); notebook.getNotesInfo().stream() .forEach(entry -> refreshCron(entry.getId())); LOGGER.info("Complete init cronjobs"); } }; loadingNotesThread.setName("Init CronJob Thread"); loadingNotesThread.setDaemon(true); loadingNotesThread.start(); }

Target:
public QuartzSchedulerService(ZeppelinConfiguration zeppelinConfiguration, Notebook notebook) throws SchedulerException { this.zeppelinConfiguration = zeppelinConfiguration; this.notebook = notebook; this.scheduler = new StdSchedulerFactory().getScheduler(); this.scheduler.start(); Thread loadingNotesThread = new Thread(() -> { LOGGER.info("Starting init cronjobs"); notebook.getNotesInfo().stream() .forEach(entry -> refreshCron(entry.getId())); LOGGER.info("Complete init cronjobs"); }); loadingNotesThread.setName("Init CronJob Thread"); loadingNotesThread.setDaemon(true); loadingNotesThread.start(); }
Source:
public static Set<DistributionModuleGroup> getModuleGroups() { Set<DistributionModuleGroup> hs = new HashSet<>(); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(EMR5150Constant.MAPREDUCE_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(EMR5150Constant.HDFS_MODULE_GROUP.getModuleName())); ComponentCondition parquetOutputCondition = new SimpleComponentCondition(new BasicExpression(SqoopConstant.FILE_FORMAT, EqualityOperator.NOT_EQ, SqoopConstant.AVRO_OUTPUT_FORMAT)); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_PARQUET_MODULE_GROUP.getModuleName(), true, parquetOutputCondition)); ComponentCondition avroOutputCondition = new SimpleComponentCondition(new BasicExpression(SqoopConstant.FILE_FORMAT, EqualityOperator.EQ, SqoopConstant.AVRO_OUTPUT_FORMAT)); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_AVRO_MODULE_GROUP.getModuleName(), true, avroOutputCondition)); return hs; }

Target:
public static Set<DistributionModuleGroup> getModuleGroups() { Set<DistributionModuleGroup> hs = new HashSet<>(); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(EMR5150Constant.MAPREDUCE_MODULE_GROUP.getModuleName())); hs.add(new DistributionModuleGroup(EMR5150Constant.HDFS_MODULE_GROUP.getModuleName())); ComponentCondition parquetOutputCondition = new SimpleComponentCondition(new BasicExpression(SqoopConstant.FILE_FORMAT, EqualityOperator.EQ, SqoopConstant.PAQUET_OUTPUT_FORMAT)); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_PARQUET_MODULE_GROUP.getModuleName(), true, parquetOutputCondition)); ComponentCondition textOutputCondition = new SimpleComponentCondition(new BasicExpression(SqoopConstant.FILE_FORMAT, EqualityOperator.EQ, SqoopConstant.TEXT_OUTPUT_FORMAT)); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_TEXT_MODULE_GROUP.getModuleName(), true, textOutputCondition)); ComponentCondition sequenceOutputCondition = new SimpleComponentCondition(new BasicExpression(SqoopConstant.FILE_FORMAT, EqualityOperator.EQ, SqoopConstant.SEQUENCE_OUTPUT_FORMAT)); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_SEQUENCE_MODULE_GROUP.getModuleName(), true, sequenceOutputCondition)); ComponentCondition avroOutputCondition = new SimpleComponentCondition(new BasicExpression(SqoopConstant.FILE_FORMAT, EqualityOperator.EQ, SqoopConstant.AVRO_OUTPUT_FORMAT)); hs.add(new DistributionModuleGroup(EMR5150Constant.SQOOP_AVRO_MODULE_GROUP.getModuleName(), true, avroOutputCondition)); return hs; }
Source:
public int prepare(Xid xid) throws XAException { log.infof("prepare xid: [%s]", xid); return prepareReturnValue; }

Target:
public int prepare(Xid xid) throws XAException { log.tracef("prepare xid: [%s]", xid); return prepareReturnValue; }
Source:
public static synchronized void doSetup() throws Exception { Map<String, String> props = Maps.newHashMapWithExpectedSize(1); props.put(QueryServices.GLOBAL_INDEX_ROW_AGE_THRESHOLD_TO_DELETE_MS_ATTRIB, Long.toString(0)); props.put(ScanInfoUtil.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY, Integer.toString(MAX_LOOKBACK)); setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); }

Target:
public static synchronized void doSetup() throws Exception { Map<String, String> props = Maps.newHashMapWithExpectedSize(2); props.put(QueryServices.GLOBAL_INDEX_ROW_AGE_THRESHOLD_TO_DELETE_MS_ATTRIB, Long.toString(0)); props.put(ScanInfoUtil.PHOENIX_MAX_LOOKBACK_AGE_CONF_KEY, Integer.toString(MAX_LOOKBACK)); setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator())); }
Source:
GitHub(String apiUrl, String login, String oauthAccessToken, String password, HttpConnector connector, RateLimitHandler rateLimitHandler) throws IOException { if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length()-1); this.apiUrl = apiUrl; if (null != connector) this.connector = connector; if (oauthAccessToken!=null) { encodedAuthorization = "token "+oauthAccessToken; } else { if (password!=null) { String authorization = (login + ':' + password); final Charset charset = Charset.defaultCharset(); encodedAuthorization = "Basic "+new String(Base64.encodeBase64(authorization.getBytes(charset)), charset); } else { encodedAuthorization = null; } } this.rateLimitHandler = rateLimitHandler; if (login==null && encodedAuthorization!=null) login = getMyself().getLogin(); this.login = login; }

Target:
GitHub(String apiUrl, String login, String oauthAccessToken, String password, HttpConnector connector, RateLimitHandler rateLimitHandler) throws IOException { if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length()-1); this.apiUrl = apiUrl; if (null != connector) this.connector = connector; if (oauthAccessToken!=null) { encodedAuthorization = "token "+oauthAccessToken; } else { if (password!=null) { String authorization = (login + ':' + password); final Charset charset; try { charset = Charset.forName("UTF-8"); } catch (Exception ex) { throw new IOException("UTF-8 encoding is not supported", ex); } encodedAuthorization = "Basic "+new String(Base64.encodeBase64(authorization.getBytes(charset)), charset); } else { encodedAuthorization = null; } } this.rateLimitHandler = rateLimitHandler; if (login==null && encodedAuthorization!=null) login = getMyself().getLogin(); this.login = login; }
Source:
private void createAndRegisterListener(RemoteCache<K, V> remote) { if (config.mode().invalidated()) { listener = new SmartInvalidatedNearCacheListener<>(this, remote.getRemoteCacheManager().getMarshaller()); try { remote.addClientListener(listener); } catch (HotRodClientException e) { listener = new InvalidatedNearCacheListener<>(this); remote.addClientListener(listener); } } else { listener = new EagerNearCacheListener(this, remote.getRemoteCacheManager().getMarshaller()); remote.addClientListener(listener); } }

Target:
private void createAndRegisterListener(RemoteCache<K, V> remote) { listener = new KeyOnlyInvalidatedNearCacheListener<>(this, remote.getRemoteCacheManager().getMarshaller()); try { remote.addClientListener(listener); } catch (HotRodClientException e) { listener = new InvalidatedNearCacheListener<>(this); remote.addClientListener(listener); } }
Source:
protected void handleMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessage responseMessage, final OsgpException osgpException) throws FunctionalException { this.installationService.handleCoupleMbusDeviceResponse(deviceMessageMetadata, (MbusChannelElementsResponseDto) responseMessage.getDataObject()); }

Target:
protected void handleMessage(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessage responseMessage, final OsgpException osgpException) throws FunctionalException { this.installationService.handleCoupleMbusDeviceResponse(deviceMessageMetadata, responseMessage.getResult(), responseMessage.getOsgpException(), (MbusChannelElementsResponseDto) responseMessage.getDataObject()); }
Source:
public Set<ServiceDependency> getUnfulfilledDependencies(String[] types) { Set<ServiceDependency> ret = new LinkedHashSet<ServiceDependency>(); for (String type : types) { if (!type.contains(".")) { type = String.format("org.myrobotlab.service.%s", type); } ServiceData sd = ServiceData.getLocalInstance(); if (!sd.containsServiceType(type)) { log.error("{} not found", type); return ret; } MetaData st = sd.getServiceType(type); List<ServiceDependency> metaDependencies = st.getDependencies(); if (metaDependencies != null && metaDependencies.size() > 0) { for (ServiceDependency library : metaDependencies) { if (!installedLibraries.containsKey(library.toString())) { ret.add(library); } else { log.debug("previously installed - {}", library); } } } Map<String, ServiceReservation> peers = st.getPeers(); if (peers != null) { for (String key : peers.keySet()) { ServiceReservation sr = peers.get(key); ret.addAll(getUnfulfilledDependencies(CodecUtils.makeFullTypeName(sr.type))); } } } return ret; }

Target:
public Set<ServiceDependency> getUnfulfilledDependencies(String[] types) { Set<ServiceDependency> ret = new LinkedHashSet<ServiceDependency>(); for (String type : types) { if (!type.contains(".")) { type = String.format("org.myrobotlab.service.%s", type); } ServiceData sd = ServiceData.getLocalInstance(); if (!sd.containsServiceType(type)) { log.error("{} not found", type); return ret; } MetaData st = ServiceData.getMetaData(type); List<ServiceDependency> metaDependencies = st.getDependencies(); if (metaDependencies != null && metaDependencies.size() > 0) { for (ServiceDependency library : metaDependencies) { if (!installedLibraries.containsKey(library.toString())) { ret.add(library); } else { log.debug("previously installed - {}", library); } } } Map<String, ServiceReservation> peers = st.getPeers(); if (peers != null) { for (String key : peers.keySet()) { ServiceReservation sr = peers.get(key); ret.addAll(getUnfulfilledDependencies(CodecUtils.makeFullTypeName(sr.type))); } } } return ret; }
Source:
static boolean runningOnComputeEngine( HttpTransportFactory transportFactory, DefaultCredentialsProvider provider) { if (Boolean.parseBoolean(provider.getEnv("NO_GCE_CHECK"))) { return false; } GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(provider)); for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) { try { HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(tokenUrl); request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS); HttpResponse response = request.execute(); try { HttpHeaders headers = response.getHeaders(); return OAuth2Utils.headersContainValue(headers, "Metadata-Flavor", "Google"); } finally { response.disconnect(); } } catch (SocketTimeoutException expected) { } catch (IOException e) { LOGGER.log( Level.WARNING, "Failed to detect whether we are running on Google Compute Engine.", e); } } return false; }

Target:
static boolean runningOnComputeEngine( HttpTransportFactory transportFactory, DefaultCredentialsProvider provider) { if (Boolean.parseBoolean(provider.getEnv(DefaultCredentialsProvider.NO_GCE_CHECK_ENV_VAR))) { return false; } GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(provider)); for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) { try { HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(tokenUrl); request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS); HttpResponse response = request.execute(); try { HttpHeaders headers = response.getHeaders(); return OAuth2Utils.headersContainValue(headers, "Metadata-Flavor", "Google"); } finally { response.disconnect(); } } catch (SocketTimeoutException expected) { } catch (IOException e) { LOGGER.log( Level.WARNING, "Failed to detect whether we are running on Google Compute Engine.", e); } } return false; }
Source:
public void testLockCreationWhenPartitionHappening() throws Throwable { ClusteredLockManager clusteredLockManager = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(0)); await(clusteredLockManager.remove(LOCK_NAME)); splitCluster(new int[]{0, 1, 2}, new int[]{3, 4, 5}); for (int i = 0; i < 6; i++) { int finalI = i; eventuallyEquals(3, () -> advancedCache(finalI).getRpcManager().getTransport().getMembers().size()); } for (EmbeddedCacheManager cm : getCacheManagers()) { ClusteredLockManager clm = EmbeddedClusteredLockManagerFactory.from(cm); eventually(() -> availabilityExceptionRaised(clm)); } }

Target:
public void testLockCreationWhenPartitionHappening() throws Throwable { ClusteredLockManager clusteredLockManager = EmbeddedClusteredLockManagerFactory.from(getCacheManagers().get(0)); await(clusteredLockManager.remove(LOCK_NAME)); splitCluster(new int[]{0, 1, 2}, new int[]{3, 4, 5}); for (EmbeddedCacheManager cm : getCacheManagers()) { ClusteredLockManager clm = EmbeddedClusteredLockManagerFactory.from(cm); eventually(() -> availabilityExceptionRaised(clm)); } }
Source:
public void createSection(Composite parent) { super.createSection(parent); this.dbc = new DataBindingContext(); this.formPresenterSupport = new FormPresenterSupport( new FormEditorPresenter(getManagedForm().getForm().getForm()), dbc); FormToolkit toolkit = new FormToolkit(parent.getDisplay()); this.model = new OpenShiftServerEditorModel(server, this, null); Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); section.setText("OpenShift Server Adapter"); GridDataFactory.fillDefaults() .align(SWT.FILL, SWT.FILL).grab(true, true) .applyTo(section); Composite container = createControls(toolkit, section, dbc); GridDataFactory.fillDefaults() .align(SWT.FILL, SWT.FILL).grab(true, true) .applyTo(container); toolkit.paintBordersFor(container); toolkit.adapt(container); GridDataFactory.fillDefaults() .align(SWT.FILL, SWT.FILL).grab(true, true) .applyTo(container); section.setClient(container); IObservableValue<Boolean> dirtyStatusObservable = DataBindingUtils.createDirtyStatusObservable(getServerEditor()); dbc.addValidationStatusProvider(new MultiValidator() { @Override protected IStatus validate() { if (Boolean.TRUE.equals(dirtyStatusObservable.getValue())) { return ValidationStatus.warning( "Saved changes to the server adapter will only get active once the adapter is restarted."); } return ValidationStatus.ok(); } }); loadResources(section, model, dbc); dbc.updateTargets(); }

Target:
public void createSection(Composite parent) { super.createSection(parent); this.dbc = new DataBindingContext(); this.formPresenterSupport = new FormPresenterSupport( new FormEditorPresenter(getManagedForm().getForm().getForm()), dbc); FormToolkit toolkit = new FormToolkit(parent.getDisplay()); this.model = new OpenShiftServerEditorModel(server, this, null); Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); section.setText("OpenShift Server Adapter"); GridDataFactory.fillDefaults() .align(SWT.FILL, SWT.FILL).grab(true, true) .applyTo(section); Composite container = createControls(toolkit, section, dbc); GridDataFactory.fillDefaults() .align(SWT.FILL, SWT.FILL).grab(true, true) .applyTo(container); toolkit.paintBordersFor(container); toolkit.adapt(container); GridDataFactory.fillDefaults() .align(SWT.FILL, SWT.FILL).grab(true, true) .applyTo(container); section.setClient(container); setupWarningToRestartAdapter(getServerEditor()); loadResources(section, model, dbc); dbc.updateTargets(); }
Source:
public static URLClassLoader urlClassLoaderFromPaths(ClassLoader parent, Collection<Path> paths) { Assert.notNull(paths, "paths collection cannot be null"); final URL[] urls; try { final URI[] uris = paths.stream().map(Path::toUri).toArray(size -> new URI[size]); urls = new URL[uris.length]; for (int i = 0; i < uris.length; i++) { urls[i] = uris[i].toURL(); } } catch (IOException e) { throw new RuntimeException(e); } return new URLClassLoader(urls, parent); }

Target:
public static URLClassLoader urlClassLoaderFromPaths(ClassLoader parent, Collection<Path> paths) { Assert.notNull(paths, "paths collection cannot be null"); final URL[] urls; try { final URI[] uris = paths.stream().map(Path::toUri).toArray(size -> new URI[size]); urls = new URL[uris.length]; for (int i = 0; i < uris.length; i++) { urls[i] = uris[i].toURL(); } } catch (IOException e) { throw new UndeclaredThrowableException(e); } return new URLClassLoader(urls, parent); }
Source:
public WorkbookParser(WorkbookParserSettings settings, Context context, Workbook workbook, String offsetId ) throws DataParserException { this.settings = requireNonNull(settings); this.context = requireNonNull(context); this.workbook = requireNonNull(workbook); this.rowIterator = iterate(this.workbook); this.offset = requireNonNull(offsetId); if (!rowIterator.hasNext()) { throw new DataParserException(Errors.EXCEL_PARSER_04); } switch (settings.getHeader()) { case WITH_HEADER: rowIterator.next(); headers = new HashMap<>(); for (Sheet sheet : workbook) { List<Field> sheetHeaders = new ArrayList<>(); Row headerRow = sheet.getRow(0); for (Cell cell : headerRow) { sheetHeaders.add(Cells.parseCell(cell)); } headers.put(sheet.getSheetName(), sheetHeaders); } break; case IGNORE_HEADER: Row ignored = rowIterator.next(); headers = new HashMap<>(); break; case NO_HEADER: headers = new HashMap<>(); break; } Offsets.parse(offsetId).ifPresent(offset -> { String startSheetName = offset.getSheetName(); int startRowNum = offset.getRowNum(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); int rowNum = row.getRowNum(); String sheetName = row.getSheet().getSheetName(); if (startSheetName.equals(sheetName) && rowNum == startRowNum) { if (rowIterator.hasPrevious()) { rowIterator.previous(); } break; } } }); }

Target:
public WorkbookParser(WorkbookParserSettings settings, Context context, Workbook workbook, String offsetId ) throws DataParserException { this.settings = requireNonNull(settings); this.context = requireNonNull(context); this.workbook = requireNonNull(workbook); this.rowIterator = iterate(this.workbook); this.offset = requireNonNull(offsetId); this.evaluator = workbook.getCreationHelper().createFormulaEvaluator(); if (!rowIterator.hasNext()) { throw new DataParserException(Errors.EXCEL_PARSER_04); } headers = new HashMap<>(); if (settings.getHeader() != NO_HEADER) { rowIterator.next(); } if (settings.getHeader() == WITH_HEADER) { for (Sheet sheet : workbook) { List<Field> sheetHeaders = new ArrayList<>(); Row headerRow = sheet.getRow(0); if (headerRow == null) { throw new DataParserException(Errors.EXCEL_PARSER_07, sheet.getSheetName()); } for (Cell cell : headerRow) { try { sheetHeaders.add(Cells.parseCell(cell, this.evaluator)); } catch (ExcelUnsupportedCellTypeException e) { throw new DataParserException(Errors.EXCEL_PARSER_05, cell.getCellTypeEnum()); } } headers.put(sheet.getSheetName(), sheetHeaders); } } Offsets.parse(offsetId).ifPresent(offset -> { String startSheetName = offset.getSheetName(); int startRowNum = offset.getRowNum(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); int rowNum = row.getRowNum(); String sheetName = row.getSheet().getSheetName(); if (startSheetName.equals(sheetName) && rowNum == startRowNum) { if (rowIterator.hasPrevious()) { rowIterator.previous(); } break; } } }); }
Source:
public void halt() throws InterruptedException { for (;;) { join(250 ); if (isAlive()) { done = true; interrupt(); if (process != null) { process.destroy(); } } else break; } }

Target:
public void halt() throws InterruptedException { for (;;) { join(250 ); if (isAlive()) { done = true; interrupt(); } else { break; } } }