_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q15700 | FamFamFlags.getFlagFromLocale | train | @Nullable
public static EFamFamFlagIcon getFlagFromLocale (@Nullable final Locale aFlagLocale)
{
if (aFlagLocale != null)
{
final String sCountry = aFlagLocale.getCountry ();
if (StringHelper.hasText (sCountry))
return EFamFamFlagIcon.getFromIDOrNull (sCountry);
}
return null;
} | java | {
"resource": ""
} |
q15701 | DynamicSelectEkstaziMojo.checkIfEkstaziDirCanBeCreated | train | private void checkIfEkstaziDirCanBeCreated() throws MojoExecutionException {
File ekstaziDir = Config.createRootDir(parentdir);
// If .ekstazi does not exist and cannot be created, let them
// know. (We also remove directory if successfully created.)
if (!ekstaziDir.exists() && (!ekstaziDir.mkdirs() || !ekstaziDir.delete())) {
throw new MojoExecutionException("Cannot create Ekstazi directory in " + parentdir);
}
} | java | {
"resource": ""
} |
q15702 | SystemMessageData.setSystemMessage | train | @Nonnull
public EChange setSystemMessage (@Nonnull final ESystemMessageType eMessageType, @Nullable final String sMessage)
{
ValueEnforcer.notNull (eMessageType, "MessageType");
if (m_eMessageType.equals (eMessageType) && EqualsHelper.equals (m_sMessage, sMessage))
return EChange.UNCHANGED;
internalSetMessageType (eMessageType);
internalSetMessage (sMessage);
setLastUpdate (PDTFactory.getCurrentLocalDateTime ());
return EChange.CHANGED;
} | java | {
"resource": ""
} |
q15703 | CrtAuthServer.createChallenge | train | public String createChallenge(String request)
throws IllegalArgumentException, ProtocolVersionException {
String userName;
userName = CrtAuthCodec.deserializeRequest(request);
Fingerprint fingerprint;
try {
fingerprint = new Fingerprint(getKeyForUser(userName));
} catch (KeyNotFoundException e) {
log.info("No public key found for user {}, creating fake fingerprint", userName);
fingerprint = createFakeFingerprint(userName);
}
byte[] uniqueData = new byte[Challenge.UNIQUE_DATA_LENGTH];
UnsignedInteger timeNow = timeSupplier.getTime();
random.nextBytes(uniqueData);
Challenge challenge = Challenge.newBuilder()
.setFingerprint(fingerprint)
.setUniqueData(uniqueData)
.setValidFromTimestamp(timeNow.minus(CLOCK_FUDGE))
.setValidToTimestamp(timeNow.plus(RESPONSE_TIMEOUT))
.setServerName(serverName)
.setUserName(userName)
.build();
return encode(CrtAuthCodec.serialize(challenge, secret));
} | java | {
"resource": ""
} |
q15704 | CrtAuthServer.getKeyForUser | train | private RSAPublicKey getKeyForUser(String userName) throws KeyNotFoundException {
RSAPublicKey key = null;
for (final KeyProvider keyProvider : keyProviders) {
try {
key = keyProvider.getKey(userName);
break;
} catch (KeyNotFoundException e) {
// that's fine, try the next provider
}
}
if (key == null) {
throw new KeyNotFoundException();
}
return key;
} | java | {
"resource": ""
} |
q15705 | CrtAuthServer.createFakeFingerprint | train | private Fingerprint createFakeFingerprint(String userName) {
byte[] usernameHmac = CrtAuthCodec.getAuthenticationCode(
this.secret, userName.getBytes(Charsets.UTF_8));
return new Fingerprint(Arrays.copyOfRange(usernameHmac, 0, 6));
} | java | {
"resource": ""
} |
q15706 | CrtAuthServer.createToken | train | public String createToken(String response)
throws IllegalArgumentException, ProtocolVersionException {
final Response decodedResponse;
final Challenge challenge;
decodedResponse = CrtAuthCodec.deserializeResponse(decode(response));
challenge = CrtAuthCodec.deserializeChallengeAuthenticated(
decodedResponse.getPayload(), secret);
if (!challenge.getServerName().equals(serverName)) {
throw new IllegalArgumentException("Got challenge with the wrong server_name encoded.");
}
PublicKey publicKey;
try {
publicKey = getKeyForUser(challenge.getUserName());
} catch (KeyNotFoundException e) {
// If the user requesting authentication doesn't have a public key, we throw an
// InvalidInputException. This normally shouldn't happen, since at this stage a challenge
// should have already been sent, which in turn requires knowledge of the user's public key.
throw new IllegalArgumentException(e);
}
boolean signatureVerified;
try {
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicKey);
signature.update(decodedResponse.getPayload());
signatureVerified = signature.verify(decodedResponse.getSignature());
} catch (Exception e) {
throw new RuntimeException(e);
}
if (challenge.isExpired(timeSupplier)) {
throw new IllegalArgumentException("The challenge is out of its validity period");
}
if (!signatureVerified) {
throw new IllegalArgumentException("Client did not provide proof that it controls the " +
"secret key.");
}
UnsignedInteger validFrom = timeSupplier.getTime().minus(CLOCK_FUDGE);
UnsignedInteger validTo = timeSupplier.getTime().plus(tokenLifetimeSeconds);
Token token = new Token(validFrom.intValue(), validTo.intValue(), challenge.getUserName());
return encode(CrtAuthCodec.serialize(token, secret));
} | java | {
"resource": ""
} |
q15707 | CrtAuthServer.validateToken | train | public String validateToken(String token)
throws IllegalArgumentException, TokenExpiredException, ProtocolVersionException {
final Token deserializedToken =
CrtAuthCodec.deserializeTokenAuthenticated(decode(token), secret);
if (deserializedToken.isExpired(timeSupplier)) {
throw new TokenExpiredException();
}
if (deserializedToken.getValidTo() - deserializedToken.getValidFrom() > MAX_VALIDITY) {
throw new TokenExpiredException("Overly long token lifetime.");
}
return deserializedToken.getUserName();
} | java | {
"resource": ""
} |
q15708 | Lexers.lookupLexer | train | public Optional<Object> lookupLexer(PyGateway gateway, String alias) {
Object result = lexerCache.get(alias);
if (result == null) {
result = evalLookupLexer(gateway, alias, NULL);
lexerCache.put(alias, result);
}
if (result == NULL) {
return Optional.absent();
} else {
return Optional.of(result);
}
} | java | {
"resource": ""
} |
q15709 | ChannelSftpRunner.execute | train | @Nonnull
public static ESuccess execute (@Nonnull final IJSchSessionProvider aSessionProvider,
final int nChannelConnectTimeoutMillis,
@Nonnull final IChannelSftpRunnable aRunnable) throws JSchException
{
ValueEnforcer.notNull (aSessionProvider, "SessionProvider");
ValueEnforcer.notNull (aRunnable, "Runnable");
Session aSession = null;
Channel aChannel = null;
ChannelSftp aSFTPChannel = null;
try
{
// get session from pool
aSession = aSessionProvider.createSession ();
if (aSession == null)
throw new IllegalStateException ("Failed to create JSch session from provider");
// Open the SFTP channel
aChannel = aSession.openChannel ("sftp");
// Set connection timeout
aChannel.connect (nChannelConnectTimeoutMillis);
aSFTPChannel = (ChannelSftp) aChannel;
// call callback
aRunnable.execute (aSFTPChannel);
return ESuccess.SUCCESS;
}
catch (final SftpException ex)
{
LOGGER.error ("Error peforming SFTP action: " + aRunnable.getDisplayName (), ex);
return ESuccess.FAILURE;
}
finally
{
// end SFTP session
if (aSFTPChannel != null)
aSFTPChannel.quit ();
// close channel
if (aChannel != null && aChannel.isConnected ())
aChannel.disconnect ();
// destroy session
if (aSession != null)
JSchSessionFactory.destroySession (aSession);
}
} | java | {
"resource": ""
} |
q15710 | GlobalPasswordSettings.setPasswordConstraintList | train | public static void setPasswordConstraintList (@Nonnull final IPasswordConstraintList aPasswordConstraintList)
{
ValueEnforcer.notNull (aPasswordConstraintList, "PasswordConstraintList");
// Create a copy
final IPasswordConstraintList aRealPasswordConstraints = aPasswordConstraintList.getClone ();
s_aRWLock.writeLocked ( () -> {
s_aPasswordConstraintList = aRealPasswordConstraints;
});
LOGGER.info ("Set global password constraints to " + aRealPasswordConstraints);
} | java | {
"resource": ""
} |
q15711 | EkstaziCFT.createCoverageClassVisitor | train | private CoverageClassVisitor createCoverageClassVisitor(String className, ClassWriter cv, boolean isRedefined) {
// We cannot change classfiles if class is being redefined.
return new CoverageClassVisitor(className, cv);
} | java | {
"resource": ""
} |
q15712 | EkstaziCFT.isMonitorAccessibleFromClassLoader | train | private boolean isMonitorAccessibleFromClassLoader(ClassLoader loader) {
if (loader == null) {
return false;
}
boolean isMonitorAccessible = true;
InputStream monitorInputStream = null;
try {
monitorInputStream = loader.getResourceAsStream(COVERAGE_MONITOR_RESOURCE);
if (monitorInputStream == null) {
isMonitorAccessible = false;
}
} catch (Exception ex1) {
isMonitorAccessible = false;
try {
if (monitorInputStream != null) {
monitorInputStream.close();
}
} catch (IOException ex2) {
// do nothing
}
}
return isMonitorAccessible;
} | java | {
"resource": ""
} |
q15713 | EkstaziCFT.saveClassfileBufferForDebugging | train | @SuppressWarnings("unused")
private void saveClassfileBufferForDebugging(String className, byte[] classfileBuffer) {
try {
if (className.contains("CX")) {
java.io.DataOutputStream tmpout = new java.io.DataOutputStream(new java.io.FileOutputStream("out"));
tmpout.write(classfileBuffer, 0, classfileBuffer.length);
tmpout.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
} | java | {
"resource": ""
} |
q15714 | EkstaziCFT.instrumentClassFile | train | private static byte[] instrumentClassFile(byte[] classfileBuffer) {
String className = new ClassReader(classfileBuffer).getClassName().replace("/", ".");
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
byte[] newClassfileBuffer = new EkstaziCFT().transform(currentClassLoader, className, null, null, classfileBuffer);
return newClassfileBuffer;
} | java | {
"resource": ""
} |
q15715 | CollectingJSCodeProvider.addAt | train | @Nonnull
public CollectingJSCodeProvider addAt (@Nonnegative final int nIndex, @Nullable final IHasJSCode aProvider)
{
if (aProvider != null)
m_aList.add (nIndex, aProvider);
return this;
} | java | {
"resource": ""
} |
q15716 | JSFunction.name | train | @Nonnull
public JSFunction name (@Nonnull @Nonempty final String sName)
{
if (!JSMarshaller.isJSIdentifier (sName))
throw new IllegalArgumentException ("The name '" + sName + "' is not a legal JS identifier!");
m_sName = sName;
return this;
} | java | {
"resource": ""
} |
q15717 | TypeaheadEditSelection.getSelectionForRequiredObject | train | @Nonnull
public static TypeaheadEditSelection getSelectionForRequiredObject (@Nonnull final IWebPageExecutionContext aWPEC,
@Nullable final String sEditFieldName,
@Nullable final String sHiddenFieldName)
{
ValueEnforcer.notNull (aWPEC, "WPEC");
String sEditValue = aWPEC.params ().getAsString (sEditFieldName);
String sHiddenFieldValue = aWPEC.params ().getAsString (sHiddenFieldName);
if (StringHelper.hasText (sHiddenFieldValue))
{
if (StringHelper.hasNoText (sEditValue))
{
// The content of the edit field was deleted after a valid item was once
// selected
sHiddenFieldValue = null;
}
}
else
{
if (StringHelper.hasText (sEditValue))
{
// No ID but a text -> no object selected but only a string typed
sEditValue = null;
}
}
return new TypeaheadEditSelection (sEditValue, sHiddenFieldValue);
} | java | {
"resource": ""
} |
q15718 | BootstrapLoginHTMLProvider.createPageHeader | train | @Nullable
@OverrideOnDemand
protected IHCNode createPageHeader (@Nonnull final ISimpleWebExecutionContext aSWEC,
@Nullable final IHCNode aPageTitle)
{
return BootstrapPageHeader.createOnDemand (aPageTitle);
} | java | {
"resource": ""
} |
q15719 | HCGoogleAnalytics.createEventTrackingCode | train | @Nonnull
public static JSInvocation createEventTrackingCode (@Nonnull final String sCategory,
@Nonnull final String sAction,
@Nullable final String sLabel,
@Nullable final Integer aValue)
{
final JSArray aArray = new JSArray ().add ("_trackEvent").add (sCategory).add (sAction);
if (StringHelper.hasText (sLabel))
aArray.add (sLabel);
if (aValue != null)
aArray.add (aValue.intValue ());
return JSExpr.ref ("_gaq").invoke ("push").arg (aArray);
} | java | {
"resource": ""
} |
q15720 | SemanticTypes.sanitiseSemanticTypes | train | public static Collection<String> sanitiseSemanticTypes(final Collection<String> semanticTypes) {
if (semanticTypes == null) return ImmutableList.of();
// check that each of the given types are in the map we have, otherwise throw it away
final Set<String> s = new LinkedHashSet<>(semanticTypes);
return s.retainAll(SEMANTIC_TYPES_CODE_TO_DESCRIPTION.keySet()) ? s : semanticTypes;
} | java | {
"resource": ""
} |
q15721 | ASTPrinter.printComments | train | public static String printComments(String indent, List<JavaComment> comments) {
final StringBuilder builder = new StringBuilder();
for (JavaComment comment : comments) {
builder.append(print(indent, comment));
builder.append("\n");
}
return builder.toString();
} | java | {
"resource": ""
} |
q15722 | ASTPrinter.print | train | public static String print(final String indent, JavaComment comment) {
return comment.match(new JavaComment.MatchBlock<String>() {
@Override
public String _case(JavaDocComment x) {
final StringBuilder builder = new StringBuilder(indent);
builder.append(x.start);
for (JDToken token : x.generalSection) {
builder.append(print(indent, token));
}
for (JDTagSection tagSection : x.tagSections) {
for (JDToken token : tagSection.tokens) {
builder.append(print(indent, token));
}
}
builder.append(x.end);
return builder.toString();
}
@Override
public String _case(JavaBlockComment comment) {
final StringBuilder builder = new StringBuilder(indent);
for (List<BlockToken> line : comment.lines) {
for (BlockToken token : line) {
builder.append(token.match(new BlockToken.MatchBlock<String>() {
@Override
public String _case(BlockWord x) {
return x.word;
}
@Override
public String _case(BlockWhiteSpace x) {
return x.ws;
}
@Override
public String _case(BlockEOL x) {
return x.content + indent;
}
}));
}
}
return builder.toString();
}
@Override
public String _case(JavaEOLComment x) {
return x.comment;
}
});
} | java | {
"resource": ""
} |
q15723 | ASTPrinter.print | train | public static String print(Arg arg) {
return printArgModifiers(arg.modifiers) + print(arg.type) + " " + arg.name;
} | java | {
"resource": ""
} |
q15724 | ASTPrinter.printArgModifiers | train | public static String printArgModifiers(List<ArgModifier> modifiers) {
final StringBuilder builder = new StringBuilder();
if (modifiers.contains(ArgModifier._Final())) {
builder.append(print(ArgModifier._Final()));
builder.append(" ");
}
if (modifiers.contains(ArgModifier._Transient())) {
builder.append(print(ArgModifier._Transient()));
builder.append(" ");
}
if (modifiers.contains(ArgModifier._Volatile())) {
builder.append(print(ArgModifier._Volatile()));
builder.append(" ");
}
return builder.toString();
} | java | {
"resource": ""
} |
q15725 | ASTPrinter.print | train | public static String print(Type type) {
return type.match(new Type.MatchBlock<String>(){
@Override
public String _case(Ref x) {
return print(x.type);
}
@Override
public String _case(Primitive x) {
return print(x.type);
}
});
} | java | {
"resource": ""
} |
q15726 | ASTPrinter.print | train | public static String print(RefType type) {
return type.match(new RefType.MatchBlock<String>() {
@Override
public String _case(ClassType x) {
final StringBuilder builder = new StringBuilder(x.baseName);
if (!x.typeArguments.isEmpty()) {
builder.append("<");
boolean first = true;
for (RefType typeArgument : x.typeArguments) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append(print(typeArgument));
}
builder.append(">");
}
return builder.toString();
}
@Override
public String _case(ArrayType x) {
return print(x.heldType) + "[]";
}});
} | java | {
"resource": ""
} |
q15727 | ASTPrinter.print | train | public static String print(PrimitiveType type) {
return type.match(new PrimitiveType.MatchBlock<String>() {
@Override
public String _case(BooleanType x) {
return "boolean";
}
@Override
public String _case(ByteType x) {
return "byte";
}
@Override
public String _case(CharType x) {
return "char";
}
@Override
public String _case(DoubleType x) {
return "double";
}
@Override
public String _case(FloatType x) {
return "float";
}
@Override
public String _case(IntType x) {
return "int";
}
@Override
public String _case(LongType x) {
return "long";
}
@Override
public String _case(ShortType x) {
return "short";
}});
} | java | {
"resource": ""
} |
q15728 | ASTPrinter.print | train | public static String print(ArgModifier modifier) {
return modifier.match(new ArgModifier.MatchBlock<String>() {
@Override
public String _case(Final x) {
return "final";
}
@Override
public String _case(Volatile x) {
return "volatile";
}
@Override
public String _case(Transient x) {
return "transient";
}
});
} | java | {
"resource": ""
} |
q15729 | ASTPrinter.print | train | private static String print(final String indent, JDToken token) {
return token.match(new JDToken.MatchBlock<String>() {
@Override
public String _case(JDAsterisk x) {
return "*";
}
@Override
public String _case(JDEOL x) {
return x.content + indent;
}
@Override
public String _case(JDTag x) {
return x.name;
}
@Override
public String _case(JDWord x) {
return x.word;
}
@Override
public String _case(JDWhiteSpace x) {
return x.ws;
}
});
} | java | {
"resource": ""
} |
q15730 | ASTPrinter.print | train | public static String print(final Literal literal) {
return literal.match(new Literal.MatchBlock<String>() {
@Override
public String _case(StringLiteral x) {
return x.content;
}
@Override
public String _case(FloatingPointLiteral x) {
return x.content;
}
@Override
public String _case(IntegerLiteral x) {
return x.content;
}
@Override
public String _case(CharLiteral x) {
return x.content;
}
@Override
public String _case(BooleanLiteral x) {
return x.content;
}
@Override
public String _case(NullLiteral x) {
return "null";
}
});
} | java | {
"resource": ""
} |
q15731 | ASTPrinter.print | train | public static String print(Expression expression) {
return expression.match(new Expression.MatchBlock<String>() {
@Override
public String _case(LiteralExpression x) {
return print(x.literal);
}
@Override
public String _case(VariableExpression x) {
return x.selector.match(new Optional.MatchBlock<Expression, String>() {
@Override
public String _case(Some<Expression> x) {
return print(x.value) + ".";
}
@Override
public String _case(None<Expression> x) {
return "";
}
}) + x.identifier;
}
@Override
public String _case(NestedExpression x) {
return "( " + print(x.expression) + " )";
}
@Override
public String _case(ClassReference x) {
return print(x.type) + ".class";
}
@Override
public String _case(TernaryExpression x) {
return print(x.cond) + " ? " + print(x.trueExpression) + " : " + print (x.falseExpression);
}
@Override
public String _case(BinaryExpression x) {
return print(x.left) + " " + print(x.op) + " " + print(x.right);
}
});
} | java | {
"resource": ""
} |
q15732 | BootstrapSpacingBuilder.property | train | @Nonnull
public BootstrapSpacingBuilder property (@Nonnull final EBootstrapSpacingPropertyType eProperty)
{
ValueEnforcer.notNull (eProperty, "Property");
m_eProperty = eProperty;
return this;
} | java | {
"resource": ""
} |
q15733 | BootstrapSpacingBuilder.side | train | @Nonnull
public BootstrapSpacingBuilder side (@Nonnull final EBootstrapSpacingSideType eSide)
{
ValueEnforcer.notNull (eSide, "Side");
m_eSide = eSide;
return this;
} | java | {
"resource": ""
} |
q15734 | UIStateRegistry.registerState | train | @Nonnull
@SuppressFBWarnings ("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
public EChange registerState (@Nonnull @Nonempty final String sStateID, @Nonnull final IHasUIState aNewState)
{
ValueEnforcer.notEmpty (sStateID, "StateID");
ValueEnforcer.notNull (aNewState, "NewState");
final ObjectType aOT = aNewState.getObjectType ();
if (aOT == null)
throw new IllegalStateException ("Object has no typeID: " + aNewState);
return m_aRWLock.writeLocked ( () -> {
final Map <String, IHasUIState> aMap = m_aMap.computeIfAbsent (aOT, k -> new CommonsHashMap<> ());
if (LOGGER.isDebugEnabled () && aMap.containsKey (sStateID))
LOGGER.debug ("Overwriting " + aOT.getName () + " with ID " + sStateID + " with new object");
aMap.put (sStateID, aNewState);
return EChange.CHANGED;
});
} | java | {
"resource": ""
} |
q15735 | UIStateRegistry.registerState | train | @Nonnull
public EChange registerState (@Nonnull final IHCElement <?> aNewElement)
{
ValueEnforcer.notNull (aNewElement, "NewElement");
if (aNewElement.hasNoID ())
LOGGER.warn ("Registering the state for an object that has no ID - creating a new ID now!");
return registerState (aNewElement.ensureID ().getID (), aNewElement);
} | java | {
"resource": ""
} |
q15736 | FineUploader5Chunking.setPartSize | train | @Nonnull
public FineUploader5Chunking setPartSize (@Nonnegative final long nPartSize)
{
ValueEnforcer.isGT0 (nPartSize, "PartSize");
m_nChunkingPartSize = nPartSize;
return this;
} | java | {
"resource": ""
} |
q15737 | FineUploader5Chunking.setParamNameChunkSize | train | @Nonnull
public FineUploader5Chunking setParamNameChunkSize (@Nonnull @Nonempty final String sParamNameChunkSize)
{
ValueEnforcer.notEmpty (sParamNameChunkSize, "ParamNameChunkSize");
m_sChunkingParamNamesChunkSize = sParamNameChunkSize;
return this;
} | java | {
"resource": ""
} |
q15738 | FineUploader5Chunking.setParamNamePartByteOffset | train | @Nonnull
public FineUploader5Chunking setParamNamePartByteOffset (@Nonnull @Nonempty final String sParamNamePartByteOffset)
{
ValueEnforcer.notEmpty (sParamNamePartByteOffset, "ParamNamePartByteOffset");
m_sChunkingParamNamesPartByteOffset = sParamNamePartByteOffset;
return this;
} | java | {
"resource": ""
} |
q15739 | FineUploader5Chunking.setParamNamePartIndex | train | @Nonnull
public FineUploader5Chunking setParamNamePartIndex (@Nonnull @Nonempty final String sParamNamePartIndex)
{
ValueEnforcer.notEmpty (sParamNamePartIndex, "ParamNamePartIndex");
m_sChunkingParamNamesPartIndex = sParamNamePartIndex;
return this;
} | java | {
"resource": ""
} |
q15740 | FineUploader5Chunking.setParamNameTotalParts | train | @Nonnull
public FineUploader5Chunking setParamNameTotalParts (@Nonnull @Nonempty final String sParamNameTotalParts)
{
ValueEnforcer.notEmpty (sParamNameTotalParts, "ParamNameTotalParts");
m_sChunkingParamNamesTotalParts = sParamNameTotalParts;
return this;
} | java | {
"resource": ""
} |
q15741 | BytecodeCleaner.removeDebugInfo | train | public static byte[] removeDebugInfo(byte[] bytes) {
if (bytes.length >= 4) {
// Check magic number.
int magic = ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16)
| ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff);
if (magic != 0xCAFEBABE)
return bytes;
} else {
return bytes;
}
// We set the initial size as it cannot exceed that value (but note that
// this may not be the final size).
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
DataOutputStream dos = new DataOutputStream(baos);
try {
ClassReader classReader = new ClassReader(bytes);
CleanClass cleanClass = new CleanClass(dos);
classReader.accept(cleanClass, ClassReader.SKIP_DEBUG);
if (cleanClass.isFiltered()) {
return FILTERED_BYTECODE;
}
} catch (Exception ex) {
return bytes;
}
return baos.toByteArray();
} | java | {
"resource": ""
} |
q15742 | HCSWFObject.addFlashVar | train | @Nonnull
public final HCSWFObject addFlashVar (@Nonnull final String sName, final Object aValue)
{
if (!JSMarshaller.isJSIdentifier (sName))
throw new IllegalArgumentException ("The name '" + sName + "' is not a legal JS identifier!");
if (m_aFlashVars == null)
m_aFlashVars = new CommonsLinkedHashMap <> ();
m_aFlashVars.put (sName, aValue);
return this;
} | java | {
"resource": ""
} |
q15743 | HCSWFObject.removeFlashVar | train | @Nonnull
public final HCSWFObject removeFlashVar (@Nullable final String sName)
{
if (m_aFlashVars != null)
m_aFlashVars.remove (sName);
return this;
} | java | {
"resource": ""
} |
q15744 | DynamicEkstazi.initAgentAtRuntimeAndReportSuccess | train | public static Instrumentation initAgentAtRuntimeAndReportSuccess() {
try {
setSystemClassLoaderClassPath();
} catch (Exception e) {
Log.e("Could not set classpath. Tool will be off.", e);
return null;
}
try {
return addClassfileTransformer();
} catch (Exception e) {
Log.e("Could not add transformer. Tool will be off.", e);
return null;
}
} | java | {
"resource": ""
} |
q15745 | DynamicEkstazi.setSystemClassLoaderClassPath | train | private static void setSystemClassLoaderClassPath() throws Exception {
Log.d("Setting classpath");
// We use agent class as we do not extract this class in newly created
// jar (otherwise we may end up creating one -magic jar from another);
// also it will exist even without JUnit classes).
URL url = EkstaziAgent.class.getResource(EkstaziAgent.class.getSimpleName() + ".class");
String origPath = url.getFile().replace("file:", "").replaceAll(".jar!.*", ".jar");
File junitJar = new File(origPath);
File xtsJar = new File(origPath.replaceAll(".jar", "-magic.jar"));
boolean isCreated = false;
// If extracted (Tool) jar is newer than junit*.jar, there is no reason
// to extract files again, so just return in that case.
if (FileUtil.isSecondNewerThanFirst(junitJar, xtsJar)) {
// We cannot return here, as we have to include jar on the path.
isCreated = true;
} else {
// Extract new jar as junit.jar is newer.
String[] includePrefixes = { Names.EKSTAZI_PACKAGE_BIN };
String[] excludePrefixes = { EkstaziAgent.class.getName() };
isCreated = JarXtractor.extract(junitJar, xtsJar, includePrefixes, excludePrefixes);
}
// Add jar to classpath if it was successfully created, otherwise throw
// an exception.
if (isCreated) {
addURL(xtsJar.toURI().toURL());
} else {
throw new RuntimeException("Could not extract Tool classes in separate jar.");
}
} | java | {
"resource": ""
} |
q15746 | DynamicEkstazi.addURL | train | private static void addURL(URL url) throws Exception {
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class<?> sysclass = URLClassLoader.class;
Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(sysloader, new Object[] { url });
} | java | {
"resource": ""
} |
q15747 | CoverageMonitor.t | train | public static void t(Class<?> clz) {
// Must be non null and type of interest.
if (clz == null || ClassesCache.check(clz) || Types.isIgnorable(clz)) {
return;
}
// Check and assign id to this class (this must be synchronized).
try {
sLock.lock();
if (!sClasses.add(clz)) {
return;
}
} finally {
sLock.unlock();
}
String className = clz.getName();
String resourceName = className.substring(className.lastIndexOf(".") + 1).concat(".class");
URL url = null;
try {
// Find resource for the class (URL that we will use to extract
// the path).
url = clz.getResource(resourceName);
} catch (SecurityException ex) {
Log.w("Unable to obtain resource because of security reasons.");
}
// If no URL obtained, return.
if (url == null) {
return;
}
recordURL(url.toExternalForm());
} | java | {
"resource": ""
} |
q15748 | CoverageMonitor.t | train | public static void t(Class<?> clz, int probeId) {
if (clz != null) {
int index = probeId & PROBE_SIZE_MASK;
if (PROBE_ARRAY[index] != clz) {
PROBE_ARRAY[index] = clz;
t(clz);
}
}
} | java | {
"resource": ""
} |
q15749 | CoverageMonitor.addFileURL | train | public static void addFileURL(File f) {
String absolutePath = f.getAbsolutePath();
if (!filterFile(absolutePath)) {
try {
recordURL(f.toURI().toURL().toExternalForm());
} catch (MalformedURLException e) {
// Never expected.
}
}
} | java | {
"resource": ""
} |
q15750 | CoverageMonitor.recordURL | train | protected static void recordURL(String externalForm) {
if (filterURL(externalForm)) {
return;
}
if (isWellKnownUrl(externalForm)) {
// Ignore JUnit classes if specified in configuration.
if (Config.DEPENDENCIES_INCLUDE_WELLKNOWN_V) {
safeRecordURL(externalForm);
}
} else {
safeRecordURL(externalForm);
}
} | java | {
"resource": ""
} |
q15751 | CoverageMonitor.safeRecordURL | train | private static void safeRecordURL(String externalForm) {
try {
sLock.lock();
sURLs.add(externalForm);
} finally {
sLock.unlock();
}
} | java | {
"resource": ""
} |
q15752 | Log.c | train | public static final void c(String msg) {
if (msg.replaceAll("\\s+", "").equals("")) {
println(CONF_TEXT);
} else {
println(CONF_TEXT + ": " + msg);
}
} | java | {
"resource": ""
} |
q15753 | PathDescriptor.matchesParts | train | @Nonnull
public PathMatchingResult matchesParts (@Nonnull final List <String> aPathParts)
{
ValueEnforcer.notNull (aPathParts, "PathParts");
final int nPartCount = m_aPathParts.size ();
if (aPathParts.size () != nPartCount)
{
// Size must match
return PathMatchingResult.NO_MATCH;
}
final ICommonsOrderedMap <String, String> aVariableValues = new CommonsLinkedHashMap <> ();
for (int i = 0; i < nPartCount; ++i)
{
final PathDescriptorPart aPart = m_aPathParts.get (i);
final String sPathPart = aPathParts.get (i);
if (!aPart.matches (sPathPart))
{
// Current part does not match - full error
return PathMatchingResult.NO_MATCH;
}
// Matching variable part?
if (aPart.isVariable ())
aVariableValues.put (aPart.getName (), sPathPart);
}
// We've got it!
return PathMatchingResult.createSuccess (aVariableValues);
} | java | {
"resource": ""
} |
q15754 | FineUploader5Retry.setAutoAttemptDelay | train | @Nonnull
public FineUploader5Retry setAutoAttemptDelay (@Nonnegative final int nAutoAttemptDelay)
{
ValueEnforcer.isGE0 (nAutoAttemptDelay, "AutoAttemptDelay");
m_nRetryAutoAttemptDelay = nAutoAttemptDelay;
return this;
} | java | {
"resource": ""
} |
q15755 | FineUploader5Retry.setMaxAutoAttempts | train | @Nonnull
public FineUploader5Retry setMaxAutoAttempts (@Nonnegative final int nMaxAutoAttempts)
{
ValueEnforcer.isGE0 (nMaxAutoAttempts, "MaxAutoAttempts");
m_nRetryMaxAutoAttempts = nMaxAutoAttempts;
return this;
} | java | {
"resource": ""
} |
q15756 | FineUploader5Retry.setPreventRetryResponseProperty | train | @Nonnull
public FineUploader5Retry setPreventRetryResponseProperty (@Nonnull @Nonempty final String sPreventRetryResponseProperty)
{
ValueEnforcer.notEmpty (sPreventRetryResponseProperty, "PreventRetryResponseProperty");
m_sRetryPreventRetryResponseProperty = sPreventRetryResponseProperty;
return this;
} | java | {
"resource": ""
} |
q15757 | RevocationStatus.markRevoked | train | public void markRevoked (@Nonnull @Nonempty final String sRevocationUserID,
@Nonnull final LocalDateTime aRevocationDT,
@Nonnull @Nonempty final String sRevocationReason)
{
ValueEnforcer.notEmpty (sRevocationUserID, "RevocationUserID");
ValueEnforcer.notNull (aRevocationDT, "RevocationDT");
ValueEnforcer.notEmpty (sRevocationReason, "RevocationReason");
if (m_bRevoked)
throw new IllegalStateException ("This object is already revoked!");
m_bRevoked = true;
m_sRevocationUserID = sRevocationUserID;
m_aRevocationDT = aRevocationDT;
m_sRevocationReason = sRevocationReason;
} | java | {
"resource": ""
} |
q15758 | SnomedCoderService.doc | train | @GET
@Produces(MediaType.TEXT_PLAIN)
public InputStream doc() throws IOException {
//noinspection ConstantConditions
return getClass().getClassLoader().getResource("SnomedCoderService_help.txt").openStream();
} | java | {
"resource": ""
} |
q15759 | SnomedCoderService.mapTextWithOptions | train | @POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
public static Collection<Utterance> mapTextWithOptions(final AnalysisRequest r)
throws IOException, InterruptedException, JAXBException, SQLException, ParserConfigurationException,
SAXException {
System.out.println(r);
// metamap options
final Collection<Option> opts = new ArrayList<>();
final Set<String> optionNames = new HashSet<>();
for (final String o : r.getOptions()) {
final Option opt = MetaMapOptions.strToOpt(o);
if (opt != null) {
optionNames.add(opt.name());
if (!opt.useProcessorDefault()) opts.add(opt);
}
}
// always make sure we have a restrict_to_sources option
if (!optionNames.contains(new RestrictToSources().name())) opts.add(new RestrictToSources());
// tmp files for metamap in/out
final File infile = File.createTempFile("metamap-input-", ".txt");
final File outfile = File.createTempFile("metamap-output-", ".xml");
final String s = r.getText() + (r.getText().endsWith("\n") ? "" : "\n");
final String ascii = MetaMap.decomposeToAscii(URLDecoder.decode(s, "UTF-8"));
Files.write(ascii, infile, Charsets.UTF_8);
// we don't want too much data for a free service
if (infile.length() > MAX_DATA_BYTES) {
throw new WebApplicationException(
Response.status(Responses.NOT_ACCEPTABLE)
.entity("Too much data, currently limited to " + MAX_DATA_BYTES + " bytes.")
.type("text/plain").build()
);
}
// process the data with MetaMap
final MetaMap metaMap = new MetaMap(PUBLIC_MM_DIR, opts);
if (!metaMap.process(infile, outfile)) {
throw new WebApplicationException(Response.status(INTERNAL_SERVER_ERROR)
.entity("Processing failed, aborting.")
.type("text/plain").build());
}
// look up the SNOMED codes from the UMLS CUI code/description combinations returned by MetaMap
final MMOs root = JaxbLoader.loadXml(outfile);
try (final SnomedLookup snomedLookup = new SnomedLookup(DB_PATH)) {
snomedLookup.enrichXml(root);
}
//noinspection ResultOfMethodCallIgnored
infile.delete();
//noinspection ResultOfMethodCallIgnored
outfile.delete();
return destructiveFilter(root);
} | java | {
"resource": ""
} |
q15760 | SnomedCoderService.destructiveFilter | train | private static Collection<Utterance> destructiveFilter(final MMOs root) {
final Collection<Utterance> utterances = new ArrayList<>();
for (final MMO mmo : root.getMMO()) {
for (final Utterance utterance : mmo.getUtterances().getUtterance()) {
// clear candidates to save heaps of bytes
for (final Phrase phrase : utterance.getPhrases().getPhrase()) {
phrase.setCandidates(null);
}
utterances.add(utterance);
}
}
return utterances;
} | java | {
"resource": ""
} |
q15761 | AbstractObjectDeliveryHttpHandler._initialFillSet | train | private static void _initialFillSet (@Nonnull final ICommonsOrderedSet <String> aSet,
@Nullable final String sItemList,
final boolean bUnify)
{
ValueEnforcer.notNull (aSet, "Set");
if (!aSet.isEmpty ())
throw new IllegalArgumentException ("The provided set must be empty, but it is not: " + aSet);
if (StringHelper.hasText (sItemList))
{
// Perform some default replacements to avoid updating all references at
// once before splitting
final String sRealItemList = StringHelper.replaceAll (sItemList,
EXTENSION_MACRO_WEB_DEFAULT,
"js,css,png,jpg,jpeg,gif,eot,svg,ttf,woff,woff2,map");
for (final String sItem : StringHelper.getExploded (',', sRealItemList))
{
String sRealItem = sItem.trim ();
if (bUnify)
sRealItem = getUnifiedItem (sRealItem);
// Add only non-empty items
if (StringHelper.hasText (sRealItem))
aSet.add (sRealItem);
}
}
} | java | {
"resource": ""
} |
q15762 | TextStripper.extractText | train | public List<Page> extractText(InputStream src) throws IOException {
List<Page> pages = Lists.newArrayList();
PdfReader reader = new PdfReader(src);
RenderListener listener = new InternalListener();
PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
pages.add(currentPage = new Page());
PdfDictionary pageDic = reader.getPageN(i);
PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
processor.processContent(ContentByteUtils.getContentBytesForPage(reader, i), resourcesDic);
}
reader.close();
return pages;
} | java | {
"resource": ""
} |
q15763 | CrtAuthClient.createResponse | train | public String createResponse(String challenge)
throws IllegalArgumentException, KeyNotFoundException, ProtocolVersionException {
byte[] decodedChallenge = decode(challenge);
Challenge deserializedChallenge = CrtAuthCodec.deserializeChallenge(decodedChallenge);
if (!deserializedChallenge.getServerName().equals(serverName)) {
throw new IllegalArgumentException(
String.format("Server name mismatch (%s != %s). Possible MITM attack.",
deserializedChallenge.getServerName(), serverName)
);
}
byte[] signature = signer.sign(decodedChallenge, deserializedChallenge.getFingerprint());
return encode(CrtAuthCodec.serialize(new Response(decodedChallenge, signature)));
} | java | {
"resource": ""
} |
q15764 | EkstaziAgent.initSingleCoverageMode | train | private static boolean initSingleCoverageMode(final String runName, Instrumentation instrumentation) {
// Check if run is affected and if not start coverage.
if (Ekstazi.inst().checkIfAffected(runName)) {
Ekstazi.inst().startCollectingDependencies(runName);
// End coverage when VM ends execution.
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
Ekstazi.inst().finishCollectingDependencies(runName);
}
});
return true;
} else {
instrumentation.addTransformer(new RemoveMainCFT());
return false;
}
} | java | {
"resource": ""
} |
q15765 | AbstractHTMLProvider.addMetaElements | train | @OverrideOnDemand
protected void addMetaElements (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope,
@Nonnull final HCHead aHead)
{
final ICommonsList <IMetaElement> aMetaElements = new CommonsArrayList <> ();
{
// add special meta element at the beginning
final IMimeType aMimeType = PhotonHTMLHelper.getMimeType (aRequestScope);
aMetaElements.add (EStandardMetaElement.CONTENT_TYPE.getAsMetaElement (aMimeType.getAsString ()));
}
PhotonMetaElements.getAllRegisteredMetaElementsForGlobal (aMetaElements);
PhotonMetaElements.getAllRegisteredMetaElementsForThisRequest (aMetaElements);
for (final IMetaElement aMetaElement : aMetaElements)
for (final Map.Entry <Locale, String> aEntry : aMetaElement.getContent ())
{
final HCMeta aMeta = new HCMeta ();
if (aMetaElement.isHttpEquiv ())
aMeta.setHttpEquiv (aMetaElement.getName ());
else
aMeta.setName (aMetaElement.getName ());
aMeta.setContent (aEntry.getValue ());
final Locale aContentLocale = aEntry.getKey ();
if (aContentLocale != null && !LocaleHelper.isSpecialLocale (aContentLocale))
aMeta.setLanguage (aContentLocale.toString ());
aHead.metaElements ().add (aMeta);
}
} | java | {
"resource": ""
} |
q15766 | FineUploader5Core.setMaxConnections | train | @Nonnull
public FineUploader5Core setMaxConnections (@Nonnegative final int nMaxConnections)
{
ValueEnforcer.isGT0 (nMaxConnections, "MaxConnections");
m_nCoreMaxConnections = nMaxConnections;
return this;
} | java | {
"resource": ""
} |
q15767 | JSFormatter.outdentAlways | train | @Nonnull
public JSFormatter outdentAlways ()
{
if (m_nIndentLevel == 0)
throw new IllegalStateException ("Nothing left to outdent!");
m_nIndentLevel--;
m_sIndentCache = m_sIndentCache.substring (0, m_nIndentLevel * m_aSettings.getIndent ().length ());
return this;
} | java | {
"resource": ""
} |
q15768 | JSDefinedClass._extends | train | @Nonnull
@CodingStyleguideUnaware
public JSDefinedClass _extends (@Nonnull final AbstractJSClass aSuperClass)
{
m_aSuperClass = ValueEnforcer.notNull (aSuperClass, "SuperClass");
return this;
} | java | {
"resource": ""
} |
q15769 | JSDefinedClass.method | train | @Nonnull
public JSMethod method (@Nonnull @Nonempty final String sName)
{
final JSMethod aMethod = new JSMethod (this, sName);
m_aMethods.add (aMethod);
return aMethod;
} | java | {
"resource": ""
} |
q15770 | BootstrapModal.openModal | train | @Nonnull
public JSPackage openModal (@Nullable final EBootstrapModalOptionBackdrop aBackdrop,
@Nullable final Boolean aKeyboard,
@Nullable final Boolean aFocus,
@Nullable final Boolean aShow,
@Nullable final String sRemotePath)
{
final JSPackage ret = new JSPackage ();
final JSAssocArray aOptions = new JSAssocArray ();
if (aBackdrop != null)
aOptions.add ("backdrop", aBackdrop.getJSExpression ());
if (aFocus != null)
aOptions.add ("focus", aFocus.booleanValue ());
if (aKeyboard != null)
aOptions.add ("keyboard", aKeyboard.booleanValue ());
if (aShow != null)
aOptions.add ("show", aShow.booleanValue ());
ret.add (jsModal ().arg (aOptions));
if (StringHelper.hasText (sRemotePath))
{
// Load content into modal
ret.add (JQuery.idRef (_getContentID ()).load (sRemotePath));
}
return ret;
} | java | {
"resource": ""
} |
q15771 | AbstractWebPageSecurityObjectWithAttributes.onShowSelectedObjectCustomAttrs | train | @Nullable
@OverrideOnDemand
protected ICommonsSet <String> onShowSelectedObjectCustomAttrs (@Nonnull final WPECTYPE aWPEC,
@Nonnull final DATATYPE aSelectedObject,
@Nonnull final Map <String, String> aCustomAttrs,
@Nonnull final BootstrapViewForm aViewForm)
{
return null;
} | java | {
"resource": ""
} |
q15772 | AbstractWebPageSecurityObjectWithAttributes.validateCustomInputParameters | train | @OverrideOnDemand
@Nullable
protected ICommonsMap <String, String> validateCustomInputParameters (@Nonnull final WPECTYPE aWPEC,
@Nullable final DATATYPE aSelectedObject,
@Nonnull final FormErrorList aFormErrors,
@Nonnull final EWebPageFormAction eFormAction)
{
return null;
} | java | {
"resource": ""
} |
q15773 | UserUploadManager.addUploadedFile | train | public void addUploadedFile (@Nonnull @Nonempty final String sFieldName, @Nonnull final TemporaryUserDataObject aUDO)
{
ValueEnforcer.notEmpty (sFieldName, "FieldName");
ValueEnforcer.notNull (aUDO, "UDO");
m_aRWLock.writeLocked ( () -> {
// Remove an eventually existing old UDO with the same filename - avoid
// bloating the list
final TemporaryUserDataObject aOldUDO = m_aMap.remove (sFieldName);
if (aOldUDO != null)
_deleteUDO (aOldUDO);
// Add the new one
m_aMap.put (sFieldName, aUDO);
});
} | java | {
"resource": ""
} |
q15774 | UserUploadManager.confirmUploadedFiles | train | @Nonnull
@ReturnsMutableCopy
public ICommonsOrderedMap <String, UserDataObject> confirmUploadedFiles (@Nullable final String... aFieldNames)
{
final ICommonsOrderedMap <String, UserDataObject> ret = new CommonsLinkedHashMap <> ();
if (aFieldNames != null)
{
m_aRWLock.writeLocked ( () -> {
for (final String sFieldName : aFieldNames)
{
// Remove an eventually existing old UDO
final TemporaryUserDataObject aUDO = m_aMap.remove (sFieldName);
if (aUDO != null)
{
LOGGER.info ("Confirmed uploaded file " + aUDO);
// Convert from temporary to real UDO
ret.put (sFieldName, new UserDataObject (aUDO.getPath ()));
}
}
});
}
return ret;
} | java | {
"resource": ""
} |
q15775 | UserUploadManager.confirmUploadedFile | train | @Nullable
public UserDataObject confirmUploadedFile (@Nullable final String sFieldName)
{
return m_aRWLock.writeLocked ( () -> {
if (StringHelper.hasText (sFieldName))
{
// Remove an eventually existing old UDO
final TemporaryUserDataObject aUDO = m_aMap.remove (sFieldName);
if (aUDO != null)
{
LOGGER.info ("Confirmed uploaded file " + aUDO);
// Convert from temporary to real UDO
return new UserDataObject (aUDO.getPath ());
}
}
return null;
});
} | java | {
"resource": ""
} |
q15776 | UserUploadManager.cancelUploadedFiles | train | @Nonnull
@ReturnsMutableCopy
public ICommonsList <String> cancelUploadedFiles (@Nullable final String... aFieldNames)
{
final ICommonsList <String> ret = new CommonsArrayList <> ();
if (ArrayHelper.isNotEmpty (aFieldNames))
{
m_aRWLock.writeLocked ( () -> {
for (final String sFieldName : aFieldNames)
{
final TemporaryUserDataObject aUDO = m_aMap.remove (sFieldName);
if (aUDO != null)
{
_deleteUDO (aUDO);
ret.add (sFieldName);
}
}
});
}
return ret;
} | java | {
"resource": ""
} |
q15777 | UserUploadManager.getUploadedFile | train | @Nullable
public TemporaryUserDataObject getUploadedFile (@Nullable final String sFieldName)
{
if (StringHelper.hasNoText (sFieldName))
return null;
return m_aRWLock.readLocked ( () -> m_aMap.get (sFieldName));
} | java | {
"resource": ""
} |
q15778 | DefaultBootstrapFormGroupRenderer.modifyFirstControlIfLabelIsPresent | train | @OverrideOnDemand
protected void modifyFirstControlIfLabelIsPresent (@Nonnull final IHCElementWithChildren <?> aLabel,
@Nonnull final IHCControl <?> aFirstControl)
{
// Set the default placeholder (if none is present)
if (aFirstControl instanceof IHCInput <?>)
{
final IHCInput <?> aEdit = (IHCInput <?>) aFirstControl;
final EHCInputType eType = aEdit.getType ();
if (eType != null && eType.hasPlaceholder () && !aEdit.hasPlaceholder ())
aEdit.setPlaceholder (_getPlaceholderText (aLabel));
}
else
if (aFirstControl instanceof IHCTextArea <?>)
{
final IHCTextArea <?> aTextArea = (IHCTextArea <?>) aFirstControl;
if (!aTextArea.hasPlaceholder ())
aTextArea.setPlaceholder (_getPlaceholderText (aLabel));
}
} | java | {
"resource": ""
} |
q15779 | HCChart.getJSUpdateCode | train | @Nonnull
public IHasJSCode getJSUpdateCode (@Nonnull final IJSExpression aJSDataVar)
{
final JSPackage ret = new JSPackage ();
// Cleanup old chart
ret.invoke (JSExpr.ref (getJSChartVar ()), "destroy");
// Use new chart
ret.assign (JSExpr.ref (getJSChartVar ()), new JSDefinedClass ("Chart")._new ()
.arg (JSExpr.ref (getCanvasID ())
.invoke ("getContext")
.arg ("2d"))
.invoke (m_aChart.getJSMethodName ())
.arg (aJSDataVar)
.arg (getJSOptions ()));
return ret;
} | java | {
"resource": ""
} |
q15780 | PhotonJS.unregisterJSIncludeFromThisRequest | train | public static void unregisterJSIncludeFromThisRequest (@Nonnull final IJSPathProvider aJSPathProvider)
{
final JSResourceSet aSet = _getPerRequestSet (false);
if (aSet != null)
aSet.removeItem (aJSPathProvider);
} | java | {
"resource": ""
} |
q15781 | FileUtil.readFile | train | public static byte[] readFile(File file) throws IOException {
// Open file
RandomAccessFile f = new RandomAccessFile(file, "r");
try {
// Get and check length
long longlength = f.length();
int length = (int) longlength;
if (length != longlength) {
throw new IOException("File size >= 2 GB");
}
// Read file and return data
byte[] data = new byte[length];
f.readFully(data);
return data;
} finally {
// Close file
f.close();
}
} | java | {
"resource": ""
} |
q15782 | FileUtil.writeFile | train | public static void writeFile(File file, byte[] bytes) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bytes);
} finally {
if (fos != null) {
fos.close();
}
}
} | java | {
"resource": ""
} |
q15783 | FileUtil.isSecondNewerThanFirst | train | public static boolean isSecondNewerThanFirst(File first, File second) {
boolean isSecondNewerThanFirst = false;
// If file does not exist, it cannot be newer.
if (second.exists()) {
long firstLastModified = first.lastModified();
long secondLastModified = second.lastModified();
// 0L is returned if there was any error, so we check if both last
// modification stamps are != 0L.
if (firstLastModified != 0L && secondLastModified != 0L) {
isSecondNewerThanFirst = secondLastModified > firstLastModified;
}
}
return isSecondNewerThanFirst;
} | java | {
"resource": ""
} |
q15784 | FileUtil.loadBytes | train | public static byte[] loadBytes(URL url) {
byte[] bytes = null;
try {
bytes = loadBytes(url.openStream());
} catch (IOException ex) {
// ex.printStackTrace();
}
return bytes;
} | java | {
"resource": ""
} |
q15785 | WebSiteResourceBundleManager.getResourceBundleOfID | train | @Nullable
public WebSiteResourceBundleSerialized getResourceBundleOfID (@Nullable final String sBundleID)
{
if (StringHelper.hasNoText (sBundleID))
return null;
return m_aRWLock.readLocked ( () -> m_aMapToBundle.get (sBundleID));
} | java | {
"resource": ""
} |
q15786 | WebSiteResourceBundleManager.containsResourceBundleOfID | train | public boolean containsResourceBundleOfID (@Nullable final String sBundleID)
{
if (StringHelper.hasNoText (sBundleID))
return false;
return m_aRWLock.readLocked ( () -> m_aMapToBundle.containsKey (sBundleID));
} | java | {
"resource": ""
} |
q15787 | AbstractMojoInterceptor.throwMojoExecutionException | train | protected static void throwMojoExecutionException(Object mojo, String message, Exception cause) throws Exception {
Class<?> clz = mojo.getClass().getClassLoader().loadClass(MavenNames.MOJO_EXECUTION_EXCEPTION_BIN);
Constructor<?> con = clz.getConstructor(String.class, Exception.class);
Exception ex = (Exception) con.newInstance(message, cause);
throw ex;
} | java | {
"resource": ""
} |
q15788 | AbstractMojoInterceptor.invokeAndGetString | train | protected static String invokeAndGetString(String methodName, Object mojo) throws Exception {
return (String) invokeGetMethod(methodName, mojo);
} | java | {
"resource": ""
} |
q15789 | AbstractMojoInterceptor.invokeAndGetBoolean | train | protected static boolean invokeAndGetBoolean(String methodName, Object mojo) throws Exception {
return (Boolean) invokeGetMethod(methodName, mojo);
} | java | {
"resource": ""
} |
q15790 | AbstractMojoInterceptor.invokeAndGetList | train | @SuppressWarnings("unchecked")
protected static List<String> invokeAndGetList(String methodName, Object mojo) throws Exception {
return (List<String>) invokeGetMethod(methodName, mojo);
} | java | {
"resource": ""
} |
q15791 | AbstractMojoInterceptor.setField | train | protected static void setField(String fieldName, Object mojo, Object value) throws Exception {
Field field = null;
try {
field = mojo.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException ex) {
// Ignore exception and try superclass.
field = mojo.getClass().getSuperclass().getDeclaredField(fieldName);
}
field.setAccessible(true);
field.set(mojo, value);
} | java | {
"resource": ""
} |
q15792 | AbstractMojoInterceptor.getField | train | protected static Object getField(String fieldName, Object mojo) throws Exception {
Field field = null;
try {
field = mojo.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException ex) {
// Ignore exception and try superclass.
field = mojo.getClass().getSuperclass().getDeclaredField(fieldName);
}
field.setAccessible(true);
return field.get(mojo);
} | java | {
"resource": ""
} |
q15793 | AgentLoader.loadAgent | train | public static boolean loadAgent(URL agentJarURL) throws Exception {
File toolsJarFile = findToolsJar();
Class<?> vmClass = null;
if (toolsJarFile == null || !toolsJarFile.exists()) {
// likely Java 9+ (when tools.jar is not available). Java
// 9 also requires that
// -Djvm.options=jdk.attach.allowAttachSelf=true is set.
vmClass = ClassLoader.getSystemClassLoader().loadClass("com.sun.tools.attach.VirtualMachine");
} else {
vmClass = loadVirtualMachine(toolsJarFile);
}
if (vmClass == null) {
return false;
}
attachAgent(vmClass, agentJarURL);
return true;
} | java | {
"resource": ""
} |
q15794 | AgentLoader.attachAgent | train | private static void attachAgent(Class<?> vmClass, URL agentJarURL) throws Exception {
String pid = getPID();
String agentAbsolutePath = new File(agentJarURL.toURI().getSchemeSpecificPart()).getAbsolutePath();
Object vm = getAttachMethod(vmClass).invoke(null, new Object[] { pid });
getLoadAgentMethod(vmClass).invoke(vm, new Object[] { agentAbsolutePath });
getDetachMethod(vmClass).invoke(vm);
} | java | {
"resource": ""
} |
q15795 | AgentLoader.getAttachMethod | train | private static Method getAttachMethod(Class<?> vmClass) throws SecurityException, NoSuchMethodException {
return vmClass.getMethod("attach", new Class<?>[] { String.class });
} | java | {
"resource": ""
} |
q15796 | AgentLoader.getLoadAgentMethod | train | private static Method getLoadAgentMethod(Class<?> vmClass) throws SecurityException, NoSuchMethodException {
return vmClass.getMethod("loadAgent", new Class[] { String.class });
} | java | {
"resource": ""
} |
q15797 | AgentLoader.getPID | train | private static String getPID() {
String vmName = ManagementFactory.getRuntimeMXBean().getName();
return vmName.substring(0, vmName.indexOf("@"));
} | java | {
"resource": ""
} |
q15798 | AgentLoader.findToolsJar | train | private static File findToolsJar() {
String javaHome = System.getProperty("java.home");
File javaHomeFile = new File(javaHome);
File toolsJarFile = new File(javaHomeFile, "lib" + File.separator + TOOLS_JAR_NAME);
if (!toolsJarFile.exists()) {
toolsJarFile = new File(System.getenv("java_home"), "lib" + File.separator + TOOLS_JAR_NAME);
}
if (!toolsJarFile.exists() && javaHomeFile.getAbsolutePath().endsWith(File.separator + "jre")) {
javaHomeFile = javaHomeFile.getParentFile();
toolsJarFile = new File(javaHomeFile, "lib" + File.separator + TOOLS_JAR_NAME);
}
if (!toolsJarFile.exists() && isMac() && javaHomeFile.getAbsolutePath().endsWith(File.separator + "Home")) {
javaHomeFile = javaHomeFile.getParentFile();
toolsJarFile = new File(javaHomeFile, "Classes" + File.separator + CLASSES_JAR_NAME);
}
return toolsJarFile;
} | java | {
"resource": ""
} |
q15799 | JavaDocParserImpl.lookahead | train | public Token lookahead() {
Token current = token;
if (current.next == null) {
current.next = token_source.getNextToken();
}
return current.next;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.