code
stringlengths
73
34.1k
label
stringclasses
1 value
private static void handleResourceLoader(final Object resourceLoader, final ClassLoader classLoader, final ClasspathOrder classpathOrderOut, final ScanSpec scanSpec, final LogNode log) { if (resourceLoader == null) { return; } // PathResourceLoader has root field, which i...
java
private static void handleRealModule(final Object module, final Set<Object> visitedModules, final ClassLoader classLoader, final ClasspathOrder classpathOrderOut, final ScanSpec scanSpec, final LogNode log) { if (!visitedModules.add(module)) { // Avoid extracting paths from t...
java
private static boolean matchesPatternList(final String str, final List<Pattern> patterns) { if (patterns != null) { for (final Pattern pattern : patterns) { if (pattern.matcher(str).matches()) { return true; } } } return...
java
private static void quoteList(final Collection<String> coll, final StringBuilder buf) { buf.append('['); boolean first = true; for (final String item : coll) { if (first) { first = false; } else { buf.append(", "); } ...
java
@Override public String getModuleName() { String moduleName = moduleNameFromModuleDescriptor; if (moduleName == null || moduleName.isEmpty()) { moduleName = moduleNameFromManifestFile; } if (moduleName == null || moduleName.isEmpty()) { if (derivedAutomaticMod...
java
String getZipFilePath() { return packageRootPrefix.isEmpty() ? zipFilePath : zipFilePath + "!/" + packageRootPrefix.substring(0, packageRootPrefix.length() - 1); }
java
private boolean filter(final String classpathElementPath) { if (scanSpec.classpathElementFilters != null) { for (final ClasspathElementFilter filter : scanSpec.classpathElementFilters) { if (!filter.includeClasspathElement(classpathElementPath)) { return false; ...
java
boolean addSystemClasspathEntry(final String pathEntry, final ClassLoader classLoader) { if (classpathEntryUniqueResolvedPaths.add(pathEntry)) { order.add(new SimpleEntry<>(pathEntry, classLoader)); return true; } return false; }
java
private boolean addClasspathEntry(final String pathEntry, final ClassLoader classLoader, final ScanSpec scanSpec) { if (scanSpec.overrideClasspath == null // && (SystemJarFinder.getJreLibOrExtJars().contains(pathEntry) || pathEntry.equals(SystemJarFinder.getJr...
java
public boolean addClasspathEntries(final String pathStr, final ClassLoader classLoader, final ScanSpec scanSpec, final LogNode log) { if (pathStr == null || pathStr.isEmpty()) { return false; } else { final String[] parts = JarUtils.smartPathSplit(pathStr); ...
java
private static TypeArgument parse(final Parser parser, final String definingClassName) throws ParseException { final char peek = parser.peek(); if (peek == '*') { parser.expect('*'); return new TypeArgument(Wildcard.ANY, null); } else if (peek == '+') { parser...
java
static List<TypeArgument> parseList(final Parser parser, final String definingClassName) throws ParseException { if (parser.peek() == '<') { parser.expect('<'); final List<TypeArgument> typeArguments = new ArrayList<>(2); while (parser.peek() != '>') { if (!pa...
java
private static void addBundleFile(final Object bundlefile, final Set<Object> path, final ClassLoader classLoader, final ClasspathOrder classpathOrderOut, final ScanSpec scanSpec, final LogNode log) { // Don't get stuck in infinite loop if (bundlefile != null && path.add(bundlefil...
java
private static void addClasspathEntries(final Object owner, final ClassLoader classLoader, final ClasspathOrder classpathOrderOut, final ScanSpec scanSpec, final LogNode log) { // type ClasspathEntry[] final Object entries = ReflectionUtils.getFieldVal(owner, "entries", false); if (e...
java
static ClassTypeSignature parse(final String typeDescriptor, final ClassInfo classInfo) throws ParseException { final Parser parser = new Parser(typeDescriptor); // The defining class name is used to resolve type variables using the defining class' type descriptor. // But here we are parsing the...
java
public TypeSignature getTypeDescriptor() { if (typeDescriptorStr == null) { return null; } if (typeDescriptor == null) { try { typeDescriptor = TypeSignature.parse(typeDescriptorStr, declaringClassName); typeDescriptor.setScanResult(scanRes...
java
public TypeSignature getTypeSignature() { if (typeSignatureStr == null) { return null; } if (typeSignature == null) { try { typeSignature = TypeSignature.parse(typeSignatureStr, declaringClassName); typeSignature.setScanResult(scanResult); ...
java
@Override public int compareTo(final FieldInfo other) { final int diff = declaringClassName.compareTo(other.declaringClassName); if (diff != 0) { return diff; } return name.compareTo(other.name); }
java
private List<ClasspathElementModule> getModuleOrder(final LogNode log) throws InterruptedException { final List<ClasspathElementModule> moduleCpEltOrder = new ArrayList<>(); if (scanSpec.overrideClasspath == null && scanSpec.overrideClassLoaders == null && scanSpec.scanModules) { // Add modu...
java
private static void findClasspathOrderRec(final ClasspathElement currClasspathElement, final Set<ClasspathElement> visitedClasspathElts, final List<ClasspathElement> order) { if (visitedClasspathElts.add(currClasspathElement)) { if (!currClasspathElement.skipClasspathElement) { ...
java
private static List<ClasspathElement> orderClasspathElements( final Collection<Entry<Integer, ClasspathElement>> classpathEltsIndexed) { final List<Entry<Integer, ClasspathElement>> classpathEltsIndexedOrdered = new ArrayList<>( classpathEltsIndexed); CollectionUtils.sortIfNo...
java
private List<ClasspathElement> findClasspathOrder(final Set<ClasspathElement> uniqueClasspathElements, final Queue<Entry<Integer, ClasspathElement>> toplevelClasspathEltsIndexed) { final List<ClasspathElement> toplevelClasspathEltsOrdered = orderClasspathElements( toplevelClasspathEl...
java
private <W> void processWorkUnits(final Collection<W> workUnits, final LogNode log, final WorkUnitProcessor<W> workUnitProcessor) throws InterruptedException, ExecutionException { WorkQueue.runWorkQueue(workUnits, executorService, interruptionChecker, numParallelTasks, log, workUnitP...
java
@Override public ScanResult call() throws InterruptedException, CancellationException, ExecutionException { ScanResult scanResult = null; Exception exception = null; final long scanStart = System.currentTimeMillis(); try { // Perform the scan scanResult = open...
java
public List<String> list() throws SecurityException { if (collectorsToList == null) { throw new IllegalArgumentException("Could not call Collectors.toList()"); } final Object /* Stream<String> */ resourcesStream = ReflectionUtils.invokeMethod(moduleReader, "list", /* ...
java
private Object openOrRead(final String path, final boolean open) throws SecurityException { final String methodName = open ? "open" : "read"; final Object /* Optional<InputStream> */ optionalInputStream = ReflectionUtils.invokeMethod(moduleReader, methodName, String.class, path, /* throw...
java
private static void findMetaAnnotations(final AnnotationInfo ai, final AnnotationInfoList allAnnotationsOut, final Set<ClassInfo> visited) { final ClassInfo annotationClassInfo = ai.getClassInfo(); if (annotationClassInfo != null && annotationClassInfo.annotationInfo != null // Don't...
java
public boolean containsName(final String methodName) { for (final MethodInfo mi : this) { if (mi.getName().equals(methodName)) { return true; } } return false; }
java
private int read(final int off, final int len) throws IOException { if (len == 0) { return 0; } if (inputStream != null) { // Wrapped InputStream return inputStream.read(buf, off, len); } else { // Wrapped ByteBuffer final int b...
java
private void readMore(final int bytesRequired) throws IOException { if ((long) used + (long) bytesRequired > FileUtils.MAX_BUFFER_SIZE) { // Since buf is an array, we're limited to reading 2GB per file throw new IOException("File is larger than 2GB, cannot read it"); } //...
java
public void skip(final int bytesToSkip) throws IOException { final int bytesToRead = Math.max(0, curr + bytesToSkip - used); if (bytesToRead > 0) { readMore(bytesToRead); } curr += bytesToSkip; }
java
public List<String> getPaths() { final List<String> resourcePaths = new ArrayList<>(this.size()); for (final Resource resource : this) { resourcePaths.add(resource.getPath()); } return resourcePaths; }
java
public static ClassGraphException newClassGraphException(final String message, final Throwable cause) throws ClassGraphException { return new ClassGraphException(message, cause); }
java
static ArrayTypeSignature parse(final Parser parser, final String definingClassName) throws ParseException { int numArrayDims = 0; while (parser.peek() == '[') { numArrayDims++; parser.next(); } if (numArrayDims > 0) { final TypeSignature elementTypeSi...
java
public static String normalizeURLPath(final String urlPath) { String urlPathNormalized = urlPath; if (!urlPathNormalized.startsWith("jrt:") && !urlPathNormalized.startsWith("http://") && !urlPathNormalized.startsWith("https://")) { // Any URL with the "jar:" prefix must have ...
java
public boolean canGetAsSlice() throws IOException, InterruptedException { final long dataStartOffsetWithinPhysicalZipFile = getEntryDataStartOffsetWithinPhysicalZipFile(); return !isDeflated // && dataStartOffsetWithinPhysicalZipFile / FileUtils.MAX_BUFFER_SIZE // == (dat...
java
public byte[] load() throws IOException, InterruptedException { try (InputStream is = open()) { return FileUtils.readAllBytesAsArray(is, uncompressedSize); } }
java
@Override public int compareTo(final FastZipEntry o) { final int diff0 = o.version - this.version; if (diff0 != 0) { return diff0; } final int diff1 = entryNameUnversioned.compareTo(o.entryNameUnversioned); if (diff1 != 0) { return diff1; } ...
java
private static boolean hasTypeVariables(final Type type) { if (type instanceof TypeVariable<?> || type instanceof GenericArrayType) { return true; } else if (type instanceof ParameterizedType) { for (final Type arg : ((ParameterizedType) type).getActualTypeArguments()) { ...
java
public Constructor<?> getConstructorForFieldTypeWithSizeHint(final Type fieldTypeFullyResolved, final ClassFieldCache classFieldCache) { if (!isTypeVariable) { return constructorForFieldTypeWithSizeHint; } else { final Class<?> fieldRawTypeFullyResolved = JSONUtils.ge...
java
public Constructor<?> getDefaultConstructorForFieldType(final Type fieldTypeFullyResolved, final ClassFieldCache classFieldCache) { if (!isTypeVariable) { return defaultConstructorForFieldType; } else { final Class<?> fieldRawTypeFullyResolved = JSONUtils.getRawType(f...
java
private static void appendPathElt(final Object pathElt, final StringBuilder buf) { if (buf.length() > 0) { buf.append(File.pathSeparatorChar); } // Escape any rogue path separators, as long as file separator is not '\\' (on Windows, if there are any // extra ';' characters in...
java
public static String leafName(final String path) { final int bangIdx = path.indexOf('!'); final int endIdx = bangIdx >= 0 ? bangIdx : path.length(); int leafStartIdx = 1 + (File.separatorChar == '/' ? path.lastIndexOf('/', endIdx) : Math.max(path.lastIndexOf('/', endIdx), path.la...
java
public static String classfilePathToClassName(final String classfilePath) { if (!classfilePath.endsWith(".class")) { throw new IllegalArgumentException("Classfile path does not end with \".class\": " + classfilePath); } return classfilePath.substring(0, classfilePath.length() - 6).re...
java
static BaseTypeSignature parse(final Parser parser) { switch (parser.peek()) { case 'B': parser.next(); return new BaseTypeSignature("byte"); case 'C': parser.next(); return new BaseTypeSignature("char"); case 'D': parser.next()...
java
private static String getPath(final Object classpath) { final Object container = ReflectionUtils.getFieldVal(classpath, "container", false); if (container == null) { return ""; } final Object delegate = ReflectionUtils.getFieldVal(container, "delegate", false); if (d...
java
Set<String> findReferencedClassNames() { final Set<String> allReferencedClassNames = new LinkedHashSet<>(); findReferencedClassNames(allReferencedClassNames); // Remove references to java.lang.Object allReferencedClassNames.remove("java.lang.Object"); return allReferencedClassNam...
java
private static Map<CharSequence, Object> getInitialIdToObjectMap(final Object objectInstance, final Object parsedJSON) { final Map<CharSequence, Object> idToObjectInstance = new HashMap<>(); if (parsedJSON instanceof JSONObject) { final JSONObject itemJsonObject = (JSONObject) pa...
java
private static <T> T deserializeObject(final Class<T> expectedType, final String json, final ClassFieldCache classFieldCache) throws IllegalArgumentException { // Parse the JSON Object parsedJSON; try { parsedJSON = JSONParser.parseJSON(json); } catch (final Parse...
java
public static <T> T deserializeObject(final Class<T> expectedType, final String json) throws IllegalArgumentException { final ClassFieldCache classFieldCache = new ClassFieldCache(/* resolveTypes = */ true, /* onlySerializePublicFields = */ false); return deserializeObject(ex...
java
private static void findLayerOrder(final Object /* ModuleLayer */ layer, final Set<Object> /* Set<ModuleLayer> */ layerVisited, final Set<Object> /* Set<ModuleLayer> */ parentLayers, final Deque<Object> /* Deque<ModuleLayer> */ layerOrderOut) { if (layerVisited.add(layer)) { ...
java
private static List<ModuleRef> findModuleRefs(final LinkedHashSet<Object> layers, final ScanSpec scanSpec, final LogNode log) { if (layers.isEmpty()) { return Collections.emptyList(); } // Traverse the layer DAG to find the layer resolution order final Deque<Obje...
java
static ClassRefTypeSignature parse(final Parser parser, final String definingClassName) throws ParseException { if (parser.peek() == 'L') { parser.next(); if (!TypeUtils.getIdentifierToken(parser, /* separator = */ '/', /* separatorReplace = */ '.')) { throw new ParseExce...
java
private static boolean isParentFirstStrategy(final ClassLoader classRealmInstance) { final Object strategy = ReflectionUtils.getFieldVal(classRealmInstance, "strategy", false); if (strategy != null) { final String strategyClassName = strategy.getClass().getName(); if (strategyCla...
java
public static boolean startsWith(Msg msg, String data, boolean includeLength) { final int length = data.length(); assert (length < 256); int start = includeLength ? 1 : 0; if (msg.size() < length + start) { return false; } boolean comparison = includeLeng...
java
@Override public void write(final T value, boolean incomplete) { // Place the value to the queue, add new terminator element. queue.push(value); // Move the "flush up to here" pointer. if (!incomplete) { f = queue.backPos(); } }
java
@Override public T unwrite() { if (f == queue.backPos()) { return null; } queue.unpush(); return queue.back(); }
java
@Override public boolean flush() { // If there are no un-flushed items, do nothing. if (w == f) { return true; } // Try to set 'c' to 'f'. if (!c.compareAndSet(w, f)) { // Compare-and-swap was unsuccessful because 'c' is NULL. // T...
java
@Override public boolean checkRead() { // Was the value prefetched already? If so, return. int h = queue.frontPos(); if (h != r) { return true; } // There's no prefetched value, so let us prefetch more values. // Prefetching is to simply retrieve t...
java
@Override public ByteBuffer getBuffer() { // If we are expected to read large message, we'll opt for zero- // copy, i.e. we'll ask caller to fill the data directly to the // message. Note that subsequent read(s) are non-blocking, thus // each single read reads at most SO_RCVB...
java
@Override public Step.Result decode(ByteBuffer data, int size, ValueReference<Integer> processed) { processed.set(0); // In case of zero-copy simply adjust the pointers, no copying // is required. Also, run the state machine in case all the data // were processed. if ...
java
public boolean rm(Msg msg, int start, int size) { // TODO: Shouldn't an error be reported if the key does not exist? if (size == 0) { if (refcnt == 0) { return false; } refcnt--; return refcnt == 0; } assert (msg != n...
java
public boolean check(ByteBuffer data) { assert (data != null); int size = data.limit(); // This function is on critical path. It deliberately doesn't use // recursion to get a bit better performance. Trie current = this; int start = 0; while (true) { ...
java
public ZMsg duplicate() { if (frames.isEmpty()) { return null; } else { ZMsg msg = new ZMsg(); for (ZFrame f : frames) { msg.add(f.duplicate()); } return msg; } }
java
public ZMsg wrap(ZFrame frame) { if (frame != null) { push(new ZFrame("")); push(frame); } return this; }
java
public static ZMsg recvMsg(Socket socket, boolean wait) { return recvMsg(socket, wait ? 0 : ZMQ.DONTWAIT); }
java
public static ZMsg recvMsg(Socket socket, int flag) { if (socket == null) { throw new IllegalArgumentException("socket is null"); } ZMsg msg = new ZMsg(); while (true) { ZFrame f = ZFrame.recvFrame(socket, flag); if (f == null) { ...
java
public static boolean save(ZMsg msg, DataOutputStream file) { if (msg == null) { return false; } try { // Write number of frames file.writeInt(msg.size()); if (msg.size() > 0) { for (ZFrame f : msg) { // Wri...
java
public static ZMsg newStringMsg(String... strings) { ZMsg msg = new ZMsg(); for (String data : strings) { msg.addString(data); } return msg; }
java
public ZMsg dump(Appendable out) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.printf("--------------------------------------\n"); for (ZFrame frame : frames) { pw.printf("[%03d] %s\n", frame.size(), fra...
java
@Deprecated protected ZAgent agent(Socket phone, String secret) { return ZAgent.Creator.create(phone, secret); }
java
public Ticket add(long delay, TimerHandler handler, Object... args) { if (handler == null) { return null; } Utils.checkArgument(delay > 0, "Delay of a ticket has to be strictly greater than 0"); final Ticket ticket = new Ticket(this, now(), delay, handler, args); ...
java
public long timeout() { if (tickets.isEmpty()) { return -1; } sortIfNeeded(); // Tickets are sorted, so check first ticket Ticket first = tickets.get(0); return first.start - now() + first.delay; }
java
public int execute() { int executed = 0; final long now = now(); sortIfNeeded(); Set<Ticket> cancelled = new HashSet<>(); for (Ticket ticket : this.tickets) { if (now - ticket.start < ticket.delay) { // tickets are ordered, not meeting the conditio...
java
private NetProtocol checkProtocol(String protocol) { // First check out whether the protcol is something we are aware of. NetProtocol proto = NetProtocol.getProtocol(protocol); if (proto == null || !proto.valid) { errno.set(ZError.EPROTONOSUPPORT); return proto; ...
java
private void addEndpoint(String addr, Own endpoint, Pipe pipe) { // Activate the session. Make it a child of this socket. launchChild(endpoint); endpoints.insert(addr, new EndpointPipe(endpoint, pipe)); }
java
final void startReaping(Poller poller) { // Plug the socket to the reaper thread. this.poller = poller; SelectableChannel fd = mailbox.getFd(); handle = this.poller.addHandle(fd, this); this.poller.setPollIn(handle); // Initialize the termination and check whether ...
java
private boolean processCommands(int timeout, boolean throttle) { Command cmd; if (timeout != 0) { // If we are asked to wait, simply ask mailbox to wait. cmd = mailbox.recv(timeout); } else { // If we are asked not to wait, check whether we haven...
java
private void extractFlags(Msg msg) { // Test whether IDENTITY flag is valid for this socket type. if (msg.isIdentity()) { assert (options.recvIdentity); } // Remove MORE flag. rcvmore = msg.hasMore(); }
java
@Override public String getAddress() { if (((InetSocketAddress) address.address()).getPort() == 0) { return address(address); } return address.toString(); }
java
public boolean pathExists(String path) { String[] pathElements = path.split("/"); ZConfig current = this; for (String pathElem : pathElements) { if (pathElem.isEmpty()) { continue; } current = current.children.get(pathElem); if ...
java
public String[] keypairZ85() { String[] pair = new String[2]; byte[] publicKey = new byte[Size.PUBLICKEY.bytes()]; byte[] secretKey = new byte[Size.SECRETKEY.bytes()]; int rc = curve25519xsalsa20poly1305.crypto_box_keypair(publicKey, secretKey); assert (rc == 0); p...
java
public byte[][] keypair() { byte[][] pair = new byte[2][]; byte[] publicKey = new byte[Size.PUBLICKEY.bytes()]; byte[] secretKey = new byte[Size.SECRETKEY.bytes()]; int rc = curve25519xsalsa20poly1305.crypto_box_keypair(publicKey, secretKey); assert (rc == 0); pair...
java
private void error(ErrorReason error) { if (options.rawSocket) { // For raw sockets, send a final 0-length message to the application // so that it knows the peer has been disconnected. Msg terminator = new Msg(); processMsg.apply(terminator); } ...
java
private int write(ByteBuffer outbuf) { int nbytes; try { nbytes = fd.write(outbuf); if (nbytes == 0) { errno.set(ZError.EAGAIN); } } catch (IOException e) { errno.set(ZError.ENOTCONN); nbytes = -1; } ...
java
private int read(ByteBuffer buf) { int nbytes; try { nbytes = fd.read(buf); if (nbytes == -1) { errno.set(ZError.ENOTCONN); } else if (nbytes == 0) { if (!fd.isBlocking()) { // If not a single byte c...
java
public boolean sendAndDestroy(Socket socket, int flags) { boolean ret = send(socket, flags); if (ret) { destroy(); } return ret; }
java
public boolean hasSameData(ZFrame other) { if (other == null) { return false; } if (size() == other.size()) { return Arrays.equals(data, other.data); } return false; }
java
private byte[] recv(Socket socket, int flags) { Utils.checkArgument(socket != null, "socket parameter must not be null"); data = socket.recv(flags); more = socket.hasReceiveMore(); return data; }
java
public static ZFrame recvFrame(Socket socket, int flags) { ZFrame f = new ZFrame(); byte[] data = f.recv(socket, flags); if (data == null) { return null; } return f; }
java
public void terminate() { slotSync.lock(); try { // Connect up any pending inproc connections, otherwise we will hang for (Entry<PendingConnection, String> pending : pendingConnections.entries()) { SocketBase s = createSocket(ZMQ.ZMQ_PAIR); // ...
java
public Selector createSelector() { selectorSync.lock(); try { Selector selector = Selector.open(); assert (selector != null); selectors.add(selector); return selector; } catch (IOException e) { throw new ZError.IOException(e...
java
boolean registerEndpoint(String addr, Endpoint endpoint) { endpointsSync.lock(); Endpoint inserted = null; try { inserted = endpoints.put(addr, endpoint); } finally { endpointsSync.unlock(); } if (inserted != null) { return...
java
public void attachPipe(Pipe pipe) { assert (!isTerminating()); assert (this.pipe == null); assert (pipe != null); this.pipe = pipe; this.pipe.setEventSink(this); }
java
private void cleanPipes() { assert (pipe != null); // Get rid of half-processed messages in the out pipe. Flush any // unflushed messages upstream. pipe.rollback(); pipe.flush(); // Remove any half-read message from the in pipe. while (incompleteIn) { ...
java
public void destroy() { for (Socket socket : sockets) { destroySocket(socket); } sockets.clear(); for (Selector selector : selectors) { context.close(selector); } selectors.clear(); // Only terminate context if we are on the main thre...
java
public Socket createSocket(SocketType type) { // Create and register socket Socket socket = context.socket(type); socket.setRcvHWM(this.rcvhwm); socket.setSndHWM(this.sndhwm); sockets.add(socket); return socket; }
java
public void destroySocket(Socket s) { if (s == null) { return; } s.setLinger(linger); s.close(); this.sockets.remove(s); }
java
Selector selector() { Selector selector = context.selector(); selectors.add(selector); return selector; }
java
@Deprecated @Draft public void closeSelector(Selector selector) { if (selectors.remove(selector)) { context.close(selector); } }
java