_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q167500
StaticTable.createMap
validation
private static Map<String, Integer> createMap() { int length = STATIC_TABLE.size(); HashMap<String, Integer> ret = new HashMap<String, Integer>(length); // Iterate through the static table in reverse order to // save the smallest index for a given name in the map. for (int index = length; index > 0; index--) { HeaderField entry = getEntry(index); String name = new String(entry.name, 0, entry.name.length, ISO_8859_1); ret.put(name, index); } return ret; }
java
{ "resource": "" }
q167501
HuffmanEncoder.getEncodedLength
validation
public int getEncodedLength(byte[] data) { if (data == null) { throw new NullPointerException("data"); } long len = 0; for (byte b : data) { len += lengths[b & 0xFF]; } return (int)((len + 7) >> 3); }
java
{ "resource": "" }
q167502
DynamicTable.length
validation
public int length() { int length; if (head < tail) { length = headerFields.length - tail + head; } else { length = head - tail; } return length; }
java
{ "resource": "" }
q167503
DynamicTable.add
validation
public void add(HeaderField header) { int headerSize = header.size(); if (headerSize > capacity) { clear(); return; } while (size + headerSize > capacity) { remove(); } headerFields[head++] = header; size += header.size(); if (head == headerFields.length) { head = 0; } }
java
{ "resource": "" }
q167504
DynamicTable.setCapacity
validation
public void setCapacity(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Illegal Capacity: "+ capacity); } // initially capacity will be -1 so init won't return here if (this.capacity == capacity) { return; } this.capacity = capacity; if (capacity == 0) { clear(); } else { // initially size will be 0 so remove won't be called while (size > capacity) { remove(); } } int maxEntries = capacity / HEADER_ENTRY_OVERHEAD; if (capacity % HEADER_ENTRY_OVERHEAD != 0) { maxEntries++; } // check if capacity change requires us to reallocate the array if (headerFields != null && headerFields.length == maxEntries) { return; } HeaderField[] tmp = new HeaderField[maxEntries]; // initially length will be 0 so there will be no copy int len = length(); int cursor = tail; for (int i = 0; i < len; i++) { HeaderField entry = headerFields[cursor++]; tmp[i] = entry; if (cursor == headerFields.length) { cursor = 0; } } this.tail = 0; this.head = tail + len; this.headerFields = tmp; }
java
{ "resource": "" }
q167505
Encoder.encodeHeader
validation
public void encodeHeader(OutputStream out, byte[] name, byte[] value, boolean sensitive) throws IOException { // If the header value is sensitive then it must never be indexed if (sensitive) { int nameIndex = getNameIndex(name); encodeLiteral(out, name, value, IndexType.NEVER, nameIndex); return; } // If the peer will only use the static table if (capacity == 0) { int staticTableIndex = StaticTable.getIndex(name, value); if (staticTableIndex == -1) { int nameIndex = StaticTable.getIndex(name); encodeLiteral(out, name, value, IndexType.NONE, nameIndex); } else { encodeInteger(out, 0x80, 7, staticTableIndex); } return; } int headerSize = HeaderField.sizeOf(name, value); // If the headerSize is greater than the max table size then it must be encoded literally if (headerSize > capacity) { int nameIndex = getNameIndex(name); encodeLiteral(out, name, value, IndexType.NONE, nameIndex); return; } HeaderEntry headerField = getEntry(name, value); if (headerField != null) { int index = getIndex(headerField.index) + StaticTable.length; // Section 6.1. Indexed Header Field Representation encodeInteger(out, 0x80, 7, index); } else { int staticTableIndex = StaticTable.getIndex(name, value); if (staticTableIndex != -1) { // Section 6.1. Indexed Header Field Representation encodeInteger(out, 0x80, 7, staticTableIndex); } else { int nameIndex = getNameIndex(name); if (useIndexing) { ensureCapacity(headerSize); } IndexType indexType = useIndexing ? IndexType.INCREMENTAL : IndexType.NONE; encodeLiteral(out, name, value, indexType, nameIndex); if (useIndexing) { add(name, value); } } } }
java
{ "resource": "" }
q167506
Encoder.setMaxHeaderTableSize
validation
public void setMaxHeaderTableSize(OutputStream out, int maxHeaderTableSize) throws IOException { if (maxHeaderTableSize < 0) { throw new IllegalArgumentException("Illegal Capacity: " + maxHeaderTableSize); } if (capacity == maxHeaderTableSize) { return; } capacity = maxHeaderTableSize; ensureCapacity(0); encodeInteger(out, 0x20, 5, maxHeaderTableSize); }
java
{ "resource": "" }
q167507
Encoder.encodeInteger
validation
private static void encodeInteger(OutputStream out, int mask, int n, int i) throws IOException { if (n < 0 || n > 8) { throw new IllegalArgumentException("N: " + n); } int nbits = 0xFF >>> (8 - n); if (i < nbits) { out.write(mask | i); } else { out.write(mask | nbits); int length = i - nbits; while (true) { if ((length & ~0x7F) == 0) { out.write(length); return; } else { out.write((length & 0x7F) | 0x80); length >>>= 7; } } } }
java
{ "resource": "" }
q167508
Encoder.encodeStringLiteral
validation
private void encodeStringLiteral(OutputStream out, byte[] string) throws IOException { int huffmanLength = Huffman.ENCODER.getEncodedLength(string); if ((huffmanLength < string.length && !forceHuffmanOff) || forceHuffmanOn) { encodeInteger(out, 0x80, 7, huffmanLength); Huffman.ENCODER.encode(out, string); } else { encodeInteger(out, 0x00, 7, string.length); out.write(string, 0, string.length); } }
java
{ "resource": "" }
q167509
Encoder.encodeLiteral
validation
private void encodeLiteral(OutputStream out, byte[] name, byte[] value, IndexType indexType, int nameIndex) throws IOException { int mask; int prefixBits; switch(indexType) { case INCREMENTAL: mask = 0x40; prefixBits = 6; break; case NONE: mask = 0x00; prefixBits = 4; break; case NEVER: mask = 0x10; prefixBits = 4; break; default: throw new IllegalStateException("should not reach here"); } encodeInteger(out, mask, prefixBits, nameIndex == -1 ? 0 : nameIndex); if (nameIndex == -1) { encodeStringLiteral(out, name); } encodeStringLiteral(out, value); }
java
{ "resource": "" }
q167510
Encoder.ensureCapacity
validation
private void ensureCapacity(int headerSize) throws IOException { while (size + headerSize > capacity) { int index = length(); if (index == 0) { break; } remove(); } }
java
{ "resource": "" }
q167511
Encoder.getHeaderField
validation
HeaderField getHeaderField(int index) { HeaderEntry entry = head; while(index-- >= 0) { entry = entry.before; } return entry; }
java
{ "resource": "" }
q167512
Encoder.getEntry
validation
private HeaderEntry getEntry(byte[] name, byte[] value) { if (length() == 0 || name == null || value == null) { return null; } int h = hash(name); int i = index(h); for (HeaderEntry e = headerFields[i]; e != null; e = e.next) { if (e.hash == h && HpackUtil.equals(name, e.name) && HpackUtil.equals(value, e.value)) { return e; } } return null; }
java
{ "resource": "" }
q167513
Encoder.getIndex
validation
private int getIndex(byte[] name) { if (length() == 0 || name == null) { return -1; } int h = hash(name); int i = index(h); int index = -1; for (HeaderEntry e = headerFields[i]; e != null; e = e.next) { if (e.hash == h && HpackUtil.equals(name, e.name)) { index = e.index; break; } } return getIndex(index); }
java
{ "resource": "" }
q167514
Encoder.add
validation
private void add(byte[] name, byte[] value) { int headerSize = HeaderField.sizeOf(name, value); // Clear the table if the header field size is larger than the capacity. if (headerSize > capacity) { clear(); return; } // Evict oldest entries until we have enough capacity. while (size + headerSize > capacity) { remove(); } // Copy name and value that modifications of original do not affect the dynamic table. name = Arrays.copyOf(name, name.length); value = Arrays.copyOf(value, value.length); int h = hash(name); int i = index(h); HeaderEntry old = headerFields[i]; HeaderEntry e = new HeaderEntry(h, name, value, head.before.index - 1, old); headerFields[i] = e; e.addBefore(head); size += headerSize; }
java
{ "resource": "" }
q167515
Encoder.hash
validation
private static int hash(byte[] name) { int h = 0; for (int i = 0; i < name.length; i++) { h = 31 * h + name[i]; } if (h > 0) { return h; } else if (h == Integer.MIN_VALUE) { return Integer.MAX_VALUE; } else { return -h; } }
java
{ "resource": "" }
q167516
HuffmanDecoder.decode
validation
public byte[] decode(byte[] buf) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Node node = root; int current = 0; int bits = 0; for (int i = 0; i < buf.length; i++) { int b = buf[i] & 0xFF; current = (current << 8) | b; bits += 8; while (bits >= 8) { int c = (current >>> (bits - 8)) & 0xFF; node = node.children[c]; bits -= node.bits; if (node.isTerminal()) { if (node.symbol == HpackUtil.HUFFMAN_EOS) { throw EOS_DECODED; } baos.write(node.symbol); node = root; } } } while (bits > 0) { int c = (current << (8 - bits)) & 0xFF; node = node.children[c]; if (node.isTerminal() && node.bits <= bits) { bits -= node.bits; baos.write(node.symbol); node = root; } else { break; } } // Section 5.2. String Literal Representation // Padding not corresponding to the most significant bits of the code // for the EOS symbol (0xFF) MUST be treated as a decoding error. int mask = (1 << bits) - 1; if ((current & mask) != mask) { throw INVALID_PADDING; } return baos.toByteArray(); }
java
{ "resource": "" }
q167517
GroovyShellServiceBean.setDefaultScriptNames
validation
public void setDefaultScriptNames(String scriptNames) { if (!scriptNames.trim().isEmpty()) service.setDefaultScripts(asList(scriptNames.split(","))); }
java
{ "resource": "" }
q167518
Shorts.assertEqualTo
validation
public void assertEqualTo(Description description, Short actual, short expected) { assertNotNull(description, actual); if (!isEqualTo(actual, expected)) { throw failures.failure(description, shouldBeEqual(actual, expected)); } }
java
{ "resource": "" }
q167519
Shorts.assertNotEqualTo
validation
public void assertNotEqualTo(Description description, Short actual, short expected) { assertNotNull(description, actual); if (isEqualTo(actual, expected)) { throw failures.failure(description, shouldNotBeEqual(actual, expected)); } }
java
{ "resource": "" }
q167520
Shorts.assertGreaterThan
validation
public void assertGreaterThan(Description description, Short actual, short expected) { assertNotNull(description, actual); if (!isGreaterThan(actual, expected)) { throw failures.failure(description, ShouldBeGreaterThan.shouldBeGreaterThan(actual, expected)); } }
java
{ "resource": "" }
q167521
Floats.assertGreaterThan
validation
public void assertGreaterThan(Description description, Float actual, float expected) { assertNotNull(description, actual); if (!isGreaterThan(actual, expected)) { throw failures.failure(description, shouldBeGreaterThan(actual, expected)); } }
java
{ "resource": "" }
q167522
Characters.assertEqual
validation
public void assertEqual(Description description, Character actual, char expected) { assertNotNull(description, actual); if (actual.charValue() != expected) { throw failures.failure(description, shouldBeEqual(actual, expected)); } }
java
{ "resource": "" }
q167523
Characters.assertNotEqual
validation
public void assertNotEqual(Description description, Character actual, char other) { assertNotNull(description, actual); if (actual.charValue() == other) { throw failures.failure(description, shouldNotBeEqual(actual, other)); } }
java
{ "resource": "" }
q167524
Characters.assertLessThan
validation
public void assertLessThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (!isLessThan(actual, other)) { throw failures.failure(description, shouldBeLessThan(actual, other)); } }
java
{ "resource": "" }
q167525
Characters.assertNotGreaterThan
validation
public void assertNotGreaterThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (isGreaterThan(actual, other)) { throw failures.failure(description, shouldNotBeGreaterThan(actual, other)); } }
java
{ "resource": "" }
q167526
Characters.assertGreaterThan
validation
public void assertGreaterThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (!isGreaterThan(actual, other)) { throw failures.failure(description, shouldBeGreaterThan(actual, other)); } }
java
{ "resource": "" }
q167527
Characters.assertNotLessThan
validation
public void assertNotLessThan(Description description, Character actual, char other) { assertNotNull(description, actual); if (isLessThan(actual, other)) { throw failures.failure(description, ShouldNotBeLessThan.shouldNotBeLessThan(actual, other)); } }
java
{ "resource": "" }
q167528
Characters.assertLowerCase
validation
public void assertLowerCase(Description description, Character actual) { assertNotNull(description, actual); if (!isLowerCase(actual)) { throw failures.failure(description, shouldBeLowerCase(actual)); } }
java
{ "resource": "" }
q167529
Characters.assertUpperCase
validation
public void assertUpperCase(Description description, Character actual) { assertNotNull(description, actual); if (!isUpperCase(actual)) { throw failures.failure(description, shouldBeUpperCase(actual)); } }
java
{ "resource": "" }
q167530
IntArrays.assertHasSize
validation
public void assertHasSize(Description description, int[] actual, int expectedSize) { arrays.assertHasSize(description, actual, expectedSize); }
java
{ "resource": "" }
q167531
IntArrays.assertContains
validation
public void assertContains(Description description, int[] actual, int[] values) { arrays.assertContains(description, actual, values); }
java
{ "resource": "" }
q167532
Maps.assertContainsKey
validation
public <K> void assertContainsKey(Description description, Map<?, ?> actual, K key) { assertNotNull(description, actual); if (!actual.containsKey(key)) { throw failures.failure(description, shouldContainKey(actual, key)); } }
java
{ "resource": "" }
q167533
Maps.assertDoesNotContainKey
validation
public <K> void assertDoesNotContainKey(Description description, Map<?, ?> actual, K key) { assertNotNull(description, actual); if (actual.containsKey(key)) { throw failures.failure(description, shouldNotContainKey(actual, key)); } }
java
{ "resource": "" }
q167534
Maps.assertContainsValue
validation
public <V> void assertContainsValue(Description description, Map<?, ?> actual, V value) { assertNotNull(description, actual); if (!actual.containsValue(value)) { throw failures.failure(description, shouldContainValue(actual, value)); } }
java
{ "resource": "" }
q167535
Maps.assertDoesNotContainValue
validation
public <V> void assertDoesNotContainValue(Description description, Map<?, ?> actual, V value) { assertNotNull(description, actual); if (actual.containsValue(value)) { throw failures.failure(description, shouldNotContainValue(actual, value)); } }
java
{ "resource": "" }
q167536
Maps.assertDoesNotContainDuplicateValues
validation
public <K, V> void assertDoesNotContainDuplicateValues(Description description, Map<K, V> actual) { assertNotNull(description, actual); Collection<?> duplicates = duplicatesFrom(actual.values()); if (!duplicates.isEmpty()) { throw failures.failure(description, shouldNotHaveDuplicates(actual, duplicates)); } }
java
{ "resource": "" }
q167537
BigDecimals.assertEqual
validation
public void assertEqual(Description description, BigDecimal actual, BigDecimal expected) { checkNumberIsNotNull(expected); assertNotNull(description, actual); comparables.assertEqual(description, actual, expected); }
java
{ "resource": "" }
q167538
BigDecimals.assertIsZero
validation
public void assertIsZero(Description description, BigDecimal actual) { comparables.assertEqual(description, actual, ZERO); }
java
{ "resource": "" }
q167539
BigDecimals.assertIsNotZero
validation
public void assertIsNotZero(Description description, BigDecimal actual) { comparables.assertNotEqual(description, actual, ZERO); }
java
{ "resource": "" }
q167540
BigDecimals.assertIsPositive
validation
public void assertIsPositive(Description description, BigDecimal actual) { comparables.assertGreaterThan(description, actual, ZERO); }
java
{ "resource": "" }
q167541
BigDecimals.assertIsNegative
validation
public void assertIsNegative(Description description, BigDecimal actual) { comparables.assertLessThan(description, actual, ZERO); }
java
{ "resource": "" }
q167542
FloatAssert.isEqualTo
validation
public FloatAssert isEqualTo(float expected, Offset<Float> offset) { floats.assertEqual(description, actual, expected, offset); return this; }
java
{ "resource": "" }
q167543
ByteArrayAssert.contains
validation
public ByteArrayAssert contains(byte value, Index index) { arrays.assertContains(description, actual, value, index); return this; }
java
{ "resource": "" }
q167544
Doubles.assertNotEqual
validation
public void assertNotEqual(Description description, Double actual, Double expected, Offset<Double> offset) { checkOffsetIsNotNull(offset); checkNumberIsNotNull(expected); assertNotNull(description, actual); if (isEqualTo(actual, expected, offset)) { throw failures.failure(description, shouldNotBeEqual(actual, expected)); } }
java
{ "resource": "" }
q167545
Doubles.assertNotGreaterThan
validation
public void assertNotGreaterThan(Description description, Double actual, double expected) { assertNotNull(description, actual); if (isGreaterThan(actual, expected)) { throw failures.failure(description, shouldNotBeGreaterThan(actual, expected)); } }
java
{ "resource": "" }
q167546
Doubles.assertLessThan
validation
public void assertLessThan(Description description, Double actual, double expected) { assertNotNull(description, actual); if (!isLessThan(actual, expected)) { throw failures.failure(description, shouldBeLessThan(actual, expected)); } }
java
{ "resource": "" }
q167547
Doubles.assertNotLessThan
validation
public void assertNotLessThan(Description description, Double actual, double expected) { assertNotNull(description, actual); if (isLessThan(actual, expected)) { throw failures.failure(description, shouldNotBeLessThan(actual, expected)); } }
java
{ "resource": "" }
q167548
ByteArrays.assertContainsOnly
validation
public void assertContainsOnly(Description description, byte[] actual, byte[] values) { arrays.assertContainsOnly(description, actual, values); }
java
{ "resource": "" }
q167549
ByteArrays.assertContainsSequence
validation
public void assertContainsSequence(Description description, byte[] actual, byte[] sequence) { arrays.assertContainsSequence(description, actual, sequence); }
java
{ "resource": "" }
q167550
Objects.assertEqual
validation
public void assertEqual(Description description, Object actual, Object expected) { if (!areEqual(actual, expected)) { throw shouldBeEqual(actual, expected).newAssertionError(description); } }
java
{ "resource": "" }
q167551
Objects.assertNotEqual
validation
public void assertNotEqual(Description description, Object actual, Object other) { if (areEqual(actual, other)) { throw failures.failure(description, shouldNotBeEqual(actual, other)); } }
java
{ "resource": "" }
q167552
Objects.assertSame
validation
public void assertSame(Description description, Object actual, Object expected) { if (actual != expected) { String format = "expected:<%s> and actual:<%s> should refer to the same instance"; throw failures.failure(description, new BasicErrorMessageFactory(format, expected, actual)); } }
java
{ "resource": "" }
q167553
Objects.assertNotSame
validation
public void assertNotSame(Description description, Object actual, Object other) { if (actual == other) { String format = "expected not same:<%s>"; throw failures.failure(description, new BasicErrorMessageFactory(format, actual)); } }
java
{ "resource": "" }
q167554
CharArrays.assertDoesNotContain
validation
public void assertDoesNotContain(Description description, char[] actual, char[] values) { arrays.assertDoesNotContain(description, actual, values); }
java
{ "resource": "" }
q167555
CharArrays.assertIsSorted
validation
public void assertIsSorted(Description description, char[] actual) { if(actual == null) { throw failures.failure("The actual is null"); } if (actual.length == 0) { return; } for (int i = 0; i < actual.length - 1; i++) { if (actual[i] > actual[i + 1]) { throw failures.failure(description, shouldBeSorted(i, actual)); } } }
java
{ "resource": "" }
q167556
ArgumentMatchers.named
validation
@Factory public static <T> Matcher<T> named(String name, Matcher<T> matcher) { return describedAs("%0 = %1", matcher, name, matcher); }
java
{ "resource": "" }
q167557
ArgumentMatchers.notEmptyString
validation
@Factory public static Matcher<String> notEmptyString() { return new CustomTypeSafeMatcher<String>("not empty") { @Override protected boolean matchesSafely(String s) { return !s.isEmpty(); } }; }
java
{ "resource": "" }
q167558
JsonEncoderDecoderClassCreator.getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance
validation
static String getMiddleNameForPrefixingAsAccessorMutatorJavaBeansSpecCompliance(String fieldName) { if (fieldName.length() > 1 && Character.isUpperCase(fieldName.charAt(1))) { return fieldName; } return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); }
java
{ "resource": "" }
q167559
JsonEncoderDecoderClassCreator.exists
validation
private boolean exists(JClassType type, JField field, String fieldName, boolean isSetter) { if (field instanceof DummyJField) { return true; } JType[] args; if (isSetter) { args = new JType[] { field.getType() }; } else { args = new JType[] {}; } JMethod m = type.findMethod(fieldName, args); if (null != m) { if (isIgnored(m)) { return false; } if (isSetter) { return true; } JClassType returnType = m.getReturnType().isClassOrInterface(); JClassType fieldType = field.getType().isClassOrInterface(); if (returnType == null || fieldType == null) { // at least one is a primitive type return m.getReturnType().equals(field.getType()); } // both are non-primitives return returnType.isAssignableFrom(fieldType); } try { JType objectType = find(Object.class, getLogger(), context); JClassType superType = type.getSuperclass(); if (!objectType.equals(superType)) { return exists(superType, field, fieldName, isSetter); } } catch (UnableToCompleteException e) { // do nothing } return false; }
java
{ "resource": "" }
q167560
BindingDefaults.getAnnotationResolvers
validation
public static List<AnnotationResolver> getAnnotationResolvers(GeneratorContext context, TreeLogger logger) { // do this only the first time call if (null == _annotationResolversRequested) { // call additional AnnotationResolvers if there are some configured try { for (String className : context.getPropertyOracle() .getConfigurationProperty("org.fusesource.restygwt.annotationresolver").getValues()) { logger.log(TreeLogger.INFO, "classname to resolve: " + className); Class<?> clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { throw new RuntimeException("could not resolve class " + className + " " + e.getMessage()); } if (null != clazz) { try { logger.log(TreeLogger.INFO, "add annotationresolver: " + clazz.getName()); addAnnotationResolver((AnnotationResolver) clazz.newInstance()); } catch (InstantiationException e) { throw new RuntimeException("could not instanciate class " + className + " " + e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException("could not access class " + className + " " + e.getMessage()); } } else { throw new RuntimeException("could not create instance for classname " + className); } } } catch (BadPropertyValueException ignored) { /* * ignored since there is no * * <set-configuration-property name="org.fusesource.restygwt.annotationresolver" * value="org.fusesource.restygwt.rebind.ModelChangeAnnotationResolver"/> */ logger.log(TreeLogger.DEBUG, "no additional annotationresolvers found"); } } // return a copy List<AnnotationResolver> ret = new ArrayList<AnnotationResolver>(); ret.addAll(annotationResolvers); return _annotationResolversRequested = ret; }
java
{ "resource": "" }
q167561
Method.expect
validation
public Method expect(int... statuses) { if (statuses.length == 1 && statuses[0] < 0) { anyStatus = true; } else { anyStatus = false; expectedStatuses.clear(); for (int status : statuses) { expectedStatuses.add(status); } } return this; }
java
{ "resource": "" }
q167562
BaseSourceCreator.reduceName
validation
private String reduceName(String newClassName, String suffix) { if (newClassName.length() < MAX_FILE_NAME_LENGTH) { return newClassName; } // String sufx = "_Gen_GwtJackEncDec_"; //Lets first try to reduce the package name of the parametrized types // according to parametersName2ClassName parametrized types //Lets find if there are parametrized types String noSufix = newClassName.substring(0, newClassName.length() - suffix.length()); if (newClassName.indexOf("__") > 0) { //has generic String primaryName = noSufix.substring(0, noSufix.indexOf("__")); String genericPart = noSufix.substring(noSufix.indexOf("__") + 2); StringBuilder stringBuilder = new StringBuilder(); String[] eachGeneric = genericPart.split("__"); for (String genericType : eachGeneric) { stringBuilder.append("__"); stringBuilder.append(reduceType(genericType)); } String finalName = primaryName + stringBuilder.toString() + suffix; if (finalName.length() > MAX_FILE_NAME_LENGTH) { //File name is still too long wrapping it out aggressively String baseName = primaryName + stringBuilder.toString(); int firstPosition = baseName.indexOf("__"); int lastPosition = baseName.lastIndexOf("__"); String middle = baseName.substring(firstPosition, lastPosition); finalName = baseName.substring(0, firstPosition) + middle.subSequence(0, 4) + "_" + (middle.length() - 5) + "_" + middle.substring(middle.length() - 9) + baseName.substring(lastPosition) + suffix; return finalName; } return finalName; } //If there is no generic type lets give an error and force the client to reduce className return newClassName; }
java
{ "resource": "" }
q167563
BaseSourceCreator.getBooleanProperty
validation
protected static boolean getBooleanProperty(TreeLogger logger, PropertyOracle propertyOracle, String propertyName, boolean defaultValue) { try { SelectionProperty prop = propertyOracle.getSelectionProperty(logger, propertyName); String propVal = prop.getCurrentValue(); return Boolean.parseBoolean(propVal); } catch (BadPropertyValueException e) { // return the default value } return defaultValue; }
java
{ "resource": "" }
q167564
CachingCallbackFilter.filter
validation
@Override public RequestCallback filter(Method method, Response response, RequestCallback callback) { int code = response.getStatusCode(); final CacheKey ck = cacheKey(method.builder); final List<RequestCallback> removedCallbacks = cache.removeCallbacks(ck); if (removedCallbacks != null) { callback = new RequestCallback() { @Override public void onResponseReceived(Request request, Response response) { if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .finer("call " + removedCallbacks.size() + " more queued callbacks for " + ck); } // call all callbacks found in cache for (RequestCallback cb : removedCallbacks) { cb.onResponseReceived(request, response); } } @Override public void onError(Request request, Throwable exception) { if (LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()).severe( "cannot call " + (removedCallbacks.size() + 1) + " callbacks for " + ck + " due to error: " + exception.getMessage()); } if (LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .finer("call " + removedCallbacks.size() + " more queued callbacks for " + ck); } // and all the others, found in cache for (RequestCallback cb : removedCallbacks) { cb.onError(request, exception); } } }; } else { if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .finer("removed one or no " + "callback for cachekey " + ck); } } if (isCachingStatusCode(code)) { cacheResult(method, response); return callback; } if (GWT.isClient() && LogConfiguration.loggingIsEnabled()) { Logger.getLogger(CachingCallbackFilter.class.getName()) .info("cannot cache due to invalid response code: " + code); } return callback; }
java
{ "resource": "" }
q167565
ModelChangeAnnotationResolver.getAnnotationsAsStringArray
validation
@SuppressWarnings("rawtypes") private String[] getAnnotationsAsStringArray(Class[] classes) { if (null == classes) { return null; } List<String> ret = new ArrayList<String>(); for (Class c : classes) { ret.add(c.getName()); } return ret.toArray(new String[ret.size()]); }
java
{ "resource": "" }
q167566
JsonpMethod.send
validation
public Object send(AsyncCallback<JavaScriptObject> callback) { return jsonpBuilder.requestObject(resource.getUri(), callback); }
java
{ "resource": "" }
q167567
TokenRequestHandler.process
validation
private Response process( MultivaluedMap<String, String> parameters, String clientId, String clientSecret, String[] clientCertificatePath) { // Extra properties to associate with an access token. Property[] properties = mSpi.getProperties(); String clientCertificate = null; if (clientCertificatePath != null && clientCertificatePath.length > 0) { // The first one is the client's certificate. clientCertificate = clientCertificatePath[0]; // if we have more in the path, pass them along separately without the first one if (clientCertificatePath.length > 1) { clientCertificatePath = Arrays.copyOfRange( clientCertificatePath, 1, clientCertificatePath.length); } } // Call Authlete's /api/auth/token API. TokenResponse response = getApiCaller().callToken( parameters, clientId, clientSecret, properties, clientCertificate, clientCertificatePath); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INVALID_CLIENT: // 401 Unauthorized return ResponseUtil.unauthorized(content, CHALLENGE); case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case PASSWORD: // Process the token request whose flow is "Resource Owner Password Credentials". return handlePassword(response); case OK: // 200 OK return ResponseUtil.ok(content); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/token", action); } }
java
{ "resource": "" }
q167568
TokenRequestHandler.handlePassword
validation
private Response handlePassword(TokenResponse response) { // The credentials of the resource owner. String username = response.getUsername(); String password = response.getPassword(); // Validate the credentials. String subject = mSpi.authenticateUser(username, password); // Extra properties to associate with an access token. Property[] properties = mSpi.getProperties(); // The ticket for Authlete's /api/auth/token/* API. String ticket = response.getTicket(); if (subject != null) { // Issue an access token and optionally an ID token. return getApiCaller().tokenIssue(ticket, subject, properties); } else { // The credentials are invalid. An access token is not issued. throw getApiCaller().tokenFail(ticket, Reason.INVALID_RESOURCE_OWNER_CREDENTIALS); } }
java
{ "resource": "" }
q167569
AuthorizationDecisionHandler.handle
validation
public Response handle(String ticket, String[] claimNames, String[] claimLocales) throws WebApplicationException { try { // Process the end-user's decision. return process(ticket, claimNames, claimLocales); } catch (WebApplicationException e) { throw e; } catch (Throwable t) { // Unexpected error. throw unexpected("Unexpected error in AuthorizationDecisionHandler", t); } }
java
{ "resource": "" }
q167570
AuthorizationDecisionHandler.process
validation
private Response process(String ticket, String[] claimNames, String[] claimLocales) { // If the end-user did not grant authorization to the client application. if (mSpi.isClientAuthorized() == false) { // The end-user denied the authorization request. return fail(ticket, Reason.DENIED); } // The subject (= unique identifier) of the end-user. String subject = mSpi.getUserSubject(); // If the subject of the end-user is not available. if (subject == null || subject.length() == 0) { // The end-user is not authenticated. return fail(ticket, Reason.NOT_AUTHENTICATED); } // The time when the end-user was authenticated. long authTime = mSpi.getUserAuthenticatedAt(); // The ACR (Authentication Context Class Reference) of the // end-user authentication. String acr = mSpi.getAcr(); // Collect claim values. Map<String, Object> claims = collectClaims(subject, claimNames, claimLocales); // Extra properties to associate with an access token and/or // an authorization code. Property[] properties = mSpi.getProperties(); // Scopes to associate with an access token and/or an authorization code. // If a non-null value is returned from mSpi.getScopes(), the scope set // replaces the scopes that have been specified in the original // authorization request. String[] scopes = mSpi.getScopes(); // Authorize the authorization request. return authorize(ticket, subject, authTime, acr, claims, properties, scopes); }
java
{ "resource": "" }
q167571
AuthorizationDecisionHandler.collectClaims
validation
private Map<String, Object> collectClaims(String subject, String[] claimNames, String[] claimLocales) { // If no claim is required. if (claimNames == null || claimNames.length == 0) { return null; } // Drop empty and duplicate entries from claimLocales. claimLocales = normalizeClaimLocales(claimLocales); // Claim values. Map<String, Object> claims = new HashMap<String, Object>(); // For each requested claim. for (String claimName : claimNames) { // If the claim name is empty. if (claimName == null || claimName.length() == 0) { continue; } // Split the claim name into the name part and the tag part. String[] elements = claimName.split("#", 2); String name = elements[0]; String tag = (elements.length == 2) ? elements[1] : null; // If the name part is empty. if (name == null || name.length() == 0) { continue; } // Get the claim value of the claim. Object value = getClaim(name, tag, claimLocales); // If the claim value was not obtained. if (value == null) { continue; } if (tag == null) { // Just for an edge case where claimName ends with "#". claimName = name; } // Add the pair of the claim name and the claim value. claims.put(claimName, value); } // If no claim value has been obtained. if (claims.size() == 0) { return null; } // Obtained claim values. return claims; }
java
{ "resource": "" }
q167572
BaseAuthorizationDecisionEndpoint.handle
validation
public Response handle( AuthleteApi api, AuthorizationDecisionHandlerSpi spi, String ticket, String[] claimNames, String[] claimLocales) { try { // Create a handler. AuthorizationDecisionHandler handler = new AuthorizationDecisionHandler(api, spi); // Delegate the task to the handler. return handler.handle(ticket, claimNames, claimLocales); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }
java
{ "resource": "" }
q167573
AuthleteApiCaller.userInfoIssue
validation
public Response userInfoIssue(String accessToken, Map<String, Object> claims) { // Call Authlete's /api/auth/userinfo/issue API. UserInfoIssueResponse response = callUserInfoIssue(accessToken, claims); // 'action' in the response denotes the next action which // this service implementation should take. UserInfoIssueResponse.Action action = response.getAction(); // The content of the response to the client application. // The format of the content varies depending on the action. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.bearerError(Status.INTERNAL_SERVER_ERROR, content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.bearerError(Status.BAD_REQUEST, content); case UNAUTHORIZED: // 401 Unauthorized return ResponseUtil.bearerError(Status.UNAUTHORIZED, content); case FORBIDDEN: // 403 Forbidden return ResponseUtil.bearerError(Status.FORBIDDEN, content); case JSON: // 200 OK, application/json;charset=UTF-8 return ResponseUtil.ok(content); case JWT: // 200 OK, application/jwt return ResponseUtil.ok(content, ResponseUtil.MEDIA_TYPE_JWT); default: // This never happens. throw unknownAction("/api/auth/userinfo/issue", action); } }
java
{ "resource": "" }
q167574
AuthorizationPageModel.computeLoginId
validation
private static String computeLoginId(AuthorizationResponse info) { if (info.getSubject() != null) { return info.getSubject(); } return info.getLoginHint(); }
java
{ "resource": "" }
q167575
BaseJwksEndpoint.handle
validation
public Response handle(AuthleteApi api) { try { // Create a handler. JwksRequestHandler handler = new JwksRequestHandler(api); // Delegate the task to the handler. return handler.handle(); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }
java
{ "resource": "" }
q167576
BaseIntrospectionEndpoint.handle
validation
public Response handle(AuthleteApi api, MultivaluedMap<String, String> parameters) { try { // Create a handler. IntrospectionRequestHandler handler = new IntrospectionRequestHandler(api); // Delegate the task to the handler. return handler.handle(parameters); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }
java
{ "resource": "" }
q167577
AuthleteApiImpl.createServiceOwnerCredentials
validation
private String createServiceOwnerCredentials(AuthleteConfiguration configuration) { if (configuration.getServiceOwnerAccessToken() != null) { return "Bearer " + configuration.getServiceOwnerAccessToken(); } else { String key = configuration.getServiceOwnerApiKey(); String secret = configuration.getServiceOwnerApiSecret(); return new BasicCredentials(key, secret).format(); } }
java
{ "resource": "" }
q167578
AuthleteApiImpl.createServiceCredentials
validation
private String createServiceCredentials(AuthleteConfiguration configuration) { if (configuration.getServiceAccessToken() != null) { return "Bearer " + configuration.getServiceAccessToken(); } else { String key = configuration.getServiceApiKey(); String secret = configuration.getServiceApiSecret(); return new BasicCredentials(key, secret).format(); } }
java
{ "resource": "" }
q167579
AuthleteApiImpl.getJaxRsClient
validation
private javax.ws.rs.client.Client getJaxRsClient() { // If a JAX-RS client has not been created yet. if (mJaxRsClient == null) { // Create a JAX-RS client. javax.ws.rs.client.Client client = createJaxRsClient(); synchronized (this) { if (mJaxRsClient == null) { mJaxRsClient = client; } } } // Set a connection timeout. setConnectionTimeout(mJaxRsClient); // Set a read timeout. setReadTimeout(mJaxRsClient); return mJaxRsClient; }
java
{ "resource": "" }
q167580
AuthleteApiImpl.createJaxRsClient
validation
private javax.ws.rs.client.Client createJaxRsClient() { if (getJaxRsClientBuilder() != null) { // if we have a builder configured, use it return getJaxRsClientBuilder().build(); } else { // otherwise just use the system discovered default return ClientBuilder.newClient(); } }
java
{ "resource": "" }
q167581
AuthleteApiImpl.setConnectionTimeout
validation
private void setConnectionTimeout(javax.ws.rs.client.Client client) { // The timeout value. int timeout = mSettings.getConnectionTimeout(); synchronized (mConnectionTimeoutLock) { if (mCurrentConnectionTimeout == timeout) { // The given value is the same as the current one. // Let's skip calling property() method. return; } // The given value is different from the current value. // Let's update the configuration. mCurrentConnectionTimeout = timeout; } //---------------------------------------------------------------------- // Note that there was no standardized way to set the connection timeout // before JAX-RS API 2.1 (Java EE 8) (cf. ClientBuilder.connectTimeout). //---------------------------------------------------------------------- // Convert int to Integer before calling property() method multiple times // in order to reduce the number of object creation by autoboxing. Integer value = Integer.valueOf(timeout); // For Jersey client.property("jersey.config.client.connectTimeout", value); // For Apache CXF client.property("http.connection.timeout", value); // For WebSphere (8.5.5.7+) client.property("com.ibm.ws.jaxrs.client.connection.timeout", value); }
java
{ "resource": "" }
q167582
AuthleteApiImpl.setReadTimeout
validation
private void setReadTimeout(javax.ws.rs.client.Client client) { // The timeout value. int timeout = mSettings.getReadTimeout(); synchronized (mReadTimeoutLock) { if (mCurrentReadTimeout == timeout) { // The given value is the same as the current one. // Let's skip calling property() method. return; } // The given value is different from the current value. // Let's update the configuration. mCurrentReadTimeout = timeout; } //---------------------------------------------------------------------- // Note that there was no standardized way to set the read timeout // before JAX-RS API 2.1 (Java EE 8) (cf. ClientBuilder.readTimeout). //---------------------------------------------------------------------- // Convert int to Integer before calling property() method multiple times // in order to reduce the number of object creation by autoboxing. Integer value = Integer.valueOf(timeout); // For Jersey client.property("jersey.config.client.readTimeout", value); // For Apache CXF client.property("http.receive.timeout", value); // For WebSphere (8.5.5.7+) client.property("com.ibm.ws.jaxrs.client.receive.timeout", value); }
java
{ "resource": "" }
q167583
AuthleteApiImpl.executeApiCall
validation
private <TResponse> TResponse executeApiCall(AuthleteApiCall<TResponse> apiCall) throws AuthleteApiException { try { // Call the Authlete API. return apiCall.call(); } catch (WebApplicationException e) { // Throw an exception with HTTP response information. throw createApiException(e, e.getResponse()); } catch (ResponseProcessingException e) { // Throw an exception with HTTP response information. throw createApiException(e, e.getResponse()); } catch (Throwable t) { // Throw an exception without HTTP response information. throw createApiException(t, null); } }
java
{ "resource": "" }
q167584
BaseAuthorizationEndpoint.handle
validation
public Response handle( AuthleteApi api, AuthorizationRequestHandlerSpi spi, MultivaluedMap<String, String> parameters) { try { // Create a handler. AuthorizationRequestHandler handler = new AuthorizationRequestHandler(api, spi); // Delegate the task to the handler. return handler.handle(parameters); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }
java
{ "resource": "" }
q167585
IntrospectionRequestHandler.process
validation
private Response process(MultivaluedMap<String, String> parameters) { // Call Authlete's /api/auth/introspection/standard API. StandardIntrospectionResponse response = getApiCaller().callStandardIntrospection(parameters); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case OK: // 200 OK return ResponseUtil.ok(content); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/introspection/standard", action); } }
java
{ "resource": "" }
q167586
UserInfoRequestHandler.process
validation
private Response process(String accessToken) { // Call Authlete's /api/auth/userinfo API. UserInfoResponse response = getApiCaller().callUserInfo(accessToken); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.bearerError(Status.INTERNAL_SERVER_ERROR, content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.bearerError(Status.BAD_REQUEST, content); case UNAUTHORIZED: // 401 Unauthorized return ResponseUtil.bearerError(Status.UNAUTHORIZED, content); case FORBIDDEN: // 403 Forbidden return ResponseUtil.bearerError(Status.FORBIDDEN, content); case OK: // Return the user information. return getUserInfo(response); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/userinfo", action); } }
java
{ "resource": "" }
q167587
BaseUserInfoEndpoint.handle
validation
public Response handle( AuthleteApi api, UserInfoRequestHandlerSpi spi, String accessToken) { try { // Create a handler. UserInfoRequestHandler handler = new UserInfoRequestHandler(api, spi); // Delegate the task to the handler. return handler.handle(accessToken); } catch (WebApplicationException e) { // An error occurred in the handler. onError(e); // Convert the error to a Response. return e.getResponse(); } }
java
{ "resource": "" }
q167588
AuthorizationRequestHandler.process
validation
private Response process(MultivaluedMap<String, String> parameters) { // Call Authlete's /api/auth/authorization API. AuthorizationResponse response = getApiCaller().callAuthorization(parameters); // 'action' in the response denotes the next action which // this service implementation should take. AuthorizationResponse.Action action = response.getAction(); // The content of the response to the client application. // The format of the content varies depending on the action. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case LOCATION: // 302 Found return ResponseUtil.location(content); case FORM: // 200 OK return ResponseUtil.form(content); case INTERACTION: // Process the authorization request with user interaction. return handleInteraction(response); case NO_INTERACTION: // Process the authorization request without user interaction. // The flow reaches here only when the authorization request // contained prompt=none. return handleNoInteraction(response); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/authorization", action); } }
java
{ "resource": "" }
q167589
AuthorizationRequestHandler.noInteractionCheckAuthentication
validation
private void noInteractionCheckAuthentication(AuthorizationResponse response) { // If the current user has already been authenticated. if (mSpi.isUserAuthenticated()) { // OK. return; } // A user must have logged in. throw getApiCaller().authorizationFail(response.getTicket(), Reason.NOT_LOGGED_IN); }
java
{ "resource": "" }
q167590
RevocationRequestHandler.process
validation
private Response process(MultivaluedMap<String, String> parameters, String clientId, String clientSecret) { // Call Authlete's /api/auth/revocation API. RevocationResponse response = getApiCaller().callRevocation(parameters, clientId, clientSecret); // 'action' in the response denotes the next action which // this service implementation should take. Action action = response.getAction(); // The content of the response to the client application. String content = response.getResponseContent(); // Dispatch according to the action. switch (action) { case INVALID_CLIENT: // 401 Unauthorized return ResponseUtil.unauthorized(content, CHALLENGE); case INTERNAL_SERVER_ERROR: // 500 Internal Server Error return ResponseUtil.internalServerError(content); case BAD_REQUEST: // 400 Bad Request return ResponseUtil.badRequest(content); case OK: // 200 OK return ResponseUtil.javaScript(content); default: // This never happens. throw getApiCaller().unknownAction("/api/auth/revocation", action); } }
java
{ "resource": "" }
q167591
BaseEndpoint.extractClientCertificate
validation
protected String extractClientCertificate(HttpServletRequest request) { String[] certs = extractClientCertificateChain(request); if (certs != null && certs.length > 0) { return certs[0]; } else { return null; } }
java
{ "resource": "" }
q167592
ImpliedRepoMaintainer.updateImpliedStores
validation
public void updateImpliedStores( @Observes final ArtifactStorePreUpdateEvent event ) { if ( !storeManager.isStarted() ) { return; } if ( !config.isEnabled() ) { logger.debug( "Implied-repository processing is not enabled." ); return; } try { // TODO: Update for changes map. final Map<StoreKey, ArtifactStore> currentStores = mapStores( event ); for ( final ArtifactStore store : event ) { logger.debug( "Processing store: {} for implied repo metadata", store ); processStore( store, currentStores ); } } catch ( Throwable error ) { Logger logger = LoggerFactory.getLogger( getClass() ); logger.error( String.format( "Implied-repository maintenance failed: %s", error.getMessage() ), error ); } }
java
{ "resource": "" }
q167593
CertUtils.generateX509Certificate
validation
public static X509Certificate generateX509Certificate( KeyPair pair, String dn, int days, String algorithm ) throws GeneralSecurityException, IOException { PrivateKey privateKey = pair.getPrivate(); X509CertInfo info = new X509CertInfo(); Date from = new Date(); Date to = new Date( from.getTime() + TimeUnit.DAYS.toMillis( days ) ); CertificateValidity interval = new CertificateValidity( from, to ); BigInteger sn = new BigInteger( 64, new SecureRandom() ); X500Name owner = new X500Name( dn ); info.set( X509CertInfo.VALIDITY, interval ); info.set( X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber( sn ) ); info.set( X509CertInfo.SUBJECT, owner ); info.set( X509CertInfo.ISSUER, owner ); info.set( X509CertInfo.KEY, new CertificateX509Key( pair.getPublic() ) ); info.set( X509CertInfo.VERSION, new CertificateVersion( CertificateVersion.V3 ) ); AlgorithmId algo = new AlgorithmId( AlgorithmId.sha256WithRSAEncryption_oid ); info.set( X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId( algo ) ); // Sign the cert to identify the algorithm that's used. X509CertImpl cert = new X509CertImpl( info ); cert.sign( privateKey, algorithm ); // Update the algorithm, and resign. algo = (AlgorithmId) cert.get( X509CertImpl.SIG_ALG ); info.set( CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo ); cert = new X509CertImpl( info ); cert.sign( privateKey, algorithm ); return cert; }
java
{ "resource": "" }
q167594
IndyMetricsConstants.getName
validation
public static String getName( String nodePrefix, String name, String defaultName, String... suffix ) { if ( isBlank( name ) || name.equals( DEFAULT ) ) { name = defaultName; } return name( name( nodePrefix, name ), suffix ); }
java
{ "resource": "" }
q167595
RelateGenerationManager.generateRelationshipFile
validation
public Transfer generateRelationshipFile( Transfer transfer, TransferOperation op ) { final Logger logger = LoggerFactory.getLogger( getClass() ); if ( !config.isEnabled() ) { logger.debug( "Relate Add-on is not enabled." ); return null; } logger.debug( "Relate generation for {}", transfer ); if ( transfer == null ) { logger.debug( "No transfer. No .rel generation performed." ); return null; } String txfrPath = transfer.getPath(); if ( !txfrPath.endsWith( ".pom" ) ) { logger.debug( "This is not a pom transfer." ); return null; } ArtifactPathInfo artPathInfo = ArtifactPathInfo.parse( txfrPath ); if ( artPathInfo == null ) { logger.debug( "Not an artifact download ({}). No .rel generation performed.", txfrPath ); return null; } ConcreteResource pomResource = transfer.getResource(); StoreKey storeKey = StoreKey.fromString( transfer.getLocation().getName() ); ArtifactStore store; try { store = storeManager.getArtifactStore( storeKey ); } catch ( final IndyDataException ex ) { logger.error( "Error retrieving artifactStore with key " + storeKey, ex ); return null; } logger.debug( "Generate .rel corresponding to associated POM download: {}/{}", storeKey, pomResource.getPath() ); try { URI source = new URI( pomResource.getLocation().getUri() + REL_SUFFIX ); ProjectVersionRef ref = artPathInfo.getProjectId(); // get all groups that this store is a member of Set<ArtifactStore> stores = new HashSet<>(); stores.add( store ); stores.addAll( storeManager.query().getGroupsContaining( store.getKey() ) ); List<? extends Location> supplementalLocations = LocationUtils.toLocations( stores.toArray( new ArtifactStore[0] ) ); MavenPomView pomView = mavenPomReader.read( ref, transfer, supplementalLocations, ALL_PROFILES ); EProjectDirectRelationships rel = mavenModelProcessor.readRelationships( pomView, source, new ModelProcessorConfig() ); Transfer transferRel = transfer.getSiblingMeta( REL_SUFFIX ); writeRelationships( rel, transferRel, op ); return transferRel; } catch ( Exception e ) { logger.error( "Error generating .rel file for " + txfrPath + " from store " + store, e ); return null; } }
java
{ "resource": "" }
q167596
GitManager.commit
validation
public int commit() throws GitSubsystemException { int committed = lockAnd(me->{ final int size = changelogEntries.size(); if ( !changelogEntries.isEmpty() ) { try { CommitCommand commit = git.commit(); StringBuilder sb = new StringBuilder().append( COMMIT_CHANGELOG_ENTRIES + "\n\n" ); for ( ChangelogEntry et : changelogEntries ) { sb.append( et.getUsername() + " " + et.getTimestamp() + " " + et.getMessage() ); sb.append( "\n\n" ); } String message = sb.toString(); logger.info( message ); commit.setMessage( message ).setAuthor( SYSTEM_USER, email ).call(); changelogEntries.clear(); } catch ( final JGitInternalException | GitAPIException e ) { throw new GitSubsystemException( "Cannot commit to git: " + e.getMessage(), e ); } } return size; }); return committed; }
java
{ "resource": "" }
q167597
IndyZabbixReporter.addSnapshotDataObject
validation
private void addSnapshotDataObject( String key, Snapshot snapshot, long clock, List<DataObject> dataObjectList ) { dataObjectList.add( toDataObject( key, ".min", snapshot.getMin(), clock ) ); dataObjectList.add( toDataObject( key, ".max", snapshot.getMax(), clock ) ); dataObjectList.add( toDataObject( key, ".mean", snapshot.getMean(), clock ) ); dataObjectList.add( toDataObject( key, ".stddev", snapshot.getStdDev(), clock ) ); dataObjectList.add( toDataObject( key, ".median", snapshot.getMedian(), clock ) ); dataObjectList.add( toDataObject( key, ".75th", snapshot.get75thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".95th", snapshot.get95thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".98th", snapshot.get98thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".99th", snapshot.get99thPercentile(), clock ) ); dataObjectList.add( toDataObject( key, ".99.9th", snapshot.get999thPercentile(), clock ) ); }
java
{ "resource": "" }
q167598
ProxyResponseHelper.getRemoteRepositoryName
validation
private String getRemoteRepositoryName( URL url ) throws IndyDataException { final String name = repoCreator.formatId( url.getHost(), getPort( url ), 0, null, StoreType.remote ); logger.debug( "Looking for remote repo starts with name: {}", name ); AbstractProxyRepositoryCreator abstractProxyRepositoryCreator = null; if ( repoCreator instanceof AbstractProxyRepositoryCreator ) { abstractProxyRepositoryCreator = (AbstractProxyRepositoryCreator) repoCreator; } if ( abstractProxyRepositoryCreator == null ) { return name; } Predicate<ArtifactStore> filter = abstractProxyRepositoryCreator.getNameFilter( name ); List<String> l = storeManager.query() .packageType( GENERIC_PKG_KEY ) .storeType( RemoteRepository.class ) .stream( filter ) .map( repository -> repository.getName() ) .collect( Collectors.toList() ); if ( l.isEmpty() ) { return name; } return abstractProxyRepositoryCreator.getNextName( l ); }
java
{ "resource": "" }
q167599
AbstractProxyRepositoryCreator.getNextName
validation
public String getNextName( List<String> names ) { if ( names.isEmpty() ) { return null; } String name0 = names.get( 0 ); if ( names.size() == 1 ) { return name0 + "_1"; } Collections.sort( names ); String last = names.get( names.size() - 1 ); String index = last.substring( last.lastIndexOf( "_" ) + 1 ); return name0 + "_" + ( Integer.parseInt( index ) + 1 ); }
java
{ "resource": "" }