_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q164900
ConfigureJMeterMojo.copyExplicitLibraries
train
private void copyExplicitLibraries(List<String> desiredArtifacts, File destination, boolean downloadDependencies) throws MojoExecutionException { for (String desiredArtifact : desiredArtifacts) { copyExplicitLibrary(desiredArtifact, destination, downloadDependencies); } }
java
{ "resource": "" }
q164901
ConfigureJMeterMojo.getArtifactResult
train
private Artifact getArtifactResult(Artifact desiredArtifact) throws MojoExecutionException {// NOSONAR ArtifactRequest artifactRequest = new ArtifactRequest(); artifactRequest.setArtifact(desiredArtifact); artifactRequest.setRepositories(repositoryList); try { return repositorySystem.resolveArtifact(repositorySystemSession, artifactRequest).getArtifact(); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } }
java
{ "resource": "" }
q164902
ConfigureJMeterMojo.copyArtifactIfRequired
train
private boolean copyArtifactIfRequired(Artifact artifactToCopy, Path destinationDirectory) throws MojoExecutionException { for (String ignoredArtifact : ignoredArtifacts) { Artifact artifactToIgnore = getArtifactResult(new DefaultArtifact(ignoredArtifact)); if (artifactToCopy.getFile().getName().equals(artifactToIgnore.getFile().getName())) { getLog().debug(artifactToCopy.getFile().getName() + " has not been copied over because it is in the ignore list."); return false; } } try { for (Iterator<Artifact> iterator = copiedArtifacts.iterator(); iterator.hasNext(); ) { Artifact alreadyCopiedArtifact = iterator.next(); if (artifactsAreMatchingTypes(alreadyCopiedArtifact, artifactToCopy)) { if (isArtifactIsOlderThanArtifact(alreadyCopiedArtifact, artifactToCopy)) { Path artifactToDelete = Paths.get(destinationDirectory.toString(), alreadyCopiedArtifact.getFile().getName()); getLog().debug(String.format("Deleting file:'%s'", artifactToDelete)); // We delete the old artifact and remove it from the list of copied artifacts, the new artifact will be copied below Files.deleteIfExists(artifactToDelete); iterator.remove(); break; } else { return false; } } } Path desiredArtifact = Paths.get(destinationDirectory.toString(), artifactToCopy.getFile().getName()); if (!desiredArtifact.toFile().exists()) { getLog().debug(String.format("Copying: %s to %s", desiredArtifact.toString(), destinationDirectory.toString())); Files.copy(Paths.get(artifactToCopy.getFile().getAbsolutePath()), desiredArtifact); } } catch (IOException | InvalidVersionSpecificationException e) { throw new MojoExecutionException(e.getMessage(), e); } copiedArtifacts.add(artifactToCopy); return true; }
java
{ "resource": "" }
q164903
JMeterArgumentsArray.buildArgumentsArray
train
public List<String> buildArgumentsArray() throws MojoExecutionException { if (!argumentList.contains(TESTFILE_OPT) && !disableTests) { throw new MojoExecutionException("No test(s) specified!"); } List<String> argumentsArray = new ArrayList<>(); for (JMeterCommandLineArguments argument : argumentList) { switch (argument) { case NONGUI_OPT: argumentsArray.add(NONGUI_OPT.getCommandLineArgument()); break; case TESTFILE_OPT: argumentsArray.add(TESTFILE_OPT.getCommandLineArgument()); argumentsArray.add(testFile); break; case LOGFILE_OPT: argumentsArray.add(LOGFILE_OPT.getCommandLineArgument()); argumentsArray.add(resultsLogFileName); break; case JMETER_HOME_OPT: argumentsArray.add(JMETER_HOME_OPT.getCommandLineArgument()); argumentsArray.add(jMeterHome); break; case LOGLEVEL: argumentsArray.add(LOGLEVEL.getCommandLineArgument()); argumentsArray.add(overrideRootLogLevel.toString()); break; case PROPFILE2_OPT: for (String customPropertiesFile : customPropertiesFiles) { argumentsArray.add(PROPFILE2_OPT.getCommandLineArgument()); argumentsArray.add(customPropertiesFile); } break; case REMOTE_OPT: argumentsArray.add(REMOTE_OPT.getCommandLineArgument()); break; case PROXY_HOST: argumentsArray.add(PROXY_HOST.getCommandLineArgument()); argumentsArray.add(proxyConfiguration.getHost()); break; case PROXY_PORT: argumentsArray.add(PROXY_PORT.getCommandLineArgument()); argumentsArray.add(proxyConfiguration.getPort()); break; case PROXY_USERNAME: argumentsArray.add(PROXY_USERNAME.getCommandLineArgument()); argumentsArray.add(proxyConfiguration.getUsername()); break; case PROXY_PASSWORD: argumentsArray.add(PROXY_PASSWORD.getCommandLineArgument()); argumentsArray.add(proxyConfiguration.getPassword()); break; case NONPROXY_HOSTS: argumentsArray.add(NONPROXY_HOSTS.getCommandLineArgument()); argumentsArray.add(proxyConfiguration.getHostExclusions()); break; case REMOTE_STOP: argumentsArray.add(REMOTE_STOP.getCommandLineArgument()); break; case REMOTE_OPT_PARAM: argumentsArray.add(REMOTE_OPT_PARAM.getCommandLineArgument()); argumentsArray.add(remoteStartServerList); break; case JMLOGFILE_OPT: argumentsArray.add(JMLOGFILE_OPT.getCommandLineArgument()); argumentsArray.add(jmeterLogFileName); break; case REPORT_AT_END_OPT: argumentsArray.add(REPORT_AT_END_OPT.getCommandLineArgument()); break; case REPORT_OUTPUT_FOLDER_OPT: argumentsArray.add(REPORT_OUTPUT_FOLDER_OPT.getCommandLineArgument()); argumentsArray.add(reportDirectory); break; case SERVER_OPT: argumentsArray.add(SERVER_OPT.getCommandLineArgument()); break; case SYSTEM_PROPFILE: case JMETER_PROPERTY: case JMETER_GLOBAL_PROP: case SYSTEM_PROPERTY: case VERSION_OPT: case PROPFILE_OPT: case REPORT_GENERATING_OPT: case HELP_OPT: //Unhandled options, they will be ignored break; } } return argumentsArray; }
java
{ "resource": "" }
q164904
RunJMeterServerMojo.doExecute
train
@Override public void doExecute() throws MojoExecutionException { getLog().info(" "); getLog().info(LINE_SEPARATOR); getLog().info(" S T A R T I N G J M E T E R S E R V E R "); getLog().info(LINE_SEPARATOR); getLog().info(String.format(" Host: %s", exportedRmiHostname)); getLog().info(String.format(" Port: %s", serverPort)); startJMeterServer(initializeJMeterArgumentsArray()); }
java
{ "resource": "" }
q164905
RunJMeterMojo.doExecute
train
@Override public void doExecute() throws MojoExecutionException { getLog().info(" "); getLog().info(LINE_SEPARATOR); getLog().info(" P E R F O R M A N C E T E S T S"); getLog().info(LINE_SEPARATOR); getLog().info(" "); if (!testFilesDirectory.exists()) { getLog().info("<testFilesDirectory>" + testFilesDirectory.getAbsolutePath() + "</testFilesDirectory> does not exist..."); getLog().info("Performance tests skipped!"); getLog().info(" "); return; } TestConfig testConfig = new TestConfig(new File(testConfigFile)); JMeterConfigurationHolder configuration = JMeterConfigurationHolder.getInstance(); remoteConfig.setPropertiesMap(configuration.getPropertiesMap()); jMeterProcessJVMSettings.setHeadlessDefaultIfRequired(); copyFilesInTestDirectory(testFilesDirectory, testFilesBuildDirectory); TestManager jMeterTestManager = new TestManager() .setBaseTestArgs(computeJMeterArgumentsArray(true, testConfig.getResultsOutputIsCSVFormat())) .setTestFilesDirectory(testFilesBuildDirectory) .setTestFilesIncluded(testFilesIncluded) .setTestFilesExcluded(testFilesExcluded) .setRemoteServerConfiguration(remoteConfig) .setSuppressJMeterOutput(suppressJMeterOutput) .setBinDir(configuration.getWorkingDirectory()) .setJMeterProcessJVMSettings(jMeterProcessJVMSettings) .setRuntimeJarName(configuration.getRuntimeJarName()) .setReportDirectory(reportDirectory) .setGenerateReports(generateReports) .setPostTestPauseInSeconds(postTestPauseInSeconds); if (proxyConfig != null) { getLog().info(this.proxyConfig.toString()); } testConfig.setResultsFileLocations(jMeterTestManager.executeTests()); testConfig.writeResultFilesConfigTo(testConfigFile); }
java
{ "resource": "" }
q164906
AbstractJMeterMojo.computeJMeterArgumentsArray
train
protected JMeterArgumentsArray computeJMeterArgumentsArray(boolean disableGUI, boolean isCSVFormat) throws MojoExecutionException { JMeterArgumentsArray testArgs = new JMeterArgumentsArray(disableGUI, jmeterDirectory.getAbsolutePath()) .setResultsDirectory(resultsDirectory.getAbsolutePath()) .setResultFileOutputFormatIsCSV(isCSVFormat) .setProxyConfig(proxyConfig) .setLogRootOverride(overrideRootLogLevel) .setLogsDirectory(logsDirectory.getAbsolutePath()) .addACustomPropertiesFiles(customPropertiesFiles); if (generateReports && disableGUI) { testArgs.setReportsDirectory(reportDirectory.getAbsolutePath()); } if (testResultsTimestamp) { testArgs.setResultsTimestamp(true) .appendTimestamp(appendResultsTimestamp) .setResultsFileNameDateFormat(resultsFileNameDateFormat); } return testArgs; }
java
{ "resource": "" }
q164907
AbstractJMeterMojo.loadMavenProxy
train
protected void loadMavenProxy() { if (null == settings) { return; } Proxy mvnProxy = settings.getActiveProxy(); if (mvnProxy != null) { ProxyConfiguration newProxyConfiguration = new ProxyConfiguration(); newProxyConfiguration.setHost(mvnProxy.getHost()); newProxyConfiguration.setPort(mvnProxy.getPort()); newProxyConfiguration.setUsername(mvnProxy.getUsername()); newProxyConfiguration.setPassword(mvnProxy.getPassword()); newProxyConfiguration.setHostExclusions(mvnProxy.getNonProxyHosts()); proxyConfig = newProxyConfiguration; getLog().info("Maven proxy loaded successfully"); } else { getLog().warn("No maven proxy found, however useMavenProxy is set to true!"); } }
java
{ "resource": "" }
q164908
UtilityFunctions.humanReadableCommandLineOutput
train
public static String humanReadableCommandLineOutput(List<String> arguments) { //TODO investigate removing this, only used in tests StringBuilder debugOutput = new StringBuilder(); for (String argument : arguments) { debugOutput.append(argument).append(" "); } return debugOutput.toString().trim(); }
java
{ "resource": "" }
q164909
UtilityFunctions.isNotSet
train
public static Boolean isNotSet(String value) { return null == value || value.isEmpty() || value.trim().length() == 0; }
java
{ "resource": "" }
q164910
UtilityFunctions.isNotSet
train
public static Boolean isNotSet(File value) { return null == value || value.toString().isEmpty() || value.toString().trim().length() == 0; }
java
{ "resource": "" }
q164911
RunJMeterGUIMojo.doExecute
train
@Override public void doExecute() throws MojoExecutionException { getLog().info(" "); getLog().info(LINE_SEPARATOR); getLog().info(" S T A R T I N G J M E T E R G U I "); getLog().info(LINE_SEPARATOR); startJMeterGUI(initialiseJMeterArgumentsArray()); }
java
{ "resource": "" }
q164912
PropertiesFile.loadPropertiesFile
train
private Properties loadPropertiesFile(File propertiesFile) throws MojoExecutionException { // NOSONAR try (FileInputStream propertiesFileInputStream = new FileInputStream(propertiesFile)) { Properties loadedProperties = new Properties(); loadedProperties.load(propertiesFileInputStream); return loadedProperties; } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
java
{ "resource": "" }
q164913
PropertiesFile.loadProvidedPropertiesIfAvailable
train
public void loadProvidedPropertiesIfAvailable(File providedPropertiesFile, boolean replaceAllProperties) throws MojoExecutionException { if (providedPropertiesFile.exists()) { Properties providedPropertySet = loadPropertiesFile(providedPropertiesFile); if (replaceAllProperties) { this.properties = providedPropertySet; } else { this.properties.putAll(providedPropertySet); } } }
java
{ "resource": "" }
q164914
PropertiesFile.addAndOverwriteProperties
train
public void addAndOverwriteProperties(Map<String, String> additionalProperties) { additionalProperties.values().removeAll(Collections.singleton(null)); for (Map.Entry<String, String> additionalPropertiesMap : additionalProperties.entrySet()) { if (!additionalPropertiesMap.getValue().trim().isEmpty()) { properties.setProperty(additionalPropertiesMap.getKey(), additionalPropertiesMap.getValue()); warnUserOfPossibleErrors(additionalPropertiesMap.getKey(), properties); } } }
java
{ "resource": "" }
q164915
PropertiesFile.writePropertiesToFile
train
public void writePropertiesToFile(File outputFile) throws MojoExecutionException {// NOSONAR stripOutReservedProperties(); //TODO if jmeter.properties write properties that are required for plugin if (properties.isEmpty()) { return; } try { try (FileOutputStream writeOutFinalPropertiesFile = new FileOutputStream(outputFile)) { properties.store(writeOutFinalPropertiesFile, null); writeOutFinalPropertiesFile.flush(); } } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
java
{ "resource": "" }
q164916
PropertiesFile.warnUserOfPossibleErrors
train
private void warnUserOfPossibleErrors(String newKey, Properties baseProperties) { for (String key : baseProperties.stringPropertyNames()) { if (!key.equals(newKey) && key.equalsIgnoreCase(newKey)) { LOGGER.warn("You have set a property called '{}' which is very similar to '{}'!", newKey, key); } } }
java
{ "resource": "" }
q164917
JarLibraryLoader.load
train
public boolean load(String name, boolean verify) { boolean loaded = false; try { Platform platform = Platform.detect(); JarFile jar = new JarFile(codeSource.getLocation().getPath(), verify); try { for (String path : libCandidates(platform, name)) { JarEntry entry = jar.getJarEntry(path); if (entry == null) continue; File lib = extract(name, jar.getInputStream(entry)); System.load(lib.getAbsolutePath()); lib.delete(); loaded = true; break; } } finally { jar.close(); } } catch (Throwable e) { loaded = false; } return loaded; }
java
{ "resource": "" }
q164918
JarLibraryLoader.extract
train
private static File extract(String name, InputStream is) throws IOException { byte[] buf = new byte[4096]; int len; File lib = File.createTempFile(name, "lib"); FileOutputStream os = new FileOutputStream(lib); try { while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } } catch (IOException e) { lib.delete(); throw e; } finally { os.close(); is.close(); } return lib; }
java
{ "resource": "" }
q164919
JarLibraryLoader.libCandidates
train
private List<String> libCandidates(Platform platform, String name) { List<String> candidates = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); sb.append(libraryPath).append("/"); sb.append(platform.arch).append("/"); sb.append(platform.os).append("/"); sb.append("lib").append(name); switch (platform.os) { case darwin: candidates.add(sb + ".dylib"); candidates.add(sb + ".jnilib"); break; case linux: case freebsd: candidates.add(sb + ".so"); break; } return candidates; }
java
{ "resource": "" }
q164920
Base64.decode
train
public static byte[] decode(char[] src, int[] table, char pad) { int len = src.length; if (len == 0) return new byte[0]; int padCount = (src[len - 1] == pad ? (src[len - 2] == pad ? 2 : 1) : 0); int bytes = (len * 6 >> 3) - padCount; int blocks = (bytes / 3) * 3; byte[] dst = new byte[bytes]; int si = 0, di = 0; while (di < blocks) { int n = table[src[si++]] << 18 | table[src[si++]] << 12 | table[src[si++]] << 6 | table[src[si++]]; dst[di++] = (byte) (n >> 16); dst[di++] = (byte) (n >> 8); dst[di++] = (byte) n; } if (di < bytes) { int n = 0; switch (len - si) { case 4: n |= table[src[si+3]]; case 3: n |= table[src[si+2]] << 6; case 2: n |= table[src[si+1]] << 12; case 1: n |= table[src[si]] << 18; } for (int r = 16; di < bytes; r -= 8) { dst[di++] = (byte) (n >> r); } } return dst; }
java
{ "resource": "" }
q164921
Base64.encode
train
public static char[] encode(byte[] src, char[] table, char pad) { int len = src.length; if (len == 0) return new char[0]; int blocks = (len / 3) * 3; int chars = ((len - 1) / 3 + 1) << 2; int tail = len - blocks; if (pad == 0 && tail > 0) chars -= 3 - tail; char[] dst = new char[chars]; int si = 0, di = 0; while (si < blocks) { int n = (src[si++] & 0xff) << 16 | (src[si++] & 0xff) << 8 | (src[si++] & 0xff); dst[di++] = table[(n >>> 18) & 0x3f]; dst[di++] = table[(n >>> 12) & 0x3f]; dst[di++] = table[(n >>> 6) & 0x3f]; dst[di++] = table[n & 0x3f]; } if (tail > 0) { int n = (src[si] & 0xff) << 10; if (tail == 2) n |= (src[++si] & 0xff) << 2; dst[di++] = table[(n >>> 12) & 0x3f]; dst[di++] = table[(n >>> 6) & 0x3f]; if (tail == 2) dst[di++] = table[n & 0x3f]; if (pad != 0) { if (tail == 1) dst[di++] = pad; dst[di] = pad; } } return dst; }
java
{ "resource": "" }
q164922
SysLibraryLoader.load
train
public boolean load(String name, boolean verify) { boolean loaded; try { System.loadLibrary(name); loaded = true; } catch (Throwable e) { loaded = false; } return loaded; }
java
{ "resource": "" }
q164923
CharSource.copyTo
validation
@CanIgnoreReturnValue public long copyTo(CharSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); Writer writer = closer.register(sink.openStream()); return CharStreams.copy(reader, writer); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
java
{ "resource": "" }
q164924
CharSource.read
validation
public String read() throws IOException { Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.toString(reader); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
java
{ "resource": "" }
q164925
CharSource.readLines
validation
public ImmutableList<String> readLines() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); List<String> result = Lists.newArrayList(); String line; while ((line = reader.readLine()) != null) { result.add(line); } return ImmutableList.copyOf(result); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
java
{ "resource": "" }
q164926
ReaderInputStream.read
validation
@Override public int read(byte[] b, int off, int len) throws IOException { // Obey InputStream contract. checkPositionIndexes(off, off + len, b.length); if (len == 0) { return 0; } // The rest of this method implements the process described by the CharsetEncoder javadoc. int totalBytesRead = 0; boolean doneEncoding = endOfInput; DRAINING: while (true) { // We stay in draining mode until there are no bytes left in the output buffer. Then we go // back to encoding/flushing. if (draining) { totalBytesRead += drain(b, off + totalBytesRead, len - totalBytesRead); if (totalBytesRead == len || doneFlushing) { return (totalBytesRead > 0) ? totalBytesRead : -1; } draining = false; byteBuffer.clear(); } while (true) { // We call encode until there is no more input. The last call to encode will have endOfInput // == true. Then there is a final call to flush. CoderResult result; if (doneFlushing) { result = CoderResult.UNDERFLOW; } else if (doneEncoding) { result = encoder.flush(byteBuffer); } else { result = encoder.encode(charBuffer, byteBuffer, endOfInput); } if (result.isOverflow()) { // Not enough room in output buffer--drain it, creating a bigger buffer if necessary. startDraining(true); continue DRAINING; } else if (result.isUnderflow()) { // If encoder underflows, it means either: // a) the final flush() succeeded; next drain (then done) // b) we encoded all of the input; next flush // c) we ran of out input to encode; next read more input if (doneEncoding) { // (a) doneFlushing = true; startDraining(false); continue DRAINING; } else if (endOfInput) { // (b) doneEncoding = true; } else { // (c) readMoreChars(); } } else if (result.isError()) { // Only reach here if a CharsetEncoder with non-REPLACE settings is used. result.throwException(); return 0; // Not called. } } } }
java
{ "resource": "" }
q164927
ReaderInputStream.grow
validation
private static CharBuffer grow(CharBuffer buf) { char[] copy = Arrays.copyOf(buf.array(), buf.capacity() * 2); CharBuffer bigger = CharBuffer.wrap(copy); bigger.position(buf.position()); bigger.limit(buf.limit()); return bigger; }
java
{ "resource": "" }
q164928
ReaderInputStream.readMoreChars
validation
private void readMoreChars() throws IOException { // Possibilities: // 1) array has space available on right hand side (between limit and capacity) // 2) array has space available on left hand side (before position) // 3) array has no space available // // In case 2 we shift the existing chars to the left, and in case 3 we create a bigger // array, then they both become case 1. if (availableCapacity(charBuffer) == 0) { if (charBuffer.position() > 0) { // (2) There is room in the buffer. Move existing bytes to the beginning. charBuffer.compact().flip(); } else { // (3) Entire buffer is full, need bigger buffer. charBuffer = grow(charBuffer); } } // (1) Read more characters into free space at end of array. int limit = charBuffer.limit(); int numChars = reader.read(charBuffer.array(), limit, availableCapacity(charBuffer)); if (numChars == -1) { endOfInput = true; } else { charBuffer.limit(limit + numChars); } }
java
{ "resource": "" }
q164929
ReaderInputStream.startDraining
validation
private void startDraining(boolean overflow) { byteBuffer.flip(); if (overflow && byteBuffer.remaining() == 0) { byteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2); } else { draining = true; } }
java
{ "resource": "" }
q164930
Iterables.toArray
validation
@GwtIncompatible // Array.newInstance(Class, int) public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) { return toArray(iterable, ObjectArrays.newArray(type, 0)); }
java
{ "resource": "" }
q164931
Iterables.isEmpty
validation
public static boolean isEmpty(Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); }
java
{ "resource": "" }
q164932
Iterables.toIterator
validation
static <T> Function<Iterable<? extends T>, Iterator<? extends T>> toIterator() { return new Function<Iterable<? extends T>, Iterator<? extends T>>() { @Override public Iterator<? extends T> apply(Iterable<? extends T> iterable) { return iterable.iterator(); } }; }
java
{ "resource": "" }
q164933
Iterators.consumingForArray
validation
private static <T> Iterator<T> consumingForArray(final T... elements) { return new UnmodifiableIterator<T>() { int index = 0; @Override public boolean hasNext() { return index < elements.length; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } T result = elements[index]; elements[index] = null; index++; return result; } }; }
java
{ "resource": "" }
q164934
Iterators.concatNoDefensiveCopy
validation
static <T> Iterator<T> concatNoDefensiveCopy(Iterator<? extends T>... inputs) { for (Iterator<? extends T> input : checkNotNull(inputs)) { checkNotNull(input); } return concat(consumingForArray(inputs)); }
java
{ "resource": "" }
q164935
Iterators.clear
validation
static void clear(Iterator<?> iterator) { checkNotNull(iterator); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } }
java
{ "resource": "" }
q164936
ByteSink.write
validation
public void write(byte[] bytes) throws IOException { checkNotNull(bytes); Closer closer = Closer.create(); try { OutputStream out = closer.register(openStream()); out.write(bytes); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
java
{ "resource": "" }
q164937
CacheBuilderSpec.parse
validation
public static CacheBuilderSpec parse(String cacheBuilderSpecification) { CacheBuilderSpec spec = new CacheBuilderSpec(cacheBuilderSpecification); if (!cacheBuilderSpecification.isEmpty()) { for (String keyValuePair : KEYS_SPLITTER.split(cacheBuilderSpecification)) { List<String> keyAndValue = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyValuePair)); checkArgument(!keyAndValue.isEmpty(), "blank key-value pair"); checkArgument( keyAndValue.size() <= 2, "key-value pair %s with more than one equals sign", keyValuePair); // Find the ValueParser for the current key. String key = keyAndValue.get(0); ValueParser valueParser = VALUE_PARSERS.get(key); checkArgument(valueParser != null, "unknown key %s", key); String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1); valueParser.parse(spec, key, value); } } return spec; }
java
{ "resource": "" }
q164938
CacheBuilderSpec.toCacheBuilder
validation
CacheBuilder<Object, Object> toCacheBuilder() { CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder(); if (initialCapacity != null) { builder.initialCapacity(initialCapacity); } if (maximumSize != null) { builder.maximumSize(maximumSize); } if (maximumWeight != null) { builder.maximumWeight(maximumWeight); } if (concurrencyLevel != null) { builder.concurrencyLevel(concurrencyLevel); } if (keyStrength != null) { switch (keyStrength) { case WEAK: builder.weakKeys(); break; default: throw new AssertionError(); } } if (valueStrength != null) { switch (valueStrength) { case SOFT: builder.softValues(); break; case WEAK: builder.weakValues(); break; default: throw new AssertionError(); } } if (recordStats != null && recordStats) { builder.recordStats(); } if (writeExpirationTimeUnit != null) { builder.expireAfterWrite(writeExpirationDuration, writeExpirationTimeUnit); } if (accessExpirationTimeUnit != null) { builder.expireAfterAccess(accessExpirationDuration, accessExpirationTimeUnit); } if (refreshTimeUnit != null) { builder.refreshAfterWrite(refreshDuration, refreshTimeUnit); } return builder; }
java
{ "resource": "" }
q164939
Joiner.skipNulls
validation
public Joiner skipNulls() { return new Joiner(this) { @Override public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException { checkNotNull(appendable, "appendable"); checkNotNull(parts, "parts"); while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(Joiner.this.toString(part)); break; } } while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(separator); appendable.append(Joiner.this.toString(part)); } } return appendable; } @Override public Joiner useForNull(String nullText) { throw new UnsupportedOperationException("already specified skipNulls"); } @Override public MapJoiner withKeyValueSeparator(String kvs) { throw new UnsupportedOperationException("can't use .skipNulls() with maps"); } }; }
java
{ "resource": "" }
q164940
ImmutableIntArray.of
validation
public static ImmutableIntArray of(int first, int... rest) { checkArgument( rest.length <= Integer.MAX_VALUE - 1, "the total number of elements must fit in an int"); int[] array = new int[rest.length + 1]; array[0] = first; System.arraycopy(rest, 0, array, 1, rest.length); return new ImmutableIntArray(array); }
java
{ "resource": "" }
q164941
ImmutableIntArray.subArray
validation
public ImmutableIntArray subArray(int startIndex, int endIndex) { Preconditions.checkPositionIndexes(startIndex, endIndex, length()); return startIndex == endIndex ? EMPTY : new ImmutableIntArray(array, start + startIndex, start + endIndex); }
java
{ "resource": "" }
q164942
HashingInputStream.read
validation
@Override @CanIgnoreReturnValue public int read() throws IOException { int b = in.read(); if (b != -1) { hasher.putByte((byte) b); } return b; }
java
{ "resource": "" }
q164943
HashingInputStream.read
validation
@Override @CanIgnoreReturnValue public int read(byte[] bytes, int off, int len) throws IOException { int numOfBytesRead = in.read(bytes, off, len); if (numOfBytesRead != -1) { hasher.putBytes(bytes, off, numOfBytesRead); } return numOfBytesRead; }
java
{ "resource": "" }
q164944
Serialization.writeMap
validation
static <K, V> void writeMap(Map<K, V> map, ObjectOutputStream stream) throws IOException { stream.writeInt(map.size()); for (Map.Entry<K, V> entry : map.entrySet()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } }
java
{ "resource": "" }
q164945
Serialization.writeMultiset
validation
static <E> void writeMultiset(Multiset<E> multiset, ObjectOutputStream stream) throws IOException { int entryCount = multiset.entrySet().size(); stream.writeInt(entryCount); for (Multiset.Entry<E> entry : multiset.entrySet()) { stream.writeObject(entry.getElement()); stream.writeInt(entry.getCount()); } }
java
{ "resource": "" }
q164946
Serialization.getFieldSetter
validation
static <T> FieldSetter<T> getFieldSetter(final Class<T> clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); return new FieldSetter<T>(field); } catch (NoSuchFieldException e) { throw new AssertionError(e); // programmer error } }
java
{ "resource": "" }
q164947
Stopwatch.start
validation
@CanIgnoreReturnValue public Stopwatch start() { checkState(!isRunning, "This stopwatch is already running."); isRunning = true; startTick = ticker.read(); return this; }
java
{ "resource": "" }
q164948
ConcurrentHashMultiset.add
validation
@CanIgnoreReturnValue @Override public int add(E element, int occurrences) { checkNotNull(element); if (occurrences == 0) { return count(element); } CollectPreconditions.checkPositive(occurrences, "occurences"); while (true) { AtomicInteger existingCounter = Maps.safeGet(countMap, element); if (existingCounter == null) { existingCounter = countMap.putIfAbsent(element, new AtomicInteger(occurrences)); if (existingCounter == null) { return 0; } // existingCounter != null: fall through to operate against the existing AtomicInteger } while (true) { int oldValue = existingCounter.get(); if (oldValue != 0) { try { int newValue = IntMath.checkedAdd(oldValue, occurrences); if (existingCounter.compareAndSet(oldValue, newValue)) { // newValue can't == 0, so no need to check & remove return oldValue; } } catch (ArithmeticException overflow) { throw new IllegalArgumentException( "Overflow adding " + occurrences + " occurrences to a count of " + oldValue); } } else { // In the case of a concurrent remove, we might observe a zero value, which means another // thread is about to remove (element, existingCounter) from the map. Rather than wait, // we can just do that work here. AtomicInteger newCounter = new AtomicInteger(occurrences); if ((countMap.putIfAbsent(element, newCounter) == null) || countMap.replace(element, existingCounter, newCounter)) { return 0; } break; } } // If we're still here, there was a race, so just try again. } }
java
{ "resource": "" }
q164949
CompactHashSet.resizeMeMaybe
validation
private void resizeMeMaybe(int newSize) { int entriesSize = entries.length; if (newSize > entriesSize) { int newCapacity = entriesSize + Math.max(1, entriesSize >>> 1); if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; } if (newCapacity != entriesSize) { resizeEntries(newCapacity); } } }
java
{ "resource": "" }
q164950
InetAddresses.bytesToInetAddress
validation
private static InetAddress bytesToInetAddress(byte[] addr) { try { return InetAddress.getByAddress(addr); } catch (UnknownHostException e) { throw new AssertionError(e); } }
java
{ "resource": "" }
q164951
InetAddresses.compressLongestRunOfZeroes
validation
private static void compressLongestRunOfZeroes(int[] hextets) { int bestRunStart = -1; int bestRunLength = -1; int runStart = -1; for (int i = 0; i < hextets.length + 1; i++) { if (i < hextets.length && hextets[i] == 0) { if (runStart < 0) { runStart = i; } } else if (runStart >= 0) { int runLength = i - runStart; if (runLength > bestRunLength) { bestRunStart = runStart; bestRunLength = runLength; } runStart = -1; } } if (bestRunLength >= 2) { Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); } }
java
{ "resource": "" }
q164952
InetAddresses.hextetsToIPv6String
validation
private static String hextetsToIPv6String(int[] hextets) { // While scanning the array, handle these state transitions: // start->num => "num" start->gap => "::" // num->num => ":num" num->gap => "::" // gap->num => "num" gap->gap => "" StringBuilder buf = new StringBuilder(39); boolean lastWasNumber = false; for (int i = 0; i < hextets.length; i++) { boolean thisIsNumber = hextets[i] >= 0; if (thisIsNumber) { if (lastWasNumber) { buf.append(':'); } buf.append(Integer.toHexString(hextets[i])); } else { if (i == 0 || lastWasNumber) { buf.append("::"); } } lastWasNumber = thisIsNumber; } return buf.toString(); }
java
{ "resource": "" }
q164953
InetAddresses.forUriString
validation
public static InetAddress forUriString(String hostAddr) { InetAddress addr = forUriStringNoThrow(hostAddr); if (addr == null) { throw formatIllegalArgumentException("Not a valid URI IP literal: '%s'", hostAddr); } return addr; }
java
{ "resource": "" }
q164954
InetAddresses.isCompatIPv4Address
validation
public static boolean isCompatIPv4Address(Inet6Address ip) { if (!ip.isIPv4CompatibleAddress()) { return false; } byte[] bytes = ip.getAddress(); if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0) && ((bytes[15] == 0) || (bytes[15] == 1))) { return false; } return true; }
java
{ "resource": "" }
q164955
InetAddresses.getCompatIPv4Address
validation
public static Inet4Address getCompatIPv4Address(Inet6Address ip) { checkArgument( isCompatIPv4Address(ip), "Address '%s' is not IPv4-compatible.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); }
java
{ "resource": "" }
q164956
InetAddresses.isTeredoAddress
validation
public static boolean isTeredoAddress(Inet6Address ip) { byte[] bytes = ip.getAddress(); return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01) && (bytes[2] == 0) && (bytes[3] == 0); }
java
{ "resource": "" }
q164957
InetAddresses.isIsatapAddress
validation
public static boolean isIsatapAddress(Inet6Address ip) { // If it's a Teredo address with the right port (41217, or 0xa101) // which would be encoded as 0x5efe then it can't be an ISATAP address. if (isTeredoAddress(ip)) { return false; } byte[] bytes = ip.getAddress(); if ((bytes[8] | (byte) 0x03) != (byte) 0x03) { // Verify that high byte of the 64 bit identifier is zero, modulo // the U/L and G bits, with which we are not concerned. return false; } return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e) && (bytes[11] == (byte) 0xfe); }
java
{ "resource": "" }
q164958
InetAddresses.getIsatapIPv4Address
validation
public static Inet4Address getIsatapIPv4Address(Inet6Address ip) { checkArgument(isIsatapAddress(ip), "Address '%s' is not an ISATAP address.", toAddrString(ip)); return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16)); }
java
{ "resource": "" }
q164959
InetAddresses.getEmbeddedIPv4ClientAddress
validation
public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) { if (isCompatIPv4Address(ip)) { return getCompatIPv4Address(ip); } if (is6to4Address(ip)) { return get6to4IPv4Address(ip); } if (isTeredoAddress(ip)) { return getTeredoInfo(ip).getClient(); } throw formatIllegalArgumentException("'%s' has no embedded IPv4 address.", toAddrString(ip)); }
java
{ "resource": "" }
q164960
InetAddresses.isMappedIPv4Address
validation
public static boolean isMappedIPv4Address(String ipString) { byte[] bytes = ipStringToBytes(ipString); if (bytes != null && bytes.length == 16) { for (int i = 0; i < 10; i++) { if (bytes[i] != 0) { return false; } } for (int i = 10; i < 12; i++) { if (bytes[i] != (byte) 0xff) { return false; } } return true; } return false; }
java
{ "resource": "" }
q164961
InetAddresses.decrement
validation
public static InetAddress decrement(InetAddress address) { byte[] addr = address.getAddress(); int i = addr.length - 1; while (i >= 0 && addr[i] == (byte) 0x00) { addr[i] = (byte) 0xff; i--; } checkArgument(i >= 0, "Decrementing %s would wrap.", address); addr[i]--; return bytesToInetAddress(addr); }
java
{ "resource": "" }
q164962
Files.newReader
validation
@Beta public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); }
java
{ "resource": "" }
q164963
Files.write
validation
@Beta public static void write(byte[] from, File to) throws IOException { asByteSink(to).write(from); }
java
{ "resource": "" }
q164964
Files.copy
validation
@Beta public static void copy(File from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); }
java
{ "resource": "" }
q164965
Files.copy
validation
@Beta public static void copy(File from, File to) throws IOException { checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); asByteSource(from).copyTo(asByteSink(to)); }
java
{ "resource": "" }
q164966
Files.touch
validation
@Beta @SuppressWarnings("GoodTime") // reading system time without TimeSource public static void touch(File file) throws IOException { checkNotNull(file); if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) { throw new IOException("Unable to update modification time of " + file); } }
java
{ "resource": "" }
q164967
Files.readFirstLine
validation
@Beta @Deprecated public static String readFirstLine(File file, Charset charset) throws IOException { return asCharSource(file, charset).readFirstLine(); }
java
{ "resource": "" }
q164968
ImmutableBiMap.builderWithExpectedSize
validation
@Beta public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) { checkNonnegative(expectedSize, "expectedSize"); return new Builder<>(expectedSize); }
java
{ "resource": "" }
q164969
ImmutableBiMap.forcePut
validation
@CanIgnoreReturnValue @Deprecated @Override public V forcePut(K key, V value) { throw new UnsupportedOperationException(); }
java
{ "resource": "" }
q164970
MinMaxPriorityQueue.create
validation
public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create( Iterable<? extends E> initialContents) { return new Builder<E>(Ordering.<E>natural()).create(initialContents); }
java
{ "resource": "" }
q164971
MinMaxPriorityQueue.calculateNewCapacity
validation
private int calculateNewCapacity() { int oldCapacity = queue.length; int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3); return capAtMaximumSize(newCapacity, maximumSize); }
java
{ "resource": "" }
q164972
Murmur3_32HashFunction.fmix
validation
private static HashCode fmix(int h1, int length) { h1 ^= length; h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return HashCode.fromInt(h1); }
java
{ "resource": "" }
q164973
ElementOrder.natural
validation
public static <S extends Comparable<? super S>> ElementOrder<S> natural() { return new ElementOrder<S>(Type.SORTED, Ordering.<S>natural()); }
java
{ "resource": "" }
q164974
Monitor.enter
validation
@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enter(long time, TimeUnit unit) { final long timeoutNanos = toSafeNanos(time, unit); final ReentrantLock lock = this.lock; if (!fair && lock.tryLock()) { return true; } boolean interrupted = Thread.interrupted(); try { final long startTime = System.nanoTime(); for (long remainingNanos = timeoutNanos; ; ) { try { return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS); } catch (InterruptedException interrupt) { interrupted = true; remainingNanos = remainingNanos(startTime, timeoutNanos); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
java
{ "resource": "" }
q164975
Monitor.enterInterruptibly
validation
@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException { return lock.tryLock(time, unit); }
java
{ "resource": "" }
q164976
Monitor.enterWhen
validation
public void enterWhen(Guard guard) throws InterruptedException { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lockInterruptibly(); boolean satisfied = false; try { if (!guard.isSatisfied()) { await(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } }
java
{ "resource": "" }
q164977
Monitor.enterWhen
validation
@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException { final long timeoutNanos = toSafeNanos(time, unit); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean reentrant = lock.isHeldByCurrentThread(); long startTime = 0L; locked: { if (!fair) { // Check interrupt status to get behavior consistent with fair case. if (Thread.interrupted()) { throw new InterruptedException(); } if (lock.tryLock()) { break locked; } } startTime = initNanoTime(timeoutNanos); if (!lock.tryLock(time, unit)) { return false; } } boolean satisfied = false; boolean threw = true; try { satisfied = guard.isSatisfied() || awaitNanos( guard, (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos), reentrant); threw = false; return satisfied; } finally { if (!satisfied) { try { // Don't need to signal if timed out, but do if interrupted if (threw && !reentrant) { signalNextWaiter(); } } finally { lock.unlock(); } } } }
java
{ "resource": "" }
q164978
Monitor.enterWhenUninterruptibly
validation
public void enterWhenUninterruptibly(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lock(); boolean satisfied = false; try { if (!guard.isSatisfied()) { awaitUninterruptibly(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } }
java
{ "resource": "" }
q164979
Monitor.enterIf
validation
public boolean enterIf(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; lock.lock(); boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }
java
{ "resource": "" }
q164980
Monitor.enterIf
validation
@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean enterIf(Guard guard, long time, TimeUnit unit) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } if (!enter(time, unit)) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }
java
{ "resource": "" }
q164981
Monitor.enterIfInterruptibly
validation
public boolean enterIfInterruptibly(Guard guard) throws InterruptedException { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; lock.lockInterruptibly(); boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }
java
{ "resource": "" }
q164982
Monitor.tryEnterIf
validation
public boolean tryEnterIf(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; if (!lock.tryLock()) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } }
java
{ "resource": "" }
q164983
Monitor.waitFor
validation
public void waitFor(Guard guard) throws InterruptedException { if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { await(guard, true); } }
java
{ "resource": "" }
q164984
Monitor.waitForUninterruptibly
validation
public void waitForUninterruptibly(Guard guard) { if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { awaitUninterruptibly(guard, true); } }
java
{ "resource": "" }
q164985
Monitor.waitForUninterruptibly
validation
@SuppressWarnings("GoodTime") // should accept a java.time.Duration public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) { final long timeoutNanos = toSafeNanos(time, unit); if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (guard.isSatisfied()) { return true; } boolean signalBeforeWaiting = true; final long startTime = initNanoTime(timeoutNanos); boolean interrupted = Thread.interrupted(); try { for (long remainingNanos = timeoutNanos; ; ) { try { return awaitNanos(guard, remainingNanos, signalBeforeWaiting); } catch (InterruptedException interrupt) { interrupted = true; if (guard.isSatisfied()) { return true; } signalBeforeWaiting = false; remainingNanos = remainingNanos(startTime, timeoutNanos); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
java
{ "resource": "" }
q164986
Monitor.getWaitQueueLength
validation
public int getWaitQueueLength(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } lock.lock(); try { return guard.waiterCount; } finally { lock.unlock(); } }
java
{ "resource": "" }
q164987
Monitor.signalNextWaiter
validation
@GuardedBy("lock") private void signalNextWaiter() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { if (isSatisfied(guard)) { guard.condition.signal(); break; } } }
java
{ "resource": "" }
q164988
Monitor.signalAllWaiters
validation
@GuardedBy("lock") private void signalAllWaiters() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { guard.condition.signalAll(); } }
java
{ "resource": "" }
q164989
Monitor.beginWaitingFor
validation
@GuardedBy("lock") private void beginWaitingFor(Guard guard) { int waiters = guard.waiterCount++; if (waiters == 0) { // push guard onto activeGuards guard.next = activeGuards; activeGuards = guard; } }
java
{ "resource": "" }
q164990
Monitor.endWaitingFor
validation
@GuardedBy("lock") private void endWaitingFor(Guard guard) { int waiters = --guard.waiterCount; if (waiters == 0) { // unlink guard from activeGuards for (Guard p = activeGuards, pred = null; ; pred = p, p = p.next) { if (p == guard) { if (pred == null) { activeGuards = p.next; } else { pred.next = p.next; } p.next = null; // help GC break; } } } }
java
{ "resource": "" }
q164991
Monitor.awaitNanos
validation
@GuardedBy("lock") private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting) throws InterruptedException { boolean firstTime = true; try { do { if (nanos <= 0L) { return false; } if (firstTime) { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); firstTime = false; } nanos = guard.condition.awaitNanos(nanos); } while (!guard.isSatisfied()); return true; } finally { if (!firstTime) { endWaitingFor(guard); } } }
java
{ "resource": "" }
q164992
MoreExecutors.shutdownAndAwaitTermination
validation
@Beta @CanIgnoreReturnValue @GwtIncompatible // concurrency @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static boolean shutdownAndAwaitTermination( ExecutorService service, long timeout, TimeUnit unit) { long halfTimeoutNanos = unit.toNanos(timeout) / 2; // Disable new tasks from being submitted service.shutdown(); try { // Wait for half the duration of the timeout for existing tasks to terminate if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { // Cancel currently executing tasks service.shutdownNow(); // Wait the other half of the timeout for tasks to respond to being cancelled service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); } } catch (InterruptedException ie) { // Preserve interrupt status Thread.currentThread().interrupt(); // (Re-)Cancel if current thread also interrupted service.shutdownNow(); } return service.isTerminated(); }
java
{ "resource": "" }
q164993
CharSink.write
validation
public void write(CharSequence charSequence) throws IOException { checkNotNull(charSequence); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); out.append(charSequence); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
java
{ "resource": "" }
q164994
ExecutionList.execute
validation
public void execute() { // Lock while we update our state so the add method above will finish adding any listeners // before we start to run them. RunnableExecutorPair list; synchronized (this) { if (executed) { return; } executed = true; list = runnables; runnables = null; // allow GC to free listeners even if this stays around for a while. } // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are // in the opposite order from how they were added so we need to reverse the list to fulfill our // contract. // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we could // drop the contract on the method that enforces this queue like behavior since depending on it // is likely to be a bug anyway. // N.B. All writes to the list and the next pointers must have happened before the above // synchronized block, so we can iterate the list without the lock held here. RunnableExecutorPair reversedList = null; while (list != null) { RunnableExecutorPair tmp = list; list = list.next; tmp.next = reversedList; reversedList = tmp; } while (reversedList != null) { executeListener(reversedList.runnable, reversedList.executor); reversedList = reversedList.next; } }
java
{ "resource": "" }
q164995
LittleEndianByteArray.load64Safely
validation
static long load64Safely(byte[] input, int offset, int length) { long result = 0; // Due to the way we shift, we can stop iterating once we've run out of data, the rest // of the result already being filled with zeros. // This loop is critical to performance, so please check HashBenchmark if altering it. int limit = Math.min(length, 8); for (int i = 0; i < limit; i++) { // Shift value left while iterating logically through the array. result |= (input[offset + i] & 0xFFL) << (i * 8); } return result; }
java
{ "resource": "" }
q164996
LittleEndianByteArray.store64
validation
static void store64(byte[] sink, int offset, long value) { // We don't want to assert in production code. assert offset >= 0 && offset + 8 <= sink.length; // Delegates to the fast (unsafe)version or the fallback. byteArray.putLongLittleEndian(sink, offset, value); }
java
{ "resource": "" }
q164997
LittleEndianByteArray.load32
validation
static int load32(byte[] source, int offset) { // TODO(user): Measure the benefit of delegating this to LittleEndianBytes also. return (source[offset] & 0xFF) | ((source[offset + 1] & 0xFF) << 8) | ((source[offset + 2] & 0xFF) << 16) | ((source[offset + 3] & 0xFF) << 24); }
java
{ "resource": "" }
q164998
MediaType.create
validation
public static MediaType create(String type, String subtype) { MediaType mediaType = create(type, subtype, ImmutableListMultimap.<String, String>of()); mediaType.parsedCharset = Optional.absent(); return mediaType; }
java
{ "resource": "" }
q164999
MediaType.parse
validation
public static MediaType parse(String input) { checkNotNull(input); Tokenizer tokenizer = new Tokenizer(input); try { String type = tokenizer.consumeToken(TOKEN_MATCHER); tokenizer.consumeCharacter('/'); String subtype = tokenizer.consumeToken(TOKEN_MATCHER); ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder(); while (tokenizer.hasMore()) { tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); tokenizer.consumeCharacter(';'); tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); String attribute = tokenizer.consumeToken(TOKEN_MATCHER); tokenizer.consumeCharacter('='); final String value; if ('"' == tokenizer.previewChar()) { tokenizer.consumeCharacter('"'); StringBuilder valueBuilder = new StringBuilder(); while ('"' != tokenizer.previewChar()) { if ('\\' == tokenizer.previewChar()) { tokenizer.consumeCharacter('\\'); valueBuilder.append(tokenizer.consumeCharacter(ascii())); } else { valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER)); } } value = valueBuilder.toString(); tokenizer.consumeCharacter('"'); } else { value = tokenizer.consumeToken(TOKEN_MATCHER); } parameters.put(attribute, value); } return create(type, subtype, parameters.build()); } catch (IllegalStateException e) { throw new IllegalArgumentException("Could not parse '" + input + "'", e); } }
java
{ "resource": "" }