code
stringlengths
73
34.1k
label
stringclasses
1 value
private void completeMultipart(String bucketName, String objectName, String uploadId, Part[] parts) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put(UPLOAD_ID, uploadId); CompleteMultipartUpload completeManifest = new CompleteMultipartUpload(parts); HttpResponse response = executePost(bucketName, objectName, null, queryParamMap, completeManifest); // Fixing issue https://github.com/minio/minio-java/issues/391 String bodyContent = ""; Scanner scanner = new Scanner(response.body().charStream()); try { // read entire body stream to string. scanner.useDelimiter("\\A"); if (scanner.hasNext()) { bodyContent = scanner.next(); } } finally { response.body().close(); scanner.close(); } bodyContent = bodyContent.trim(); if (!bodyContent.isEmpty()) { ErrorResponse errorResponse = new ErrorResponse(new StringReader(bodyContent)); if (errorResponse.code() != null) { throw new ErrorResponseException(errorResponse, response.response()); } } }
java
private void abortMultipartUpload(String bucketName, String objectName, String uploadId) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put(UPLOAD_ID, uploadId); executeDelete(bucketName, objectName, queryParamMap); }
java
public void removeIncompleteUpload(String bucketName, String objectName) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { for (Result<Upload> r : listIncompleteUploads(bucketName, objectName, true, false)) { Upload upload = r.get(); if (objectName.equals(upload.objectName())) { abortMultipartUpload(bucketName, objectName, upload.uploadId()); return; } } }
java
public void listenBucketNotification(String bucketName, String prefix, String suffix, String[] events, BucketEventListener eventCallback) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { Multimap<String,String> queryParamMap = HashMultimap.create(); queryParamMap.put("prefix", prefix); queryParamMap.put("suffix", suffix); for (String event: events) { queryParamMap.put("events", event); } String bodyContent = ""; Scanner scanner = null; HttpResponse response = null; ObjectMapper mapper = new ObjectMapper(); try { response = executeReq(Method.GET, getRegion(bucketName), bucketName, "", null, queryParamMap, null, 0); scanner = new Scanner(response.body().charStream()); scanner.useDelimiter("\n"); while (scanner.hasNext()) { bodyContent = scanner.next().trim(); if (bodyContent.equals("")) { continue; } NotificationInfo ni = mapper.readValue(bodyContent, NotificationInfo.class); eventCallback.updateEvent(ni); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw e; } finally { if (response != null) { response.body().close(); } if (scanner != null) { scanner.close(); } } }
java
private static int[] calculateMultipartSize(long size) throws InvalidArgumentException { if (size > MAX_OBJECT_SIZE) { throw new InvalidArgumentException("size " + size + " is greater than allowed size 5TiB"); } double partSize = Math.ceil((double) size / MAX_MULTIPART_COUNT); partSize = Math.ceil(partSize / MIN_MULTIPART_SIZE) * MIN_MULTIPART_SIZE; double partCount = Math.ceil(size / partSize); double lastPartSize = partSize - (partSize * partCount - size); if (lastPartSize == 0.0) { lastPartSize = partSize; } return new int[] { (int) partSize, (int) partCount, (int) lastPartSize }; }
java
private int getAvailableSize(Object inputStream, int expectedReadSize) throws IOException, InternalException { RandomAccessFile file = null; BufferedInputStream stream = null; if (inputStream instanceof RandomAccessFile) { file = (RandomAccessFile) inputStream; } else if (inputStream instanceof BufferedInputStream) { stream = (BufferedInputStream) inputStream; } else { throw new InternalException("Unknown input stream. This should not happen. " + "Please report to https://github.com/minio/minio-java/issues/"); } // hold current position of file/stream to reset back to this position. long pos = 0; if (file != null) { pos = file.getFilePointer(); } else { stream.mark(expectedReadSize); } // 16KiB buffer for optimization byte[] buf = new byte[16384]; int bytesToRead = buf.length; int bytesRead = 0; int totalBytesRead = 0; while (totalBytesRead < expectedReadSize) { if ((expectedReadSize - totalBytesRead) < bytesToRead) { bytesToRead = expectedReadSize - totalBytesRead; } if (file != null) { bytesRead = file.read(buf, 0, bytesToRead); } else { bytesRead = stream.read(buf, 0, bytesToRead); } if (bytesRead < 0) { // reached EOF break; } totalBytesRead += bytesRead; } // reset back to saved position. if (file != null) { file.seek(pos); } else { stream.reset(); } return totalBytesRead; }
java
public void traceOn(OutputStream traceStream) { if (traceStream == null) { throw new NullPointerException(); } else { this.traceStream = new PrintWriter(new OutputStreamWriter(traceStream, StandardCharsets.UTF_8), true); } }
java
public static void set(Headers headers, Object destination) { Field[] publicFields; Field[] privateFields; Field[] fields; Class<?> cls = destination.getClass(); publicFields = cls.getFields(); privateFields = cls.getDeclaredFields(); fields = new Field[publicFields.length + privateFields.length]; System.arraycopy(publicFields, 0, fields, 0, publicFields.length); System.arraycopy(privateFields, 0, fields, publicFields.length, privateFields.length); for (Field field : fields) { Annotation annotation = field.getAnnotation(Header.class); if (annotation == null) { continue; } Header httpHeader = (Header) annotation; String value = httpHeader.value(); String setter = httpHeader.setter(); if (setter.isEmpty()) { // assume setter name as 'setFieldName' String name = field.getName(); setter = "set" + name.substring(0, 1).toUpperCase(Locale.US) + name.substring(1); } try { Method setterMethod = cls.getMethod(setter, new Class[]{String.class}); String valueString = headers.get(value); if (valueString != null) { setterMethod.invoke(destination, valueString); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) { LOGGER.log(Level.SEVERE, "exception occured: ", e); LOGGER.log(Level.INFO, "setter: " + setter); LOGGER.log(Level.INFO, "annotation: " + value); LOGGER.log(Level.INFO, "value: " + headers.get(value)); } } }
java
public static String encode(String str) { if (str == null) { return ""; } return ESCAPER.escape(str) .replaceAll("\\!", "%21") .replaceAll("\\$", "%24") .replaceAll("\\&", "%26") .replaceAll("\\'", "%27") .replaceAll("\\(", "%28") .replaceAll("\\)", "%29") .replaceAll("\\*", "%2A") .replaceAll("\\+", "%2B") .replaceAll("\\,", "%2C") .replaceAll("\\/", "%2F") .replaceAll("\\:", "%3A") .replaceAll("\\;", "%3B") .replaceAll("\\=", "%3D") .replaceAll("\\@", "%40") .replaceAll("\\[", "%5B") .replaceAll("\\]", "%5D"); }
java
public static String getChunkSignature(String chunkSha256, DateTime date, String region, String secretKey, String prevSignature) throws NoSuchAlgorithmException, InvalidKeyException { Signer signer = new Signer(null, chunkSha256, date, region, null, secretKey, prevSignature); signer.setScope(); signer.setChunkStringToSign(); signer.setSigningKey(); signer.setSignature(); return signer.signature; }
java
public static String getChunkSeedSignature(Request request, String region, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { String contentSha256 = request.header("x-amz-content-sha256"); DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date")); Signer signer = new Signer(request, contentSha256, date, region, null, secretKey, null); signer.setScope(); signer.setCanonicalRequest(); signer.setStringToSign(); signer.setSigningKey(); signer.setSignature(); return signer.signature; }
java
public static Request signV4(Request request, String region, String accessKey, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { String contentSha256 = request.header("x-amz-content-sha256"); DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date")); Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey, null); signer.setScope(); signer.setCanonicalRequest(); signer.setStringToSign(); signer.setSigningKey(); signer.setSignature(); signer.setAuthorization(); return request.newBuilder().header("Authorization", signer.authorization).build(); }
java
public static HttpUrl presignV4(Request request, String region, String accessKey, String secretKey, int expires) throws NoSuchAlgorithmException, InvalidKeyException { String contentSha256 = "UNSIGNED-PAYLOAD"; DateTime date = DateFormat.AMZ_DATE_FORMAT.parseDateTime(request.header("x-amz-date")); Signer signer = new Signer(request, contentSha256, date, region, accessKey, secretKey, null); signer.setScope(); signer.setPresignCanonicalRequest(expires); signer.setStringToSign(); signer.setSigningKey(); signer.setSignature(); return signer.url.newBuilder() .addEncodedQueryParameter(S3Escaper.encode("X-Amz-Signature"), S3Escaper.encode(signer.signature)) .build(); }
java
public static String credential(String accessKey, DateTime date, String region) { return accessKey + "/" + date.toString(DateFormat.SIGNER_DATE_FORMAT) + "/" + region + "/s3/aws4_request"; }
java
public static String postPresignV4(String stringToSign, String secretKey, DateTime date, String region) throws NoSuchAlgorithmException, InvalidKeyException { Signer signer = new Signer(null, null, date, region, null, secretKey, null); signer.stringToSign = stringToSign; signer.setSigningKey(); signer.setSignature(); return signer.signature; }
java
public static byte[] sumHmac(byte[] key, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); mac.update(data); return mac.doFinal(); }
java
public void setContentType(String contentType) throws InvalidArgumentException { if (Strings.isNullOrEmpty(contentType)) { throw new InvalidArgumentException("empty content type"); } this.contentType = contentType; }
java
public void setContentEncoding(String contentEncoding) throws InvalidArgumentException { if (Strings.isNullOrEmpty(contentEncoding)) { throw new InvalidArgumentException("empty content encoding"); } this.contentEncoding = contentEncoding; }
java
public void setContentRange(long startRange, long endRange) throws InvalidArgumentException { if (startRange <= 0 || endRange <= 0) { throw new InvalidArgumentException("negative start/end range"); } if (startRange > endRange) { throw new InvalidArgumentException("start range is higher than end range"); } this.contentRangeStart = startRange; this.contentRangeEnd = endRange; }
java
public Map<String,String> formData(String accessKey, String secretKey, String region) throws NoSuchAlgorithmException, InvalidKeyException, InvalidArgumentException { if (Strings.isNullOrEmpty(region)) { throw new InvalidArgumentException("empty region"); } return makeFormData(accessKey, secretKey, region); }
java
public void setModified(DateTime date) throws InvalidArgumentException { if (date == null) { throw new InvalidArgumentException("Date cannot be empty"); } copyConditions.put("x-amz-copy-source-if-modified-since", date.toString(DateFormat.HTTP_HEADER_DATE_FORMAT)); }
java
public void setMatchETag(String etag) throws InvalidArgumentException { if (etag == null) { throw new InvalidArgumentException("ETag cannot be empty"); } copyConditions.put("x-amz-copy-source-if-match", etag); }
java
public void setMatchETagNone(String etag) throws InvalidArgumentException { if (etag == null) { throw new InvalidArgumentException("ETag cannot be empty"); } copyConditions.put("x-amz-copy-source-if-none-match", etag); }
java
public void parseXml(Reader reader) throws IOException, XmlPullParserException { this.xmlPullParser.setInput(reader); Xml.parseElement(this.xmlPullParser, this, this.defaultNamespaceDictionary, null); }
java
protected void parseXml(Reader reader, XmlNamespaceDictionary namespaceDictionary) throws IOException, XmlPullParserException { this.xmlPullParser.setInput(reader); Xml.parseElement(this.xmlPullParser, this, namespaceDictionary, null); }
java
public int read() throws IOException { if (this.bytesRead == this.length) { // All chunks and final additional chunk are read. // This means we have reached EOF. return -1; } try { // Read a chunk from given input stream when // it is first chunk or all bytes in chunk body is read if (this.streamBytesRead == 0 || this.chunkPos == this.chunkBody.length) { // Check if there are data available to read from given input stream. if (this.streamBytesRead != this.streamSize) { // Send all data chunks. int chunkSize = CHUNK_SIZE; if (this.streamBytesRead + chunkSize > this.streamSize) { chunkSize = this.streamSize - this.streamBytesRead; } if (readChunk(chunkSize) < 0) { return -1; } this.streamBytesRead += chunkSize; } else { // Send final additional chunk to complete chunk upload. byte[] chunk = new byte[0]; createChunkBody(chunk); } } this.bytesRead++; // Value must be between 0 to 255. int value = this.chunkBody[this.chunkPos] & 0xFF; this.chunkPos++; return value; } catch (NoSuchAlgorithmException | InvalidKeyException | InsufficientDataException | InternalException e) { throw new IOException(e.getCause()); } }
java
protected String adjustHost(final String host) { if (host.startsWith(HTTP_PROTOCOL)) { return host.replace(HTTP_PROTOCOL, EMPTY_STRING); } else if (host.startsWith(HTTPS_PROTOCOL)) { return host.replace(HTTPS_PROTOCOL, EMPTY_STRING); } return host; }
java
public static void checkNotNullOrEmpty(String string, String message) { if (string == null || string.isEmpty()) { throw new IllegalArgumentException(message); } }
java
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) public static Observable<Connectivity> observeNetworkConnectivity(final Context context) { final NetworkObservingStrategy strategy; if (Preconditions.isAtLeastAndroidMarshmallow()) { strategy = new MarshmallowNetworkObservingStrategy(); } else if (Preconditions.isAtLeastAndroidLollipop()) { strategy = new LollipopNetworkObservingStrategy(); } else { strategy = new PreLollipopNetworkObservingStrategy(); } return observeNetworkConnectivity(context, strategy); }
java
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) public static Observable<Connectivity> observeNetworkConnectivity(final Context context, final NetworkObservingStrategy strategy) { Preconditions.checkNotNull(context, "context == null"); Preconditions.checkNotNull(strategy, "strategy == null"); return strategy.observeNetworkConnectivity(context); }
java
@RequiresPermission(Manifest.permission.INTERNET) protected static Observable<Boolean> observeInternetConnectivity( final InternetObservingStrategy strategy, final int initialIntervalInMs, final int intervalInMs, final String host, final int port, final int timeoutInMs, final int httpResponse, final ErrorHandler errorHandler) { checkStrategyIsNotNull(strategy); return strategy.observeInternetConnectivity(initialIntervalInMs, intervalInMs, host, port, timeoutInMs, httpResponse, errorHandler); }
java
protected static int[] appendUnknownNetworkTypeToTypes(int[] types) { int i = 0; final int[] extendedTypes = new int[types.length + 1]; for (int type : types) { extendedTypes[i] = type; i++; } extendedTypes[i] = Connectivity.UNKNOWN_TYPE; return extendedTypes; }
java
private int getAndParseHexChar() throws ParseException { final char hexChar = getc(); if (hexChar >= '0' && hexChar <= '9') { return hexChar - '0'; } else if (hexChar >= 'a' && hexChar <= 'f') { return hexChar - 'a' + 10; } else if (hexChar >= 'A' && hexChar <= 'F') { return hexChar - 'A' + 10; } else { throw new ParseException(this, "Invalid character in Unicode escape sequence: " + hexChar); } }
java
private Number parseNumber() throws ParseException { final int startIdx = getPosition(); if (peekMatches("Infinity")) { advance(8); return Double.POSITIVE_INFINITY; } else if (peekMatches("-Infinity")) { advance(9); return Double.NEGATIVE_INFINITY; } else if (peekMatches("NaN")) { advance(3); return Double.NaN; } if (peek() == '-') { next(); } final int integralStartIdx = getPosition(); for (; hasMore(); next()) { final char c = peek(); if (c < '0' || c > '9') { break; } } final int integralEndIdx = getPosition(); final int numIntegralDigits = integralEndIdx - integralStartIdx; if (numIntegralDigits == 0) { throw new ParseException(this, "Expected a number"); } final boolean hasFractionalPart = peek() == '.'; if (hasFractionalPart) { next(); for (; hasMore(); next()) { final char c = peek(); if (c < '0' || c > '9') { break; } } if (getPosition() - (integralEndIdx + 1) == 0) { throw new ParseException(this, "Expected digits after decimal point"); } } final boolean hasExponentPart = peek() == '.'; if (hasExponentPart) { next(); final char sign = peek(); if (sign == '-' || sign == '+') { next(); } final int exponentStart = getPosition(); for (; hasMore(); next()) { final char c = peek(); if (c < '0' || c > '9') { break; } } if (getPosition() - exponentStart == 0) { throw new ParseException(this, "Expected an exponent"); } } final int endIdx = getPosition(); final String numberStr = getSubstring(startIdx, endIdx); if (hasFractionalPart || hasExponentPart) { return Double.valueOf(numberStr); } else if (numIntegralDigits < 9) { return Integer.valueOf(numberStr); } else if (numIntegralDigits == 9) { // For 9-digit numbers, could be int or long final long longVal = Long.parseLong(numberStr); if (longVal >= Integer.MIN_VALUE && longVal <= Integer.MAX_VALUE) { return (int) longVal; } else { return longVal; } } else { return Long.valueOf(numberStr); } }
java
private JSONObject parseJSONObject() throws ParseException { expect('{'); skipWhitespace(); if (peek() == '}') { // Empty object next(); return new JSONObject(Collections.<Entry<String, Object>> emptyList()); } final List<Entry<String, Object>> kvPairs = new ArrayList<>(); final JSONObject jsonObject = new JSONObject(kvPairs); boolean first = true; while (peek() != '}') { if (first) { first = false; } else { expect(','); } final CharSequence key = parseString(); if (key == null) { throw new ParseException(this, "Object keys must be strings"); } if (peek() != ':') { return null; } expect(':'); final Object value = parseJSON(); // Check for special object id key if (key.equals(JSONUtils.ID_KEY)) { if (value == null) { throw new ParseException(this, "Got null value for \"" + JSONUtils.ID_KEY + "\" key"); } jsonObject.objectId = (CharSequence) value; } else { kvPairs.add(new SimpleEntry<>(key.toString(), value)); } } expect('}'); return jsonObject; }
java
Object instantiateOrGet(final ClassInfo annotationClassInfo, final String paramName) { final boolean instantiate = annotationClassInfo != null; if (enumValue != null) { return instantiate ? enumValue.loadClassAndReturnEnumValue() : enumValue; } else if (classRef != null) { return instantiate ? classRef.loadClass() : classRef; } else if (annotationInfo != null) { return instantiate ? annotationInfo.loadClassAndInstantiate() : annotationInfo; } else if (stringValue != null) { return stringValue; } else if (integerValue != null) { return integerValue; } else if (longValue != null) { return longValue; } else if (shortValue != null) { return shortValue; } else if (booleanValue != null) { return booleanValue; } else if (characterValue != null) { return characterValue; } else if (floatValue != null) { return floatValue; } else if (doubleValue != null) { return doubleValue; } else if (byteValue != null) { return byteValue; } else if (stringArrayValue != null) { return stringArrayValue; } else if (intArrayValue != null) { return intArrayValue; } else if (longArrayValue != null) { return longArrayValue; } else if (shortArrayValue != null) { return shortArrayValue; } else if (booleanArrayValue != null) { return booleanArrayValue; } else if (charArrayValue != null) { return charArrayValue; } else if (floatArrayValue != null) { return floatArrayValue; } else if (doubleArrayValue != null) { return doubleArrayValue; } else if (byteArrayValue != null) { return byteArrayValue; } else if (objectArrayValue != null) { // Get the element type of the array final Class<?> eltClass = instantiate ? (Class<?>) getArrayValueClassOrName(annotationClassInfo, paramName, /* getClass = */ true) : null; // Allocate array as either a generic Object[] array, if the element type could not be determined, // or as an array of specific element type, if the element type was determined. final Object annotationValueObjectArray = eltClass == null ? new Object[objectArrayValue.length] : Array.newInstance(eltClass, objectArrayValue.length); // Fill the array instance. for (int i = 0; i < objectArrayValue.length; i++) { if (objectArrayValue[i] != null) { // Get the element value (may also cause the element to be instantiated) final Object eltValue = objectArrayValue[i].instantiateOrGet(annotationClassInfo, paramName); // Store the possibly-instantiated value in the array Array.set(annotationValueObjectArray, i, eltValue); } } return annotationValueObjectArray; } else { return null; } }
java
private Object getArrayValueClassOrName(final ClassInfo annotationClassInfo, final String paramName, final boolean getClass) { // Find the method in the annotation class with the same name as the annotation parameter. final MethodInfoList annotationMethodList = annotationClassInfo.methodInfo == null ? null : annotationClassInfo.methodInfo.get(paramName); if (annotationMethodList != null && annotationMethodList.size() > 1) { // There should only be one method with a given name in an annotation throw new IllegalArgumentException("Duplicated annotation parameter method " + paramName + "() in annotation class " + annotationClassInfo.getName()); } else if (annotationMethodList != null && annotationMethodList.size() == 1) { // Get the result type of the method with the same name as the annotation parameter final TypeSignature annotationMethodResultTypeSig = annotationMethodList.get(0) .getTypeSignatureOrTypeDescriptor().getResultType(); // The result type has to be an array type if (!(annotationMethodResultTypeSig instanceof ArrayTypeSignature)) { throw new IllegalArgumentException("Annotation parameter " + paramName + " in annotation class " + annotationClassInfo.getName() + " holds an array, but does not have an array type signature"); } final ArrayTypeSignature arrayTypeSig = (ArrayTypeSignature) annotationMethodResultTypeSig; if (arrayTypeSig.getNumDimensions() != 1) { throw new IllegalArgumentException("Annotations only support 1-dimensional arrays"); } final TypeSignature elementTypeSig = arrayTypeSig.getElementTypeSignature(); if (elementTypeSig instanceof ClassRefTypeSignature) { // Look up the name of the element type, for non-primitive arrays final ClassRefTypeSignature classRefTypeSignature = (ClassRefTypeSignature) elementTypeSig; return getClass ? classRefTypeSignature.loadClass() : classRefTypeSignature.getFullyQualifiedClassName(); } else if (elementTypeSig instanceof BaseTypeSignature) { // Look up the name of the primitive class, for primitive arrays final BaseTypeSignature baseTypeSignature = (BaseTypeSignature) elementTypeSig; return getClass ? baseTypeSignature.getType() : baseTypeSignature.getTypeStr(); } } else { // Could not find a method with this name -- this is an external class. // Find first non-null object in array, and use its type as the type of the array. for (final ObjectTypedValueWrapper elt : objectArrayValue) { if (elt != null) { return elt.integerValue != null ? (getClass ? Integer.class : "int") : elt.longValue != null ? (getClass ? Long.class : "long") : elt.shortValue != null ? (getClass ? Short.class : "short") : elt.characterValue != null ? (getClass ? Character.class : "char") : elt.byteValue != null ? (getClass ? Byte.class : "byte") : elt.booleanValue != null ? (getClass ? Boolean.class : "boolean") : elt.doubleValue != null ? (getClass ? Double.class : "double") : elt.floatValue != null ? (getClass ? Float.class : "float") : (getClass ? null : ""); } } } return getClass ? null : ""; }
java
public ClassGraph enableAllInfo() { enableClassInfo(); enableFieldInfo(); enableMethodInfo(); enableAnnotationInfo(); enableStaticFinalFieldConstantInitializerValues(); ignoreClassVisibility(); ignoreFieldVisibility(); ignoreMethodVisibility(); return this; }
java
public ClassGraph overrideClasspath(final Iterable<?> overrideClasspathElements) { final String overrideClasspath = JarUtils.pathElementsToPathStr(overrideClasspathElements); if (overrideClasspath.isEmpty()) { throw new IllegalArgumentException("Can't override classpath with an empty path"); } overrideClasspath(overrideClasspath); return this; }
java
public ClassGraph whitelistPackages(final String... packageNames) { enableClassInfo(); for (final String packageName : packageNames) { final String packageNameNormalized = WhiteBlackList.normalizePackageOrClassName(packageName); if (packageNameNormalized.startsWith("!") || packageNameNormalized.startsWith("-")) { throw new IllegalArgumentException( "This style of whitelisting/blacklisting is no longer supported: " + packageNameNormalized); } // Whitelist package scanSpec.packageWhiteBlackList.addToWhitelist(packageNameNormalized); final String path = WhiteBlackList.packageNameToPath(packageNameNormalized); scanSpec.pathWhiteBlackList.addToWhitelist(path + "/"); if (packageNameNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } if (!packageNameNormalized.contains("*")) { // Whitelist sub-packages if (packageNameNormalized.isEmpty()) { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(""); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(""); } else { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(packageNameNormalized + "."); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(path + "/"); } } } return this; }
java
public ClassGraph whitelistPaths(final String... paths) { for (final String path : paths) { final String pathNormalized = WhiteBlackList.normalizePath(path); // Whitelist path final String packageName = WhiteBlackList.pathToPackageName(pathNormalized); scanSpec.packageWhiteBlackList.addToWhitelist(packageName); scanSpec.pathWhiteBlackList.addToWhitelist(pathNormalized + "/"); if (pathNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } if (!pathNormalized.contains("*")) { // Whitelist sub-directories / nested paths if (pathNormalized.isEmpty()) { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(""); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(""); } else { scanSpec.packagePrefixWhiteBlackList.addToWhitelist(packageName + "."); scanSpec.pathPrefixWhiteBlackList.addToWhitelist(pathNormalized + "/"); } } } return this; }
java
public ClassGraph whitelistPackagesNonRecursive(final String... packageNames) { enableClassInfo(); for (final String packageName : packageNames) { final String packageNameNormalized = WhiteBlackList.normalizePackageOrClassName(packageName); if (packageNameNormalized.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + packageNameNormalized); } // Whitelist package, but not sub-packages scanSpec.packageWhiteBlackList.addToWhitelist(packageNameNormalized); scanSpec.pathWhiteBlackList .addToWhitelist(WhiteBlackList.packageNameToPath(packageNameNormalized) + "/"); if (packageNameNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } } return this; }
java
public ClassGraph whitelistPathsNonRecursive(final String... paths) { for (final String path : paths) { if (path.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + path); } final String pathNormalized = WhiteBlackList.normalizePath(path); // Whitelist path, but not sub-directories / nested paths scanSpec.packageWhiteBlackList.addToWhitelist(WhiteBlackList.pathToPackageName(pathNormalized)); scanSpec.pathWhiteBlackList.addToWhitelist(pathNormalized + "/"); if (pathNormalized.isEmpty()) { scanSpec.pathWhiteBlackList.addToWhitelist(""); } } return this; }
java
public ClassGraph blacklistPackages(final String... packageNames) { enableClassInfo(); for (final String packageName : packageNames) { final String packageNameNormalized = WhiteBlackList.normalizePackageOrClassName(packageName); if (packageNameNormalized.isEmpty()) { throw new IllegalArgumentException( "Blacklisting the root package (\"\") will cause nothing to be scanned"); } // Blacklisting always prevents further recursion, no need to blacklist sub-packages scanSpec.packageWhiteBlackList.addToBlacklist(packageNameNormalized); final String path = WhiteBlackList.packageNameToPath(packageNameNormalized); scanSpec.pathWhiteBlackList.addToBlacklist(path + "/"); if (!packageNameNormalized.contains("*")) { // Blacklist sub-packages (zipfile entries can occur in any order) scanSpec.packagePrefixWhiteBlackList.addToBlacklist(packageNameNormalized + "."); scanSpec.pathPrefixWhiteBlackList.addToBlacklist(path + "/"); } } return this; }
java
public ClassGraph whitelistClasses(final String... classNames) { enableClassInfo(); for (final String className : classNames) { if (className.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + className); } final String classNameNormalized = WhiteBlackList.normalizePackageOrClassName(className); // Whitelist the class itself scanSpec.classWhiteBlackList.addToWhitelist(classNameNormalized); scanSpec.classfilePathWhiteBlackList .addToWhitelist(WhiteBlackList.classNameToClassfilePath(classNameNormalized)); final String packageName = PackageInfo.getParentPackageName(classNameNormalized); // Record the package containing the class, so we can recurse to this point even if the package // is not itself whitelisted scanSpec.classPackageWhiteBlackList.addToWhitelist(packageName); scanSpec.classPackagePathWhiteBlackList .addToWhitelist(WhiteBlackList.packageNameToPath(packageName) + "/"); } return this; }
java
public ClassGraph blacklistClasses(final String... classNames) { enableClassInfo(); for (final String className : classNames) { if (className.contains("*")) { throw new IllegalArgumentException("Cannot use a glob wildcard here: " + className); } final String classNameNormalized = WhiteBlackList.normalizePackageOrClassName(className); scanSpec.classWhiteBlackList.addToBlacklist(classNameNormalized); scanSpec.classfilePathWhiteBlackList .addToBlacklist(WhiteBlackList.classNameToClassfilePath(classNameNormalized)); } return this; }
java
public ClassGraph whitelistJars(final String... jarLeafNames) { for (final String jarLeafName : jarLeafNames) { final String leafName = JarUtils.leafName(jarLeafName); if (!leafName.equals(jarLeafName)) { throw new IllegalArgumentException("Can only whitelist jars by leafname: " + jarLeafName); } scanSpec.jarWhiteBlackList.addToWhitelist(leafName); } return this; }
java
public ClassGraph blacklistJars(final String... jarLeafNames) { for (final String jarLeafName : jarLeafNames) { final String leafName = JarUtils.leafName(jarLeafName); if (!leafName.equals(jarLeafName)) { throw new IllegalArgumentException("Can only blacklist jars by leafname: " + jarLeafName); } scanSpec.jarWhiteBlackList.addToBlacklist(leafName); } return this; }
java
private void whitelistOrBlacklistLibOrExtJars(final boolean whitelist, final String... jarLeafNames) { if (jarLeafNames.length == 0) { // If no jar leafnames are given, whitelist or blacklist all lib or ext jars for (final String libOrExtJar : SystemJarFinder.getJreLibOrExtJars()) { whitelistOrBlacklistLibOrExtJars(whitelist, JarUtils.leafName(libOrExtJar)); } } else { for (final String jarLeafName : jarLeafNames) { final String leafName = JarUtils.leafName(jarLeafName); if (!leafName.equals(jarLeafName)) { throw new IllegalArgumentException("Can only " + (whitelist ? "whitelist" : "blacklist") + " jars by leafname: " + jarLeafName); } if (jarLeafName.contains("*")) { // Compare wildcarded pattern against all jars in lib and ext dirs final Pattern pattern = WhiteBlackList.globToPattern(jarLeafName); boolean found = false; for (final String libOrExtJarPath : SystemJarFinder.getJreLibOrExtJars()) { final String libOrExtJarLeafName = JarUtils.leafName(libOrExtJarPath); if (pattern.matcher(libOrExtJarLeafName).matches()) { // Check for "*" in filename to prevent infinite recursion (shouldn't happen) if (!libOrExtJarLeafName.contains("*")) { whitelistOrBlacklistLibOrExtJars(whitelist, libOrExtJarLeafName); } found = true; } } if (!found && topLevelLog != null) { topLevelLog.log("Could not find lib or ext jar matching wildcard: " + jarLeafName); } } else { // No wildcards, just whitelist or blacklist the named jar, if present boolean found = false; for (final String libOrExtJarPath : SystemJarFinder.getJreLibOrExtJars()) { final String libOrExtJarLeafName = JarUtils.leafName(libOrExtJarPath); if (jarLeafName.equals(libOrExtJarLeafName)) { if (whitelist) { scanSpec.libOrExtJarWhiteBlackList.addToWhitelist(jarLeafName); } else { scanSpec.libOrExtJarWhiteBlackList.addToBlacklist(jarLeafName); } if (topLevelLog != null) { topLevelLog.log((whitelist ? "Whitelisting" : "Blacklisting") + " lib or ext jar: " + libOrExtJarPath); } found = true; break; } } if (!found && topLevelLog != null) { topLevelLog.log("Could not find lib or ext jar: " + jarLeafName); } } } } }
java
public ClassGraph whitelistModules(final String... moduleNames) { for (final String moduleName : moduleNames) { scanSpec.moduleWhiteBlackList.addToWhitelist(WhiteBlackList.normalizePackageOrClassName(moduleName)); } return this; }
java
public ClassGraph blacklistModules(final String... moduleNames) { for (final String moduleName : moduleNames) { scanSpec.moduleWhiteBlackList.addToBlacklist(WhiteBlackList.normalizePackageOrClassName(moduleName)); } return this; }
java
public ClassGraph whitelistClasspathElementsContainingResourcePath(final String... resourcePaths) { for (final String resourcePath : resourcePaths) { final String resourcePathNormalized = WhiteBlackList.normalizePath(resourcePath); scanSpec.classpathElementResourcePathWhiteBlackList.addToWhitelist(resourcePathNormalized); } return this; }
java
public ClassGraph blacklistClasspathElementsContainingResourcePath(final String... resourcePaths) { for (final String resourcePath : resourcePaths) { final String resourcePathNormalized = WhiteBlackList.normalizePath(resourcePath); scanSpec.classpathElementResourcePathWhiteBlackList.addToBlacklist(resourcePathNormalized); } return this; }
java
public T acquire() throws E { final T instance; final T recycledInstance = unusedInstances.poll(); if (recycledInstance == null) { // Allocate a new instance -- may throw an exception of type E final T newInstance = newInstance(); if (newInstance == null) { throw new NullPointerException("Failed to allocate a new recyclable instance"); } instance = newInstance; } else { // Reuse an unused instance instance = recycledInstance; } usedInstances.add(instance); return instance; }
java
public List<URI> getClasspathURIs() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final List<URI> classpathElementOrderURIs = new ArrayList<>(); for (final ClasspathElement classpathElement : classpathOrder) { try { final URI uri = classpathElement.getURI(); if (uri != null) { classpathElementOrderURIs.add(uri); } } catch (final IllegalArgumentException e) { // Skip null location URIs } } return classpathElementOrderURIs; }
java
public ResourceList getAllResources() { if (allWhitelistedResourcesCached == null) { // Index Resource objects by path final ResourceList whitelistedResourcesList = new ResourceList(); for (final ClasspathElement classpathElt : classpathOrder) { if (classpathElt.whitelistedResources != null) { whitelistedResourcesList.addAll(classpathElt.whitelistedResources); } } // Set atomically for thread safety allWhitelistedResourcesCached = whitelistedResourcesList; } return allWhitelistedResourcesCached; }
java
public ResourceList getResourcesWithPath(final String resourcePath) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final ResourceList allWhitelistedResources = getAllResources(); if (allWhitelistedResources.isEmpty()) { return ResourceList.EMPTY_LIST; } else { final String path = FileUtils.sanitizeEntryPath(resourcePath, /* removeInitialSlash = */ true); final ResourceList resourceList = getAllResourcesAsMap().get(path); return (resourceList == null ? new ResourceList(1) : resourceList); } }
java
public ResourceList getResourcesWithLeafName(final String leafName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final ResourceList allWhitelistedResources = getAllResources(); if (allWhitelistedResources.isEmpty()) { return ResourceList.EMPTY_LIST; } else { final ResourceList filteredResources = new ResourceList(); for (final Resource classpathResource : allWhitelistedResources) { final String relativePath = classpathResource.getPath(); final int lastSlashIdx = relativePath.lastIndexOf('/'); if (relativePath.substring(lastSlashIdx + 1).equals(leafName)) { filteredResources.add(classpathResource); } } return filteredResources; } }
java
public ResourceList getResourcesWithExtension(final String extension) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final ResourceList allWhitelistedResources = getAllResources(); if (allWhitelistedResources.isEmpty()) { return ResourceList.EMPTY_LIST; } else { String bareExtension = extension; while (bareExtension.startsWith(".")) { bareExtension = bareExtension.substring(1); } final ResourceList filteredResources = new ResourceList(); for (final Resource classpathResource : allWhitelistedResources) { final String relativePath = classpathResource.getPath(); final int lastSlashIdx = relativePath.lastIndexOf('/'); final int lastDotIdx = relativePath.lastIndexOf('.'); if (lastDotIdx > lastSlashIdx && relativePath.substring(lastDotIdx + 1).equalsIgnoreCase(bareExtension)) { filteredResources.add(classpathResource); } } return filteredResources; } }
java
public ResourceList getResourcesMatchingPattern(final Pattern pattern) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } final ResourceList allWhitelistedResources = getAllResources(); if (allWhitelistedResources.isEmpty()) { return ResourceList.EMPTY_LIST; } else { final ResourceList filteredResources = new ResourceList(); for (final Resource classpathResource : allWhitelistedResources) { final String relativePath = classpathResource.getPath(); if (pattern.matcher(relativePath).matches()) { filteredResources.add(classpathResource); } } return filteredResources; } }
java
public ModuleInfoList getModuleInfo() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return new ModuleInfoList(moduleNameToModuleInfo.values()); }
java
public PackageInfoList getPackageInfo() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return new PackageInfoList(packageNameToPackageInfo.values()); }
java
public ClassInfoList getAllClasses() { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } return ClassInfo.getAllClasses(classNameToClassInfo.values(), scanSpec); }
java
public ClassInfoList getSubclasses(final String superclassName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } if (superclassName.equals("java.lang.Object")) { // Return all standard classes (interfaces don't extend Object) return getAllStandardClasses(); } else { final ClassInfo superclass = classNameToClassInfo.get(superclassName); return superclass == null ? ClassInfoList.EMPTY_LIST : superclass.getSubclasses(); } }
java
public ClassInfoList getSuperclasses(final String subclassName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } final ClassInfo subclass = classNameToClassInfo.get(subclassName); return subclass == null ? ClassInfoList.EMPTY_LIST : subclass.getSuperclasses(); }
java
public ClassInfoList getClassesWithMethodAnnotation(final String methodAnnotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableMethodInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo(), #enableMethodInfo(), " + "and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(methodAnnotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodAnnotation(); }
java
public ClassInfoList getClassesWithMethodParameterAnnotation(final String methodParameterAnnotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableMethodInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo(), #enableMethodInfo(), " + "and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(methodParameterAnnotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodParameterAnnotation(); }
java
public ClassInfoList getClassesWithFieldAnnotation(final String fieldAnnotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableFieldInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo(), #enableFieldInfo(), " + "and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(fieldAnnotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithFieldAnnotation(); }
java
public ClassInfoList getInterfaces(final String className) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(className); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getInterfaces(); }
java
public ClassInfoList getClassesWithAnnotation(final String annotationName) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) { throw new IllegalArgumentException( "Please call ClassGraph#enableClassInfo() and #enableAnnotationInfo() before #scan()"); } final ClassInfo classInfo = classNameToClassInfo.get(annotationName); return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithAnnotation(); }
java
public static ScanResult fromJSON(final String json) { final Matcher matcher = Pattern.compile("\\{[\\n\\r ]*\"format\"[ ]?:[ ]?\"([^\"]+)\"").matcher(json); if (!matcher.find()) { throw new IllegalArgumentException("JSON is not in correct format"); } if (!CURRENT_SERIALIZATION_FORMAT.equals(matcher.group(1))) { throw new IllegalArgumentException( "JSON was serialized in a different format from the format used by the current version of " + "ClassGraph -- please serialize and deserialize your ScanResult using " + "the same version of ClassGraph"); } // Deserialize the JSON final SerializationFormat deserialized = JSONDeserializer.deserializeObject(SerializationFormat.class, json); if (!deserialized.format.equals(CURRENT_SERIALIZATION_FORMAT)) { // Probably the deserialization failed before now anyway, if fields have changed, etc. throw new IllegalArgumentException("JSON was serialized by newer version of ClassGraph"); } // Perform a new "scan" with performScan set to false, which resolves all the ClasspathElement objects // and scans classpath element paths (needed for classloading), but does not scan the actual classfiles final ClassGraph classGraph = new ClassGraph(); classGraph.scanSpec = deserialized.scanSpec; classGraph.scanSpec.performScan = false; if (classGraph.scanSpec.overrideClasspath == null) { // Use the same classpath as before, if classpath was not overridden classGraph.overrideClasspath(deserialized.classpath); } final ScanResult scanResult = classGraph.scan(); scanResult.rawClasspathEltOrderStrs = deserialized.classpath; scanResult.scanSpec.performScan = true; // Set the fields related to ClassInfo in the new ScanResult, based on the deserialized JSON scanResult.scanSpec = deserialized.scanSpec; scanResult.classNameToClassInfo = new HashMap<>(); if (deserialized.classInfo != null) { for (final ClassInfo ci : deserialized.classInfo) { scanResult.classNameToClassInfo.put(ci.getName(), ci); ci.setScanResult(scanResult); } } scanResult.moduleNameToModuleInfo = new HashMap<>(); if (deserialized.moduleInfo != null) { for (final ModuleInfo mi : deserialized.moduleInfo) { scanResult.moduleNameToModuleInfo.put(mi.getName(), mi); } } scanResult.packageNameToPackageInfo = new HashMap<>(); if (deserialized.packageInfo != null) { for (final PackageInfo pi : deserialized.packageInfo) { scanResult.packageNameToPackageInfo.put(pi.getName(), pi); } } // Index Resource and ClassInfo objects scanResult.indexResourcesAndClassInfo(); scanResult.isObtainedFromDeserialization = true; return scanResult; }
java
public String toJSON(final int indentWidth) { if (closed.get()) { throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed"); } if (!scanSpec.enableClassInfo) { throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()"); } final List<ClassInfo> allClassInfo = new ArrayList<>(classNameToClassInfo.values()); CollectionUtils.sortIfNotEmpty(allClassInfo); final List<PackageInfo> allPackageInfo = new ArrayList<>(packageNameToPackageInfo.values()); CollectionUtils.sortIfNotEmpty(allPackageInfo); final List<ModuleInfo> allModuleInfo = new ArrayList<>(moduleNameToModuleInfo.values()); CollectionUtils.sortIfNotEmpty(allModuleInfo); return JSONSerializer.serializeObject(new SerializationFormat(CURRENT_SERIALIZATION_FORMAT, scanSpec, allClassInfo, allPackageInfo, allModuleInfo, rawClasspathEltOrderStrs), indentWidth, false); }
java
Type resolveTypeVariables(final Type type) { if (type instanceof Class<?>) { // Arrays and non-generic classes have no type variables return type; } else if (type instanceof ParameterizedType) { // Recursively resolve parameterized types final ParameterizedType parameterizedType = (ParameterizedType) type; final Type[] typeArgs = parameterizedType.getActualTypeArguments(); Type[] typeArgsResolved = null; for (int i = 0; i < typeArgs.length; i++) { // Recursively revolve each parameter of the type final Type typeArgResolved = resolveTypeVariables(typeArgs[i]); // Only compare typeArgs to typeArgResolved until the first difference is found if (typeArgsResolved == null) { if (!typeArgResolved.equals(typeArgs[i])) { // After the first difference is found, lazily allocate typeArgsResolved typeArgsResolved = new Type[typeArgs.length]; // Go back and copy all the previous args System.arraycopy(typeArgs, 0, typeArgsResolved, 0, i); // Insert the first different arg typeArgsResolved[i] = typeArgResolved; } } else { // After the first difference is found, keep copying the resolved args into the array typeArgsResolved[i] = typeArgResolved; } } if (typeArgsResolved == null) { // There were no type parameters to resolve return type; } else { // Return new ParameterizedType that wraps the resolved type args return new ParameterizedTypeImpl((Class<?>) parameterizedType.getRawType(), typeArgsResolved, parameterizedType.getOwnerType()); } } else if (type instanceof TypeVariable<?>) { // Look up concrete type for type variable final TypeVariable<?> typeVariable = (TypeVariable<?>) type; for (int i = 0; i < typeVariables.length; i++) { if (typeVariables[i].getName().equals(typeVariable.getName())) { return resolvedTypeArguments[i]; } } // Could not resolve type variable return type; } else if (type instanceof GenericArrayType) { // Count the array dimensions, and resolve the innermost type of the array int numArrayDims = 0; Type t = type; while (t instanceof GenericArrayType) { numArrayDims++; t = ((GenericArrayType) t).getGenericComponentType(); } final Type innermostType = t; final Type innermostTypeResolved = resolveTypeVariables(innermostType); if (!(innermostTypeResolved instanceof Class<?>)) { throw new IllegalArgumentException("Could not resolve generic array type " + type); } final Class<?> innermostTypeResolvedClass = (Class<?>) innermostTypeResolved; // Build an array to hold the size of each dimension, filled with zeroes final int[] dims = (int[]) Array.newInstance(int.class, numArrayDims); // Build a zero-sized array of the required number of dimensions, using the resolved innermost class final Object arrayInstance = Array.newInstance(innermostTypeResolvedClass, dims); // Get the class of this array instance -- this is the resolved array type return arrayInstance.getClass(); } else if (type instanceof WildcardType) { // TODO: Support WildcardType throw ClassGraphException.newClassGraphException("WildcardType not yet supported: " + type); } else { throw ClassGraphException.newClassGraphException("Got unexpected type: " + type); } }
java
private static void assignObjectIds(final Object jsonVal, final Map<ReferenceEqualityKey<Object>, JSONObject> objToJSONVal, final ClassFieldCache classFieldCache, final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId, final AtomicInteger objId, final boolean onlySerializePublicFields) { if (jsonVal instanceof JSONObject) { for (final Entry<String, Object> item : ((JSONObject) jsonVal).items) { assignObjectIds(item.getValue(), objToJSONVal, classFieldCache, jsonReferenceToId, objId, onlySerializePublicFields); } } else if (jsonVal instanceof JSONArray) { for (final Object item : ((JSONArray) jsonVal).items) { assignObjectIds(item, objToJSONVal, classFieldCache, jsonReferenceToId, objId, onlySerializePublicFields); } } else if (jsonVal instanceof JSONReference) { // Get the referenced (non-JSON) object final Object refdObj = ((JSONReference) jsonVal).idObject; if (refdObj == null) { // Should not happen throw ClassGraphException.newClassGraphException("Internal inconsistency"); } // Look up the JSON object corresponding to the referenced object final ReferenceEqualityKey<Object> refdObjKey = new ReferenceEqualityKey<>(refdObj); final JSONObject refdJsonVal = objToJSONVal.get(refdObjKey); if (refdJsonVal == null) { // Should not happen throw ClassGraphException.newClassGraphException("Internal inconsistency"); } // See if the JSON object has an @Id field // (for serialization, typeResolutions can be null) final Field annotatedField = classFieldCache.get(refdObj.getClass()).idField; CharSequence idStr = null; if (annotatedField != null) { // Get id value from field annotated with @Id try { final Object idObject = annotatedField.get(refdObj); if (idObject != null) { idStr = idObject.toString(); refdJsonVal.objectId = idStr; } } catch (IllegalArgumentException | IllegalAccessException e) { // Should not happen throw new IllegalArgumentException("Could not access @Id-annotated field " + annotatedField, e); } } if (idStr == null) { // No @Id field, or field value is null -- check if ref'd JSON Object already has an id if (refdJsonVal.objectId == null) { // Ref'd JSON object doesn't have an id yet -- generate unique integer id idStr = JSONUtils.ID_PREFIX + objId.getAndIncrement() + JSONUtils.ID_SUFFIX; refdJsonVal.objectId = idStr; } else { idStr = refdJsonVal.objectId; } } // Link both the JSON representation ob the object to the id jsonReferenceToId.put(new ReferenceEqualityKey<>((JSONReference) jsonVal), idStr); } // if (jsonVal == null) then do nothing }
java
static void jsonValToJSONString(final Object jsonVal, final Map<ReferenceEqualityKey<JSONReference>, CharSequence> jsonReferenceToId, final boolean includeNullValuedFields, final int depth, final int indentWidth, final StringBuilder buf) { if (jsonVal == null) { buf.append("null"); } else if (jsonVal instanceof JSONObject) { // Serialize JSONObject to string ((JSONObject) jsonVal).toJSONString(jsonReferenceToId, includeNullValuedFields, depth, indentWidth, buf); } else if (jsonVal instanceof JSONArray) { // Serialize JSONArray to string ((JSONArray) jsonVal).toJSONString(jsonReferenceToId, includeNullValuedFields, depth, indentWidth, buf); } else if (jsonVal instanceof JSONReference) { // Serialize JSONReference to string final Object referencedObjectId = jsonReferenceToId .get(new ReferenceEqualityKey<>((JSONReference) jsonVal)); jsonValToJSONString(referencedObjectId, jsonReferenceToId, includeNullValuedFields, depth, indentWidth, buf); } else if (jsonVal instanceof CharSequence || jsonVal instanceof Character || jsonVal.getClass().isEnum()) { // Serialize String, Character or enum val to quoted/escaped string buf.append('"'); JSONUtils.escapeJSONString(jsonVal.toString(), buf); buf.append('"'); } else { // Serialize a numeric or Boolean type (Integer, Long, Short, Float, Double, Boolean, Byte) to string // (doesn't need quoting or escaping) buf.append(jsonVal.toString()); } }
java
private void scheduleScanningIfExternalClass(final String className, final String relationship) { // Don't scan Object if (className != null && !className.equals("java.lang.Object") // Only schedule each external class once for scanning, across all threads && classNamesScheduledForScanning.add(className)) { // Search for the named class' classfile among classpath elements, in classpath order (this is O(N) // for each class, but there shouldn't be too many cases of extending scanning upwards) final String classfilePath = JarUtils.classNameToClassfilePath(className); // First check current classpath element, to avoid iterating through other classpath elements Resource classResource = classpathElement.getResource(classfilePath); ClasspathElement foundInClasspathElt = null; if (classResource != null) { // Found the classfile in the current classpath element foundInClasspathElt = classpathElement; } else { // Didn't find the classfile in the current classpath element -- iterate through other elements for (final ClasspathElement classpathOrderElt : classpathOrder) { if (classpathOrderElt != classpathElement) { classResource = classpathOrderElt.getResource(classfilePath); if (classResource != null) { foundInClasspathElt = classpathOrderElt; break; } } } } if (classResource != null) { // Found class resource if (log != null) { log.log("Scheduling external class for scanning: " + relationship + " " + className + (foundInClasspathElt == classpathElement ? "" : " -- found in classpath element " + foundInClasspathElt)); } if (additionalWorkUnits == null) { additionalWorkUnits = new ArrayList<>(); } // Schedule class resource for scanning additionalWorkUnits.add(new ClassfileScanWorkUnit(foundInClasspathElt, classResource, /* isExternalClass = */ true)); } else { if (log != null) { log.log("External " + relationship + " " + className + " was not found in " + "non-blacklisted packages -- cannot extend scanning to this class"); } } } }
java
private void extendScanningUpwards() { // Check superclass if (superclassName != null) { scheduleScanningIfExternalClass(superclassName, "superclass"); } // Check implemented interfaces if (implementedInterfaces != null) { for (final String interfaceName : implementedInterfaces) { scheduleScanningIfExternalClass(interfaceName, "interface"); } } // Check class annotations if (classAnnotations != null) { for (final AnnotationInfo annotationInfo : classAnnotations) { scheduleScanningIfExternalClass(annotationInfo.getName(), "class annotation"); } } // Check method annotations and method parameter annotations if (methodInfoList != null) { for (final MethodInfo methodInfo : methodInfoList) { if (methodInfo.annotationInfo != null) { for (final AnnotationInfo methodAnnotationInfo : methodInfo.annotationInfo) { scheduleScanningIfExternalClass(methodAnnotationInfo.getName(), "method annotation"); } if (methodInfo.parameterAnnotationInfo != null && methodInfo.parameterAnnotationInfo.length > 0) { for (final AnnotationInfo[] paramAnns : methodInfo.parameterAnnotationInfo) { if (paramAnns != null && paramAnns.length > 0) { for (final AnnotationInfo paramAnn : paramAnns) { scheduleScanningIfExternalClass(paramAnn.getName(), "method parameter annotation"); } } } } } } } // Check field annotations if (fieldInfoList != null) { for (final FieldInfo fieldInfo : fieldInfoList) { if (fieldInfo.annotationInfo != null) { for (final AnnotationInfo fieldAnnotationInfo : fieldInfo.annotationInfo) { scheduleScanningIfExternalClass(fieldAnnotationInfo.getName(), "field annotation"); } } } } }
java
void link(final Map<String, ClassInfo> classNameToClassInfo, final Map<String, PackageInfo> packageNameToPackageInfo, final Map<String, ModuleInfo> moduleNameToModuleInfo) { boolean isModuleDescriptor = false; boolean isPackageDescriptor = false; ClassInfo classInfo = null; if (className.equals("module-info")) { isModuleDescriptor = true; } else if (className.equals("package-info") || className.endsWith(".package-info")) { isPackageDescriptor = true; } else { // Handle regular classfile classInfo = ClassInfo.addScannedClass(className, classModifiers, isExternalClass, classNameToClassInfo, classpathElement, classfileResource); classInfo.setModifiers(classModifiers); classInfo.setIsInterface(isInterface); classInfo.setIsAnnotation(isAnnotation); if (superclassName != null) { classInfo.addSuperclass(superclassName, classNameToClassInfo); } if (implementedInterfaces != null) { for (final String interfaceName : implementedInterfaces) { classInfo.addImplementedInterface(interfaceName, classNameToClassInfo); } } if (classAnnotations != null) { for (final AnnotationInfo classAnnotation : classAnnotations) { classInfo.addClassAnnotation(classAnnotation, classNameToClassInfo); } } if (classContainmentEntries != null) { ClassInfo.addClassContainment(classContainmentEntries, classNameToClassInfo); } if (annotationParamDefaultValues != null) { classInfo.addAnnotationParamDefaultValues(annotationParamDefaultValues); } if (fullyQualifiedDefiningMethodName != null) { classInfo.addFullyQualifiedDefiningMethodName(fullyQualifiedDefiningMethodName); } if (fieldInfoList != null) { classInfo.addFieldInfo(fieldInfoList, classNameToClassInfo); } if (methodInfoList != null) { classInfo.addMethodInfo(methodInfoList, classNameToClassInfo); } if (typeSignature != null) { classInfo.setTypeSignature(typeSignature); } if (refdClassNames != null) { classInfo.addReferencedClassNames(refdClassNames); } } // Get or create PackageInfo, if this is not a module descriptor (the module descriptor's package is "") PackageInfo packageInfo = null; if (!isModuleDescriptor) { // Get package for this class or package descriptor packageInfo = PackageInfo.getOrCreatePackage(PackageInfo.getParentPackageName(className), packageNameToPackageInfo); if (isPackageDescriptor) { // Add any class annotations on the package-info.class file to the ModuleInfo packageInfo.addAnnotations(classAnnotations); } else if (classInfo != null) { // Add ClassInfo to PackageInfo, and vice versa packageInfo.addClassInfo(classInfo); classInfo.packageInfo = packageInfo; } } // Get or create ModuleInfo, if there is a module name final String moduleName = classpathElement.getModuleName(); if (moduleName != null) { // Get or create a ModuleInfo object for this module ModuleInfo moduleInfo = moduleNameToModuleInfo.get(moduleName); if (moduleInfo == null) { moduleNameToModuleInfo.put(moduleName, moduleInfo = new ModuleInfo(classfileResource.getModuleRef(), classpathElement)); } if (isModuleDescriptor) { // Add any class annotations on the module-info.class file to the ModuleInfo moduleInfo.addAnnotations(classAnnotations); } if (classInfo != null) { // Add ClassInfo to ModuleInfo, and vice versa moduleInfo.addClassInfo(classInfo); classInfo.moduleInfo = moduleInfo; } if (packageInfo != null) { // Add PackageInfo to ModuleInfo moduleInfo.addPackageInfo(packageInfo); } } }
java
private String intern(final String str) { if (str == null) { return null; } final String interned = stringInternMap.putIfAbsent(str, str); if (interned != null) { return interned; } return str; }
java
private int getConstantPoolStringOffset(final int cpIdx, final int subFieldIdx) throws ClassfileFormatException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } final int t = entryTag[cpIdx]; if ((t != 12 && subFieldIdx != 0) || (t == 12 && subFieldIdx != 0 && subFieldIdx != 1)) { throw new ClassfileFormatException( "Bad subfield index " + subFieldIdx + " for tag " + t + ", cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } int cpIdxToUse; if (t == 0) { // Assume this means null return 0; } else if (t == 1) { // CONSTANT_Utf8 cpIdxToUse = cpIdx; } else if (t == 7 || t == 8 || t == 19) { // t == 7 => CONSTANT_Class, e.g. "[[I", "[Ljava/lang/Thread;"; t == 8 => CONSTANT_String; // t == 19 => CONSTANT_Method_Info final int indirIdx = indirectStringRefs[cpIdx]; if (indirIdx == -1) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } if (indirIdx == 0) { // I assume this represents a null string, since the zeroeth entry is unused return 0; } cpIdxToUse = indirIdx; } else if (t == 12) { // CONSTANT_NameAndType_info final int compoundIndirIdx = indirectStringRefs[cpIdx]; if (compoundIndirIdx == -1) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } final int indirIdx = (subFieldIdx == 0 ? (compoundIndirIdx >> 16) : compoundIndirIdx) & 0xffff; if (indirIdx == 0) { // Should not happen throw new ClassfileFormatException("Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } cpIdxToUse = indirIdx; } else { throw new ClassfileFormatException("Wrong tag number " + t + " at constant pool index " + cpIdx + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); } if (cpIdxToUse < 1 || cpIdxToUse >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return entryOffset[cpIdxToUse]; }
java
private String getConstantPoolString(final int cpIdx, final int subFieldIdx) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, subFieldIdx); return constantPoolStringOffset == 0 ? null : intern(inputStreamOrByteBuffer.readString(constantPoolStringOffset, /* replaceSlashWithDot = */ false, /* stripLSemicolon = */ false)); }
java
private byte getConstantPoolStringFirstByte(final int cpIdx) throws ClassfileFormatException, IOException { final int constantPoolStringOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); if (constantPoolStringOffset == 0) { return '\0'; } final int utfLen = inputStreamOrByteBuffer.readUnsignedShort(constantPoolStringOffset); if (utfLen == 0) { return '\0'; } return inputStreamOrByteBuffer.buf[constantPoolStringOffset + 2]; }
java
private boolean constantPoolStringEquals(final int cpIdx, final String asciiString) throws ClassfileFormatException, IOException { final int strOffset = getConstantPoolStringOffset(cpIdx, /* subFieldIdx = */ 0); if (strOffset == 0) { return asciiString == null; } else if (asciiString == null) { return false; } final int strLen = inputStreamOrByteBuffer.readUnsignedShort(strOffset); final int otherLen = asciiString.length(); if (strLen != otherLen) { return false; } final int strStart = strOffset + 2; for (int i = 0; i < strLen; i++) { if ((char) (inputStreamOrByteBuffer.buf[strStart + i] & 0xff) != asciiString.charAt(i)) { return false; } } return true; }
java
private int cpReadUnsignedShort(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return inputStreamOrByteBuffer.readUnsignedShort(entryOffset[cpIdx]); }
java
private int cpReadInt(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return inputStreamOrByteBuffer.readInt(entryOffset[cpIdx]); }
java
private long cpReadLong(final int cpIdx) throws IOException { if (cpIdx < 1 || cpIdx >= cpCount) { throw new ClassfileFormatException("Constant pool index " + cpIdx + ", should be in range [1, " + (cpCount - 1) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } return inputStreamOrByteBuffer.readLong(entryOffset[cpIdx]); }
java
private Object getFieldConstantPoolValue(final int tag, final char fieldTypeDescriptorFirstChar, final int cpIdx) throws ClassfileFormatException, IOException { switch (tag) { case 1: // Modified UTF8 case 7: // Class -- N.B. Unused? Class references do not seem to actually be stored as constant initalizers case 8: // String // Forward or backward indirect reference to a modified UTF8 entry return getConstantPoolString(cpIdx); case 3: // int, short, char, byte, boolean are all represented by Constant_INTEGER final int intVal = cpReadInt(cpIdx); switch (fieldTypeDescriptorFirstChar) { case 'I': return intVal; case 'S': return (short) intVal; case 'C': return (char) intVal; case 'B': return (byte) intVal; case 'Z': return intVal != 0; default: // Fall through } throw new ClassfileFormatException("Unknown Constant_INTEGER type " + fieldTypeDescriptorFirstChar + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); case 4: // float return Float.intBitsToFloat(cpReadInt(cpIdx)); case 5: // long return cpReadLong(cpIdx); case 6: // double return Double.longBitsToDouble(cpReadLong(cpIdx)); default: // ClassGraph doesn't expect other types // (N.B. in particular, enum values are not stored in the constant pool, so don't need to be handled) throw new ClassfileFormatException("Unknown constant pool tag " + tag + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues"); } }
java
private AnnotationInfo readAnnotation() throws IOException { // Lcom/xyz/Annotation; -> Lcom.xyz.Annotation; final String annotationClassName = getConstantPoolClassDescriptor( inputStreamOrByteBuffer.readUnsignedShort()); final int numElementValuePairs = inputStreamOrByteBuffer.readUnsignedShort(); AnnotationParameterValueList paramVals = null; if (numElementValuePairs > 0) { paramVals = new AnnotationParameterValueList(numElementValuePairs); for (int i = 0; i < numElementValuePairs; i++) { final String paramName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); final Object paramValue = readAnnotationElementValue(); paramVals.add(new AnnotationParameterValue(paramName, paramValue)); } } return new AnnotationInfo(annotationClassName, paramVals); }
java
private Object readAnnotationElementValue() throws IOException { final int tag = (char) inputStreamOrByteBuffer.readUnsignedByte(); switch (tag) { case 'B': return (byte) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()); case 'C': return (char) cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()); case 'D': return Double.longBitsToDouble(cpReadLong(inputStreamOrByteBuffer.readUnsignedShort())); case 'F': return Float.intBitsToFloat(cpReadInt(inputStreamOrByteBuffer.readUnsignedShort())); case 'I': return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()); case 'J': return cpReadLong(inputStreamOrByteBuffer.readUnsignedShort()); case 'S': return (short) cpReadUnsignedShort(inputStreamOrByteBuffer.readUnsignedShort()); case 'Z': return cpReadInt(inputStreamOrByteBuffer.readUnsignedShort()) != 0; case 's': return getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); case 'e': { // Return type is AnnotationEnumVal. final String annotationClassName = getConstantPoolClassDescriptor( inputStreamOrByteBuffer.readUnsignedShort()); final String annotationConstName = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); return new AnnotationEnumValue(annotationClassName, annotationConstName); } case 'c': // Return type is AnnotationClassRef (for class references in annotations) final String classRefTypeDescriptor = getConstantPoolString( inputStreamOrByteBuffer.readUnsignedShort()); return new AnnotationClassRef(classRefTypeDescriptor); case '@': // Complex (nested) annotation. Return type is AnnotationInfo. return readAnnotation(); case '[': // Return type is Object[] (of nested annotation element values) final int count = inputStreamOrByteBuffer.readUnsignedShort(); final Object[] arr = new Object[count]; for (int i = 0; i < count; ++i) { // Nested annotation element value arr[i] = readAnnotationElementValue(); } return arr; default: throw new ClassfileFormatException("Class " + className + " has unknown annotation element type tag '" + ((char) tag) + "': element size unknown, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues"); } }
java
private void readBasicClassInfo() throws IOException, ClassfileFormatException, SkipClassException { // Modifier flags classModifiers = inputStreamOrByteBuffer.readUnsignedShort(); isInterface = (classModifiers & 0x0200) != 0; isAnnotation = (classModifiers & 0x2000) != 0; // The fully-qualified class name of this class, with slashes replaced with dots final String classNamePath = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); if (classNamePath == null) { throw new ClassfileFormatException("Class name is null"); } className = classNamePath.replace('/', '.'); if ("java.lang.Object".equals(className)) { // Don't process java.lang.Object (it has a null superclass), though you can still search for classes // that are subclasses of java.lang.Object (as an external class). throw new SkipClassException("No need to scan java.lang.Object"); } // Check class visibility modifiers final boolean isModule = (classModifiers & 0x8000) != 0; // Equivalently filename is "module-info.class" final boolean isPackage = relativePath.regionMatches(relativePath.lastIndexOf('/') + 1, "package-info.class", 0, 18); if (!scanSpec.ignoreClassVisibility && !Modifier.isPublic(classModifiers) && !isModule && !isPackage) { throw new SkipClassException("Class is not public, and ignoreClassVisibility() was not called"); } // Make sure classname matches relative path if (!relativePath.endsWith(".class")) { // Should not happen throw new SkipClassException("Classfile filename " + relativePath + " does not end in \".class\""); } final int len = classNamePath.length(); if (relativePath.length() != len + 6 || !classNamePath.regionMatches(0, relativePath, 0, len)) { throw new SkipClassException( "Relative path " + relativePath + " does not match class name " + className); } // Superclass name, with slashes replaced with dots final int superclassNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); if (superclassNameCpIdx > 0) { superclassName = getConstantPoolClassName(superclassNameCpIdx); } }
java
private void readInterfaces() throws IOException { // Interfaces final int interfaceCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int i = 0; i < interfaceCount; i++) { final String interfaceName = getConstantPoolClassName(inputStreamOrByteBuffer.readUnsignedShort()); if (implementedInterfaces == null) { implementedInterfaces = new ArrayList<>(); } implementedInterfaces.add(interfaceName); } }
java
private void readClassAttributes() throws IOException, ClassfileFormatException { // Class attributes (including class annotations, class type variables, module info, etc.) final int attributesCount = inputStreamOrByteBuffer.readUnsignedShort(); for (int i = 0; i < attributesCount; i++) { final int attributeNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final int attributeLength = inputStreamOrByteBuffer.readInt(); if (scanSpec.enableAnnotationInfo // && (constantPoolStringEquals(attributeNameCpIdx, "RuntimeVisibleAnnotations") || (!scanSpec.disableRuntimeInvisibleAnnotations && constantPoolStringEquals( attributeNameCpIdx, "RuntimeInvisibleAnnotations")))) { final int annotationCount = inputStreamOrByteBuffer.readUnsignedShort(); if (annotationCount > 0) { if (classAnnotations == null) { classAnnotations = new AnnotationInfoList(); } for (int m = 0; m < annotationCount; m++) { classAnnotations.add(readAnnotation()); } } } else if (constantPoolStringEquals(attributeNameCpIdx, "InnerClasses")) { final int numInnerClasses = inputStreamOrByteBuffer.readUnsignedShort(); for (int j = 0; j < numInnerClasses; j++) { final int innerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); final int outerClassInfoCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); if (innerClassInfoCpIdx != 0 && outerClassInfoCpIdx != 0) { if (classContainmentEntries == null) { classContainmentEntries = new ArrayList<>(); } classContainmentEntries.add(new SimpleEntry<>(getConstantPoolClassName(innerClassInfoCpIdx), getConstantPoolClassName(outerClassInfoCpIdx))); } inputStreamOrByteBuffer.skip(2); // inner_name_idx inputStreamOrByteBuffer.skip(2); // inner_class_access_flags } } else if (constantPoolStringEquals(attributeNameCpIdx, "Signature")) { // Get class type signature, including type variables typeSignature = getConstantPoolString(inputStreamOrByteBuffer.readUnsignedShort()); } else if (constantPoolStringEquals(attributeNameCpIdx, "EnclosingMethod")) { final String innermostEnclosingClassName = getConstantPoolClassName( inputStreamOrByteBuffer.readUnsignedShort()); final int enclosingMethodCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); String definingMethodName; if (enclosingMethodCpIdx == 0) { // A cpIdx of 0 (which is an invalid value) is used for anonymous inner classes declared in // class initializer code, e.g. assigned to a class field. definingMethodName = "<clinit>"; } else { definingMethodName = getConstantPoolString(enclosingMethodCpIdx, /* subFieldIdx = */ 0); // Could also fetch method type signature using subFieldIdx = 1, if needed } // Link anonymous inner classes into the class with their containing method if (classContainmentEntries == null) { classContainmentEntries = new ArrayList<>(); } classContainmentEntries.add(new SimpleEntry<>(className, innermostEnclosingClassName)); // Also store the fully-qualified name of the enclosing method, to mark this as an anonymous inner // class this.fullyQualifiedDefiningMethodName = innermostEnclosingClassName + "." + definingMethodName; } else if (constantPoolStringEquals(attributeNameCpIdx, "Module")) { final int moduleNameCpIdx = inputStreamOrByteBuffer.readUnsignedShort(); classpathElement.moduleNameFromModuleDescriptor = getConstantPoolString(moduleNameCpIdx); // (Future work): parse the rest of the module descriptor fields, and add to ModuleInfo: // https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.25 inputStreamOrByteBuffer.skip(attributeLength - 2); } else { inputStreamOrByteBuffer.skip(attributeLength); } } }
java
private void appendPath(final StringBuilder buf) { if (parentZipFileSlice != null) { parentZipFileSlice.appendPath(buf); if (buf.length() > 0) { buf.append("!/"); } } buf.append(pathWithinParentZipFileSlice); }
java
public void filterClasspathElements(final ClasspathElementFilter classpathElementFilter) { if (this.classpathElementFilters == null) { this.classpathElementFilters = new ArrayList<>(2); } this.classpathElementFilters.add(classpathElementFilter); }
java
private static boolean isModuleLayer(final Object moduleLayer) { if (moduleLayer == null) { throw new IllegalArgumentException("ModuleLayer references must not be null"); } for (Class<?> currClass = moduleLayer.getClass(); currClass != null; currClass = currClass .getSuperclass()) { if (currClass.getName().equals("java.lang.ModuleLayer")) { return true; } } return false; }
java
public void addModuleLayer(final Object moduleLayer) { if (!isModuleLayer(moduleLayer)) { throw new IllegalArgumentException("moduleLayer must be of type java.lang.ModuleLayer"); } if (this.addedModuleLayers == null) { this.addedModuleLayers = new ArrayList<>(); } this.addedModuleLayers.add(moduleLayer); }
java
public void log(final LogNode log) { if (log != null) { final LogNode scanSpecLog = log.log("ScanSpec:"); for (final Field field : ScanSpec.class.getDeclaredFields()) { try { scanSpecLog.log(field.getName() + ": " + field.get(this)); } catch (final ReflectiveOperationException e) { // Ignore } } } }
java
private static Class<?>[] getCallStackViaSecurityManager(final LogNode log) { try { return new CallerResolver().getClassContext(); } catch (final SecurityException e) { // Creating a SecurityManager can fail if the current SecurityManager does not allow // RuntimePermission("createSecurityManager") if (log != null) { log.log("Exception while trying to obtain call stack via SecurityManager", e); } return null; } }
java
static Class<?>[] getClassContext(final LogNode log) { // For JRE 9+, use StackWalker to get call stack. // N.B. need to work around StackWalker bug fixed in JDK 13, and backported to 12.0.2 and 11.0.4 // (probably introduced in JDK 9, when StackWalker was introduced): // https://github.com/classgraph/classgraph/issues/341 // https://bugs.openjdk.java.net/browse/JDK-8210457 Class<?>[] stackClasses = null; if ((VersionFinder.JAVA_MAJOR_VERSION == 11 && (VersionFinder.JAVA_MINOR_VERSION >= 1 || VersionFinder.JAVA_SUB_VERSION >= 4) && !VersionFinder.JAVA_IS_EA_VERSION) || (VersionFinder.JAVA_MAJOR_VERSION == 12 && (VersionFinder.JAVA_MINOR_VERSION >= 1 || VersionFinder.JAVA_SUB_VERSION >= 2) && !VersionFinder.JAVA_IS_EA_VERSION) || (VersionFinder.JAVA_MAJOR_VERSION == 13 && !VersionFinder.JAVA_IS_EA_VERSION) || VersionFinder.JAVA_MAJOR_VERSION > 13) { // Invoke with doPrivileged -- see: // http://mail.openjdk.java.net/pipermail/jigsaw-dev/2018-October/013974.html stackClasses = AccessController.doPrivileged(new PrivilegedAction<Class<?>[]>() { @Override public Class<?>[] run() { return getCallStackViaStackWalker(); } }); } // For JRE 7 and 8, use SecurityManager to get call stack if (stackClasses == null || stackClasses.length == 0) { stackClasses = AccessController.doPrivileged(new PrivilegedAction<Class<?>[]>() { @Override public Class<?>[] run() { return getCallStackViaSecurityManager(log); } }); } // As a fallback, use getStackTrace() to try to get the call stack if (stackClasses == null || stackClasses.length == 0) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); if (stackTrace == null || stackTrace.length == 0) { try { throw new Exception(); } catch (final Exception e) { stackTrace = e.getStackTrace(); } } final List<Class<?>> stackClassesList = new ArrayList<>(); for (final StackTraceElement elt : stackTrace) { try { stackClassesList.add(Class.forName(elt.getClassName())); } catch (final ClassNotFoundException | LinkageError ignored) { // Ignored } } if (!stackClassesList.isEmpty()) { stackClasses = stackClassesList.toArray(new Class<?>[0]); } else { // Last-ditch effort -- include just this class in the call stack stackClasses = new Class<?>[] { CallStackReader.class }; } } return stackClasses; }
java
public List<V> values() throws InterruptedException { final List<V> entries = new ArrayList<>(map.size()); for (final Entry<K, SingletonHolder<V>> ent : map.entrySet()) { final V entryValue = ent.getValue().get(); if (entryValue != null) { entries.add(entryValue); } } return entries; }
java