code
stringlengths
73
34.1k
label
stringclasses
1 value
public static int skipElement(XMLStreamReader xmlReader) throws XMLStreamException { if (!xmlReader.isStartElement()) { throw new XMLStreamException("Current node is not start element"); } if (!xmlReader.isEndElement()) { for (xmlReader.next(); !xmlReader.isEndElemen...
java
public static boolean isDependency(Extension extension, String namespace) { boolean isDependency = false; if (namespace == null) { isDependency = extension.getProperty(PKEY_DEPENDENCY, false); } else { Object namespacesObject = extension.getProperty(PKEY_NAMESPACES);...
java
public void setNamespaceProperty(String key, Object value, String namespace) { try { this.propertiesLock.lock(); Map<String, Object> namespaceProperties = getNamespaceProperties(namespace); if (namespaceProperties != null) { namespaceProperties.put(key, v...
java
public void startStep(String translationKey, String message, Object... arguments) { this.progress.startStep(this, new Message(translationKey, message, arguments)); }
java
private void performUnArchive() throws MojoExecutionException { Artifact artifact = findArtifact(); getLog().debug(String.format("Source XAR = [%s]", artifact.getFile())); unpack(artifact.getFile(), this.outputDirectory, "XAR Plugin", true, getIncludes(), getExcludes()); unpackDepen...
java
protected void unpackDependentXars(Artifact artifact) throws MojoExecutionException { try { Set<Artifact> dependencies = resolveArtifactDependencies(artifact); for (Artifact dependency : dependencies) { unpack(dependency.getFile(), this.outputDirectory, "XAR Plugin", ...
java
private void customizeEviction(ConfigurationBuilder builder) { EntryEvictionConfiguration eec = (EntryEvictionConfiguration) getCacheConfiguration().get(EntryEvictionConfiguration.CONFIGURATIONID); if (eec != null && eec.getAlgorithm() == EntryEvictionConfiguration.Algorithm.LRU) { ...
java
private void completeFilesystem(ConfigurationBuilder builder, Configuration configuration) { PersistenceConfigurationBuilder persistence = builder.persistence(); if (containsIncompleteFileLoader(configuration)) { for (StoreConfigurationBuilder<?, ?> store : persistence.stores()) { ...
java
public Configuration customize(Configuration defaultConfiguration, Configuration namedConfiguration) { // Set custom configuration ConfigurationBuilder builder = new ConfigurationBuilder(); // Named configuration have priority if (namedConfiguration != null) { read(buil...
java
public boolean containLogsFrom(LogLevel level) { for (LogEvent log : this) { if (log.getLevel().compareTo(level) <= 0) { return true; } } return false; }
java
@Override public InputStream openStream() { /* * https://jira.jboss.org/jira/browse/TMPARCH-19 If class is loaded by the Bootstrap ClassLoader, getClassLoader * will return null. Use Thread Current Context ClassLoader instead. */ ClassLoader classLoader = clazz.getClassLoa...
java
private ArchivePath calculatePath(File root, File child) { String rootPath = unifyPath(root.getPath()); String childPath = unifyPath(child.getPath()); String archiveChildPath = childPath.replaceFirst(Pattern.quote(rootPath), ""); return new BasicPath(archiveChildPath); }
java
private void initialize(int blockSize, int recordSize) { this.debug = false; this.blockSize = blockSize; this.recordSize = recordSize; this.recsPerBlock = (this.blockSize / this.recordSize); this.blockBuffer = new byte[this.blockSize]; if (this.inStream != null) { ...
java
public boolean isEOFRecord(byte[] record) { for (int i = 0, sz = this.getRecordSize(); i < sz; ++i) { if (record[i] != 0) { return false; } } return true; }
java
public void skipRecord() throws IOException { if (this.debug) { System.err.println("SkipRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx); } if (this.inStream == null) { throw new IOException("reading (via skip) from an output buffer"); } ...
java
public byte[] readRecord() throws IOException { if (this.debug) { System.err.println("ReadRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx); } if (this.inStream == null) { throw new IOException("reading from an output buffer"); } if ...
java
public void writeRecord(byte[] record) throws IOException { if (this.debug) { System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx); } if (this.outStream == null) { throw new IOException("writing to an input buffer"); } ...
java
public void writeRecord(byte[] buf, int offset) throws IOException { if (this.debug) { System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx); } if (this.outStream == null) { throw new IOException("writing to an input buffer"); ...
java
private void writeBlock() throws IOException { if (this.debug) { System.err.println("WriteBlock: blkIdx = " + this.currBlkIdx); } if (this.outStream == null) { throw new IOException("writing to an input buffer"); } this.outStream.write(this.blockBuffer, ...
java
private void flushBlock() throws IOException { if (this.debug) { System.err.println("TarBuffer.flushBlock() called."); } if (this.outStream == null) { throw new IOException("writing to an input buffer"); } // Thanks to 'Todd Kofford <tkofford@bigfoot.com...
java
public void close() throws IOException { if (this.debug) { System.err.println("TarBuffer.closeBuffer()."); } if (this.outStream != null) { this.flushBlock(); if (this.outStream != System.out && this.outStream != System.err) { this.outStream.c...
java
private Node removeNodeRecursively(final NodeImpl node, final ArchivePath path) { final NodeImpl parentNode = content.get(path.getParent()); if (parentNode != null) { parentNode.removeChild(node); } // Remove from nested archives if present nestedArchives.remove(path...
java
private boolean nestedContains(ArchivePath path) { // Iterate through nested archives for (Entry<ArchivePath, ArchiveAsset> nestedArchiveEntry : nestedArchives.entrySet()) { ArchivePath archivePath = nestedArchiveEntry.getKey(); ArchiveAsset archiveAsset = nestedArchiveEntry.getV...
java
private Node getNestedNode(ArchivePath path) { // Iterate through nested archives for (Entry<ArchivePath, ArchiveAsset> nestedArchiveEntry : nestedArchives.entrySet()) { ArchivePath archivePath = nestedArchiveEntry.getKey(); ArchiveAsset archiveAsset = nestedArchiveEntry.getValue...
java
private boolean startsWith(ArchivePath fullPath, ArchivePath startingPath) { final String context = fullPath.get(); final String startingContext = startingPath.get(); return context.startsWith(startingContext); }
java
private ArchivePath getNestedPath(ArchivePath fullPath, ArchivePath basePath) { final String context = fullPath.get(); final String baseContent = basePath.get(); // Remove the base path from the full path String nestedArchiveContext = context.substring(baseContent.length()); re...
java
private void initialize() { this.file = null; this.header = new TarHeader(); this.gnuFormat = false; this.ustarFormat = true; // REVIEW What we prefer to use... this.unixFormat = false; }
java
public boolean isDescendent(TarEntry desc) { return desc.header.name.toString().startsWith(this.header.name.toString()); }
java
public boolean isDirectory() { if (this.file != null) { return this.file.isDirectory(); } if (this.header != null) { if (this.header.linkFlag == TarHeader.LF_DIR) { return true; } if (this.header.name.toString().endsWith...
java
public void getFileTarHeader(TarHeader hdr, File file) throws InvalidHeaderException { this.file = file; String name = file.getPath(); String osname = System.getProperty("os.name"); if (osname != null) { // Strip off drive letters! // REVIEW Would a better...
java
public TarEntry[] getDirectoryEntries() throws InvalidHeaderException { if (this.file == null || !this.file.isDirectory()) { return new TarEntry[0]; } String[] list = this.file.list(); TarEntry[] result = new TarEntry[list.length]; for (int i = 0; i < list...
java
public long computeCheckSum(byte[] buf) { long sum = 0; for (int i = 0; i < buf.length; ++i) { sum += 255 & buf[i]; } return sum; }
java
public void writeEntryHeader(byte[] outbuf) throws InvalidHeaderException { int offset = 0; if (this.isUnixTarFormat()) { if (this.header.name.length() > 100) { throw new InvalidHeaderException("file path is greater than 100 characters, " + this.header.name); ...
java
public void nameTarHeader(TarHeader hdr, String name) { boolean isDir = name.endsWith("/"); this.gnuFormat = false; this.ustarFormat = true; this.unixFormat = false; hdr.checkSum = 0; hdr.devMajor = 0; hdr.devMinor = 0; hdr.name = new StringB...
java
private void doCopy() throws IOException { int copied = IOUtil.copy(currentNodeStream, outputStream, BUFFER_LENGTH); if (copied == -1) { currentNodeStream.close(); currentNodeStream = null; endAsset(); } }
java
private void startAsset(final String path, final Asset asset) throws IOException { putNextEntry(outputStream, path, asset); }
java
String getProperty(String key) { String value = properties.get(key); if (value == null) { throw new RuntimeException("No property value found for key " + key); } return value; }
java
private void init() throws IOException { bsPutUByte('B'); bsPutUByte('Z'); this.data = new Data(this.blockSize100k); this.blockSorter = new BlockSort(this.data); // huffmanised magic bytes bsPutUByte('h'); bsPutUByte('0' + this.blockSize100k); this.comb...
java
private void write0(int b) throws IOException { if (this.currentChar != -1) { b &= 0xff; if (this.currentChar == b) { if (++this.runLength > 254) { writeRun(); this.currentChar = -1; this.runLength = 0; ...
java
public static String optionallyRemovePrecedingSlash(final String path) { // Precondition check assertSpecified(path); // Is there's a first character of slash if (isFirstCharSlash(path)) { // Return everything but first char return path.substring(1); } ...
java
public static String optionallyRemoveFollowingSlash(final String path) { // Precondition check assertSpecified(path); // Is there's a last character of slash if (isLastCharSlash(path)) { // Return everything but last char return path.substring(0, path.length() - ...
java
public static String optionallyAppendSlash(final String path) { // Precondition check assertSpecified(path); // If the last character is not a slash if (!isLastCharSlash(path)) { // Append return path + ArchivePath.SEPARATOR; } // Return as-is ...
java
public static String optionallyPrependSlash(final String path) { // Adjust null String resolved = path; if (resolved == null) { resolved = EMPTY; } // If the first character is not a slash if (!isFirstCharSlash(resolved)) { // Prepend the slash ...
java
private static boolean isFirstCharSlash(final String path) { assertSpecified(path); if (path.length() == 0) { return false; } return path.charAt(0) == ArchivePath.SEPARATOR; }
java
private void initialize(int recordSize) { this.rootPath = null; this.pathPrefix = null; this.tempPath = System.getProperty("user.dir"); this.userId = 0; this.userName = ""; this.groupId = 0; this.groupName = ""; this.debug = false; thi...
java
public void setDebug(boolean debugF) { this.debug = debugF; if (this.tarIn != null) { this.tarIn.setDebug(debugF); } else if (this.tarOut != null) { this.tarOut.setDebug(debugF); } }
java
public void setUserInfo(int userId, String userName, int groupId, String groupName) { this.userId = userId; this.userName = userName; this.groupId = groupId; this.groupName = groupName; }
java
public int getRecordSize() { if (this.tarIn != null) { return this.tarIn.getRecordSize(); } else if (this.tarOut != null) { return this.tarOut.getRecordSize(); } return TarBuffer.DEFAULT_RCDSIZE; }
java
private String getTempFilePath(File eFile) { String pathStr = this.tempPath + File.separator + eFile.getName() + ".tmp"; for (int i = 1; i < 5; ++i) { File f = new File(pathStr); if (!f.exists()) { break; } pathStr = this.tempP...
java
public void listContents() throws IOException { for (;;) { TarEntry entry = this.tarIn.getNextEntry(); if (entry == null) { if (this.debug) { System.err.println("READ EOF RECORD"); } break; } ...
java
public void extractContents(File destDir) throws IOException { for (;;) { TarEntry entry = this.tarIn.getNextEntry(); if (entry == null) { if (this.debug) { System.err.println("READ EOF RECORD"); } break; ...
java
private void fswap(int[] fmap, int zz1, int zz2) { int zztmp = fmap[zz1]; fmap[zz1] = fmap[zz2]; fmap[zz2] = zztmp; }
java
private void fvswap(int[] fmap, int yyp1, int yyp2, int yyn) { while (yyn > 0) { fswap(fmap, yyp1, yyp2); yyp1++; yyp2++; yyn--; } }
java
void setDefaults() { // If no ClassLoaders are specified, use the TCCL // Ensure we default this BEFORE defaulting the extension loader, as // the loader needs a CL to be created if (this.getClassLoaders() == null) { final ClassLoader tccl = SecurityActions.getThreadContextCl...
java
public static boolean matches(byte[] signature, int length) { if (length < 3) { return false; } if (signature[0] != 'B') { return false; } if (signature[1] != 'Z') { return false; } if (signature[2] != 'h') { ret...
java
public static URLPackageScanner newInstance(boolean addRecursively, final ClassLoader classLoader, final Callback callback, final String packageName) { Validate.notNull(packageName, "Package name must be specified"); Validate.notNull(addRecursively, "AddRe...
java
static byte[] asByteArray(final InputStream in) throws IllegalArgumentException { // Precondition check if (in == null) { throw new IllegalArgumentException("stream must be specified"); } // Get content as an array of bytes final ByteArrayOutputStream out = new ByteA...
java
public static String asUTF8String(InputStream in) { // Precondition check Validate.notNull(in, "Stream must be specified"); StringBuilder buffer = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(in, CHARSET_UT...
java
public static void bufferedWriteWithFlush(final OutputStream output, final byte[] content) throws IOException { final int size = 4096; int offset = 0; while (content.length - offset > size) { output.write(content, offset, size); offset += size; } output.wr...
java
public static void copyWithClose(InputStream input, OutputStream output) throws IOException { try { copy(input, output); } finally { try { input.close(); } catch (final IOException ignore) { if (log.isLoggable(Level.FINER)) { ...
java
@Override public InputStream openStream() { try { return new BufferedInputStream(new FileInputStream(file), 8192); } catch (FileNotFoundException e) { throw new RuntimeException("Could not open file " + file, e); } }
java
public static long parseOctal(byte[] header, int offset, int length) throws InvalidHeaderException { long result = 0; boolean stillPadding = true; int end = offset + length; for (int i = offset; i < end; ++i) { if (header[i] == 0) { break; ...
java
public static StringBuffer parseName(byte[] header, int offset, int length) throws InvalidHeaderException { StringBuffer result = new StringBuffer(length); int end = offset + length; for (int i = offset; i < end; ++i) { if (header[i] == 0) { break; ...
java
public static int getNameBytes(StringBuffer name, byte[] buf, int offset, int length) { int i; for (i = 0; i < length && i < name.length(); ++i) { buf[offset + i] = (byte) name.charAt(i); } for (; i < length; ++i) { buf[offset + i] = 0; } ...
java
public static int getOctalBytes(long value, byte[] buf, int offset, int length) { int idx = length - 1; buf[offset + idx] = 0; --idx; buf[offset + idx] = (byte) ' '; --idx; if (value == 0) { buf[offset + idx] = (byte) '0'; --idx; ...
java
public static int getCheckSumOctalBytes(long value, byte[] buf, int offset, int length) { TarHeader.getOctalBytes(value, buf, offset, length); buf[offset + length - 1] = (byte) ' '; buf[offset + length - 2] = 0; return offset + length; }
java
private String merge(final String first, final String[] more) { assert first != null : "first must be specified"; assert more != null : "more must be specified"; final StringBuilder merged = new StringBuilder(); merged.append(first); for (int i = 0; i < more.length; i++) { ...
java
protected final T covariantReturn() { try { return this.getActualClass().cast(this); } catch (final ClassCastException cce) { log.log(Level.SEVERE, "The class specified by getActualClass is not a valid assignment target for this instance;" + " ...
java
@Override public Path toAbsolutePath() { // Already absolute? if (this.isAbsolute()) { return this; } // Else construct a new absolute path and normalize it final Path absolutePath = new ShrinkWrapPath(ArchivePath.SEPARATOR + this.path, this.fileSystem); ...
java
private static List<String> tokenize(final ShrinkWrapPath path) { final StringTokenizer tokenizer = new StringTokenizer(path.toString(), ArchivePath.SEPARATOR_STRING); final List<String> tokens = new ArrayList<>(); while (tokenizer.hasMoreTokens()) { tokens.add(tokenizer.nextToken())...
java
private static String normalize(final List<String> path, boolean absolute) { assert path != null : "path must be specified"; // Remove unnecessary references to this dir if (path.contains(DIR_THIS)) { path.remove(DIR_THIS); normalize(path, absolute); } /...
java
private static ShrinkWrapPath relativizeCommonRoot(final ShrinkWrapPath thisOriginal, final Path thisCurrent, final Path otherOriginal, Path otherCurrent, final int backupCount) { // Preconditions assert thisOriginal != null; assert thisCurrent != null; assert otherOriginal != nu...
java
protected void doExport() { // Get archive final Archive<?> archive = getArchive(); if (log.isLoggable(Level.FINE)) { log.fine("Exporting archive - " + archive.getName()); } // Obtain the root final Node rootNode = archive.get(ArchivePaths.root()); /...
java
private void processNode(final Node node) { processNode(node.getPath(), node); Set<Node> children = node.getChildren(); for (Node child : children) { processNode(child); } }
java
private void processArchiveAsset(File parentDirectory, ArchiveAsset nestedArchiveAsset) { // Get the nested archive Archive<?> nestedArchive = nestedArchiveAsset.getArchive(); nestedArchive.as(ExplodedExporter.class).exportExploded(parentDirectory); }
java
private File validateOutputDirectory(File outputDirectory) { // Create output directory if (!outputDirectory.mkdir() && !outputDirectory.exists()) { throw new ArchiveExportException("Unable to create archive output directory - " + outputDirectory); } if (outputDirectory.isFil...
java
private Archive<?> getArchive(final Path path) { assert path != null : "Path must be specified"; final FileSystem fs = path.getFileSystem(); assert fs != null : "File system is null"; // Could be user error in this case, passing in a Path from another provider if (!(fs instanceof...
java
private File fileFromResource(final String resourceName) throws IllegalArgumentException { final URL resourceUrl = AccessController.doPrivileged(GetTcclAction.INSTANCE).getResource(resourceName); Validate.notNull(resourceUrl, resourceName + " doesn't exist or can't be accessed"); String resourc...
java
private void writeObject(final ObjectOutputStream out) throws IOException { // Default write of non-transient fields out.defaultWriteObject(); // Write as ZIP final InputStream in = archive.as(ZipExporter.class).exportAsInputStream(); try { IOUtil.copy(in, out); // D...
java
private Format decimalFormat(int fractionPrecision) { DecimalFormat format; if (fractionPrecision == 0) { format = new DecimalFormat("###0"); } else if (fractionPrecision > 0) { StringBuilder formatSb = new StringBuilder(); formatSb.append("###0."); appendChars(formatSb, ZERO_CHARS, fractionPrecision)...
java
@Override public Object extractValueFromBytes(int offset, byte[] bytes, boolean required) { // we don't need to extract the value if all we are doing is matching if (!required) { return EMPTY; } if (offset >= bytes.length) { return null; } // length is from the first byte of the string int len = (b...
java
public void readEntries(BufferedReader lineReader, ErrorCallBack errorCallBack) throws IOException { final MagicEntry[] levelParents = new MagicEntry[MAX_LEVELS]; MagicEntry previousEntry = null; while (true) { String line = lineReader.readLine(); if (line == null) { break; } // skip blanks and co...
java
public void optimizeFirstBytes() { // now we post process the entries and remove the first byte ones we can optimize for (MagicEntry entry : entryList) { byte[] startingBytes = entry.getStartsWithByte(); if (startingBytes == null || startingBytes.length == 0) { continue; } int index = (0xFF & starti...
java
public ContentInfo findMatch(byte[] bytes) { if (bytes.length == 0) { return ContentInfo.EMPTY_INFO; } // first do the start byte ones int index = (0xFF & bytes[0]); if (index < firstByteEntryLists.length && firstByteEntryLists[index] != null) { ContentInfo info = findMatch(bytes, firstByteEntryLists[in...
java
public void format(StringBuilder sb, Object value) { if (prefix != null) { sb.append(prefix); } if (percentExpression != null && value != null) { percentExpression.append(value, sb); } if (suffix != null) { sb.append(suffix); } }
java
public ContentInfo findMatch(File file) throws IOException { int readSize = fileReadSize; if (!file.exists()) { throw new IOException("File does not exist: " + file); } if (!file.canRead()) { throw new IOException("File is not readable: " + file); } long length = file.length(); if (length <= 0) { ...
java
public ContentInfo findMatch(byte[] bytes) { if (bytes.length == 0) { return ContentInfo.EMPTY_INFO; } else { return magicEntries.findMatch(bytes); } }
java
public static ContentInfo findExtensionMatch(String name) { name = name.toLowerCase(); // look up the whole name first ContentType type = ContentType.fromFileExtension(name); if (type != ContentType.OTHER) { return new ContentInfo(type); } // now find the .ext part, if any int index = name.lastIndexO...
java
public static ContentInfo findMimeTypeMatch(String mimeType) { ContentType type = ContentType.fromMimeType(mimeType.toLowerCase()); if (type == ContentType.OTHER) { return null; } else { return new ContentInfo(type); } }
java
static List<PatternLevel> readLevelResourceFile(InputStream stream) { List<PatternLevel> levels = null; if (stream != null) { try { levels = configureClassLevels(stream); } catch (IOException e) { System.err.println( "IO exception reading the log properties file '" + LOCAL_LOG_PROPERTIES_FILE + ...
java
private void loadFile(String resourcePath) { InputStream stream = getClass().getResourceAsStream(resourcePath); if (stream == null) { throw new IllegalArgumentException(resourcePath + " is missing"); } BufferedReader lineReader = null; try { lineReader = new BufferedReader(new InputStreamReader(new GZIP...
java
ContentInfo matchBytes(byte[] bytes) { ContentData data = matchBytes(bytes, 0, 0, null); if (data == null || data.name == MagicEntryParser.UNKNOWN_NAME) { return null; } else { return new ContentInfo(data.name, data.mimeType, data.sb.toString(), data.partial); } }
java
private ContentData matchBytes(byte[] bytes, int prevOffset, int level, ContentData contentData) { int offset = this.offset; if (offsetInfo != null) { // offset can be null if we run out of bytes Integer maybeOffset = offsetInfo.getOffset(bytes); if (maybeOffset == null) { return null; } offset =...
java
public static String preProcessPattern(String pattern) { int index = pattern.indexOf('\\'); if (index < 0) { return pattern; } StringBuilder sb = new StringBuilder(); for (int pos = 0; pos < pattern.length();) { char ch = pattern.charAt(pos); if (ch != '\\') { sb.append(ch); pos++; conti...
java
public static int staticCompare(Number extractedValue, Number testValue) { long extractedLong = extractedValue.longValue(); long testLong = testValue.longValue(); if (extractedLong > testLong) { return 1; } else if (extractedLong < testLong) { return -1; } else { return 0; } }
java
protected String findOffsetMatch(TestInfo info, int startOffset, MutableOffset mutableOffset, final byte[] bytes, final char[] chars, final int maxPos) { // verify the starting offset if (startOffset < 0) { return null; } int targetPos = startOffset; boolean lastMagicCompactWhitespace = false; for (...
java
public String next() { if (next == null) { throw new NoSuchElementException(); } String s = next; advance(); return s; }
java
private synchronized void print(String output) { if (generateOneDoc) writer.print(output); else writer.println(output); }
java
public void finish() { for (Map.Entry<String, String> entry : posTags.entrySet()) { posWriter.println(entry.getKey() + " " + entry.getValue()); } posWriter.flush(); posWriter.close(); writer.flush(); writer.close(); }
java
public static void findXmlFiles(ChildesParser parser, boolean utterancePerDoc, File directory) { File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) findXmlFiles(parser...
java