code
stringlengths
73
34.1k
label
stringclasses
1 value
public void runBatchFile(File batchFile) throws IOException { final BufferedReader reader = new BufferedReader(new FileReader(batchFile)); try { doLines(0, new LineReader() { @Override public String getNextLine(String prompt) throws IOException { return reader.readLine(); } }, true); } fina...
java
private void doLines(int levelC, LineReader lineReader, boolean batch) throws IOException { if (levelC > 20) { System.out.print("Ignoring possible recursion after including 20 times"); return; } while (true) { String line = lineReader.getNextLine(DEFAULT_PROMPT); if (line == null) { break; } ...
java
private void runScript(String alias, int levelC) throws IOException { String scriptFile = alias; InputStream stream; try { stream = getInputStream(scriptFile); if (stream == null) { System.out.println("Error. Script file is not found: " + scriptFile); return; } } catch (IOException e) { Sys...
java
private MBeanInfo buildMbeanInfo(JmxAttributeFieldInfo[] attributeFieldInfos, JmxAttributeMethodInfo[] attributeMethodInfos, JmxOperationInfo[] operationInfos, boolean ignoreErrors) { // NOTE: setup the maps that track previous class configuration Map<String, JmxAttributeFieldInfo> attributeFieldInfoMap = null;...
java
private List<MBeanOperationInfo> discoverOperations(Map<String, JmxOperationInfo> attributeOperationInfoMap) { Set<MethodSignature> methodSignatureSet = new HashSet<MethodSignature>(); List<MBeanOperationInfo> operations = new ArrayList<MBeanOperationInfo>(operationMethodMap.size()); for (Class<?> clazz = target....
java
private MBeanParameterInfo[] buildOperationParameterInfo(Method method, JmxOperationInfo operationInfo) { Class<?>[] types = method.getParameterTypes(); MBeanParameterInfo[] parameterInfos = new MBeanParameterInfo[types.length]; String[] parameterNames = operationInfo.getParameterNames(); String[] parameterDesc...
java
public static ObjectName makeObjectName(JmxResource jmxResource, JmxSelfNaming selfNamingObj) { String domainName = selfNamingObj.getJmxDomainName(); if (domainName == null) { if (jmxResource != null) { domainName = jmxResource.domainName(); } if (isEmpty(domainName)) { throw new IllegalArgumentExc...
java
public static ObjectName makeObjectName(JmxSelfNaming selfNamingObj) { JmxResource jmxResource = selfNamingObj.getClass().getAnnotation(JmxResource.class); return makeObjectName(jmxResource, selfNamingObj); }
java
public static ObjectName makeObjectName(JmxResource jmxResource, Object obj) { String domainName = jmxResource.domainName(); if (isEmpty(domainName)) { throw new IllegalArgumentException( "Could not create ObjectName because domain name not specified in @JmxResource"); } String beanName = getBeanName(jm...
java
public static ObjectName makeObjectName(String domainName, String beanName, String[] folderNameStrings) { return makeObjectName(domainName, beanName, null, folderNameStrings); }
java
void doMain(String[] args, boolean throwOnError) throws Exception { if (args.length == 0) { usage(throwOnError, "no arguments specified"); return; } else if (args.length > 2) { usage(throwOnError, "improper number of arguments:" + Arrays.toString(args)); return; } // check for --usage or --help i...
java
public String[] getBeanDomains() throws JMException { checkClientConnected(); try { return mbeanConn.getDomains(); } catch (IOException e) { throw createJmException("Problems getting jmx domains: " + e, e); } }
java
public MBeanAttributeInfo getAttributeInfo(ObjectName name, String attrName) throws JMException { checkClientConnected(); return getAttrInfo(name, attrName); }
java
public String getAttributeString(String domain, String beanName, String attributeName) throws Exception { return getAttributeString(ObjectNameUtil.makeObjectName(domain, beanName), attributeName); }
java
public String getAttributeString(ObjectName name, String attributeName) throws Exception { Object bean = getAttribute(name, attributeName); if (bean == null) { return null; } else { return ClientUtils.valueToString(bean); } }
java
public void setAttribute(ObjectName name, String attrName, Object value) throws Exception { checkClientConnected(); Attribute attribute = new Attribute(attrName, value); mbeanConn.setAttribute(name, attribute); }
java
public void stop() throws Exception { if (server != null) { server.setStopTimeout(100); server.stop(); server = null; } }
java
public static String formatException(IThrowableProxy error) { String ex = ""; ex += formatTopLevelError(error); ex += formatStackTraceElements(error.getStackTraceElementProxyArray()); IThrowableProxy cause = error.getCause(); ex += DELIMITER; while (cause != null) { ex += formatTopLevelError(cause)...
java
public static Token generate(final Random random, final Key key, final String plainText) { return generate(random, key, plainText.getBytes(charset)); }
java
public static Token generate(final Random random, final Key key, final byte[] payload) { final IvParameterSpec initializationVector = generateInitializationVector(random); final byte[] cipherText = key.encrypt(payload, initializationVector); final Instant timestamp = Instant.now(); final...
java
@SuppressWarnings("PMD.LawOfDemeter") public <T> T validateAndDecrypt(final Key key, final Validator<T> validator) { return validator.validateAndDecrypt(key, this); }
java
@SuppressWarnings("PMD.LawOfDemeter") public <T> T validateAndDecrypt(final Collection<? extends Key> keys, final Validator<T> validator) { return validator.validateAndDecrypt(keys, this); }
java
@SuppressWarnings("PMD.LawOfDemeter") public void writeTo(final OutputStream outputStream) throws IOException { try (DataOutputStream dataStream = new DataOutputStream(outputStream)) { dataStream.writeByte(getVersion()); dataStream.writeLong(getTimestamp().getEpochSecond()); ...
java
public boolean isValidSignature(final Key key) { final byte[] computedHmac = key.sign(getVersion(), getTimestamp(), getInitializationVector(), getCipherText()); return Arrays.equals(getHmac(), computedHmac); }
java
boolean checkValidUUID( String uuid){ if("".equals(uuid)) return false; try { UUID u = UUID.fromString(uuid); }catch(IllegalArgumentException e){ return false; } return true; }
java
String getEnvVar( String key) { String envVal = System.getenv(key); return envVal != null ? envVal : ""; }
java
boolean checkCredentials() { if(!httpPut) { if (token.equals(CONFIG_TOKEN) || token.equals("")) { //Check if set in an environment variable, used with PaaS providers String envToken = getEnvVar( CONFIG_TOKEN); if (envToken == ""){ dbg(INVALID_TOKEN); return false; } this.setT...
java
void dbg(String msg) { if (debug ) { if (!msg.endsWith(LINE_SEP)) { System.err.println(LE + msg); } else { System.err.print(LE + msg); } } }
java
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition") public Token getAuthorizationToken(final ContainerRequest request) { String authorizationString = request.getHeaderString("Authorization"); if (authorizationString != null && !"".equals(authorizationString)) { authorizationString = auth...
java
public Token getXAuthorizationToken(final ContainerRequest request) { final String xAuthorizationString = request.getHeaderString("X-Authorization"); if (xAuthorizationString != null && !"".equals(xAuthorizationString)) { return Token.fromString(xAuthorizationString.trim()); } ...
java
protected void seed() { if (!seeded.get()) { synchronized (random) { if (!seeded.get()) { getLogger().debug("Seeding random number generator"); final GenerateRandomRequest request = new GenerateRandomRequest(); request.setNu...
java
public ByteBuffer getSecretStage(final String secretId, final Stage stage) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionStage(stage.getAwsName()); final GetSecretValueResult...
java
public static Key generateKey(final Random random) { final byte[] signingKey = new byte[signingKeyBytes]; random.nextBytes(signingKey); final byte[] encryptionKey = new byte[encryptionKeyBytes]; random.nextBytes(encryptionKey); return new Key(signingKey, encryptionKey); }
java
public byte[] sign(final byte version, final Instant timestamp, final IvParameterSpec initializationVector, final byte[] cipherText) { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream( getTokenPrefixBytes() + cipherText.length)) { return sign(version, tim...
java
@SuppressWarnings("PMD.LawOfDemeter") public byte[] encrypt(final byte[] payload, final IvParameterSpec initializationVector) { final SecretKeySpec encryptionKeySpec = getEncryptionKeySpec(); try { final Cipher cipher = Cipher.getInstance(cipherTransformation); cipher.init(EN...
java
@SuppressWarnings("PMD.LawOfDemeter") public byte[] decrypt(final byte[] cipherText, final IvParameterSpec initializationVector) { try { final Cipher cipher = Cipher.getInstance(getCipherTransformation()); cipher.init(DECRYPT_MODE, getEncryptionKeySpec(), initializationVector); ...
java
public void writeTo(final OutputStream outputStream) throws IOException { outputStream.write(getSigningKey()); outputStream.write(getEncryptionKey()); }
java
public static void renderJQueryPluginCall(final String elementId, final String pluginFunctionCall, final ResponseWriter writer, final UIComponent uiComponent) throws IOException { final String jsCall = createJQueryPluginCall(elementId, pluginFunctionCall); ...
java
@Override public void processEvent(SystemEvent event) throws AbortProcessingException { final UIViewRoot source = (UIViewRoot) event.getSource(); final FacesContext context = FacesContext.getCurrentInstance(); final WebXmlParameters webXmlParameters = new WebXmlParameters(context.getExterna...
java
private void handleCompressedResources(final FacesContext context, final boolean provideJQuery, final boolean provideBootstrap, final List<UIComponent> resources, ...
java
private void removeAllResourcesFromViewRoot(final FacesContext context, final List<UIComponent> resources, final UIViewRoot view) { final Iterator<UIComponent> it = resources.iterator(); while (it.hasNext())...
java
private void handleConfigurableResources(FacesContext context, boolean provideJQuery, boolean provideBootstrap, List<UIComponent> resources, ...
java
private void addGeneratedJSResource(FacesContext context, String resourceName, String library, UIViewRoot view) { addGeneratedResource(context, resourceName, "javax.faces.resource.Script", library, view); }
java
private void addGeneratedCSSResource(FacesContext context, String resourceName, UIViewRoot view) { addGeneratedResource(context, resourceName, "javax.faces.resource.Stylesheet", "butterfaces-dist-css", view); }
java
private void addGeneratedResource(FacesContext context, String resourceName, String rendererType, String value, UIViewRoot view) { final UIOutput resource = new UIOutput(); resource.getAttributes().put("name", resourceName); resource.setRendererType(renderer...
java
private void removeResource(FacesContext context, UIComponent resource, UIViewRoot view) { view.removeComponentResource(context, resource, HEAD); view.removeComponentResource(context, resource, TARGET); }
java
public int renderNodes(final StringBuilder stringBuilder, final List<Node> nodes, final int index, final List<String> mustacheKeys, final Map<Integer, Node> cachedNodes) { int newIndex = index; f...
java
public void clearMetaInfo(FacesContext context, UIComponent table) { context.getAttributes().remove(createKey(table)); }
java
protected void renderBooleanValue(final UIComponent component, final ResponseWriter writer, final String attributeName) throws IOException { if (component.getAttributes().get(attributeName) != null && Boolean.valueOf(component.getAttrib...
java
protected void renderStringValue(final UIComponent component, final ResponseWriter writer, final String attributeName) throws IOException { if (component.getAttributes().get(attributeName) != null && StringUtils.isNotEmpty...
java
protected void renderStringValue(final UIComponent component, final ResponseWriter writer, final String attributeName, final String matchingValue) throws IOException { if (component.getAttributes().get...
java
public int get(String url) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); try(Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { ...
java
private String constructAdditionalNamespacesString(List<AdditionalNamespace> additionalNamespaceList) { String result = ""; if (additionalNamespaceList.contains(AdditionalNamespace.IMAGE)) { result += " xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\" "; } if (...
java
public I addPage(WebPage webPage) { beforeAddPageEvent(webPage); urls.put(baseUrl + webPage.constructName(), webPage); return getThis(); }
java
public I addPage(StringSupplierWithException<String> supplier) { try { addPage(supplier.get()); } catch (Exception e) { sneakyThrow(e); } return getThis(); }
java
public I run(RunnableWithException runnable) { try { runnable.run(); } catch (Exception e) { sneakyThrow(e); } return getThis(); }
java
public byte[] toGzipByteArray() { String sitemap = this.toString(); ByteArrayInputStream inputStream = new ByteArrayInputStream(sitemap.getBytes(StandardCharsets.UTF_8)); ByteArrayOutputStream outputStream = gzipIt(inputStream); return outputStream.toByteArray(); }
java
@Deprecated public void saveSitemap(File file, String[] sitemap) throws IOException { try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { for (String string : sitemap) { writer.write(string); } } }
java
public void toFile(File file) throws IOException { String[] sitemap = toStringArray(); try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { for (String string : sitemap) { writer.write(string); } } }
java
protected String escapeXmlSpecialCharacters(String url) { // https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents return url .replace("&", "&amp;") // must be escaped first!!! .replace("\"", "&quot;") .replace("'", "&apos;") .replace("<", "&lt;") .repl...
java
public T defaultPriority(Double priority) { if (priority < 0.0 || priority > 1.0) { throw new InvalidPriorityException("Priority must be between 0 and 1.0"); } defaultPriority = priority; return getThis(); }
java
@Override public String[] toStringArray() { ArrayList<String> out = new ArrayList<>(); out.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); out.add("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"); ArrayList<WebPage> values = new ArrayList<>(urls.values()); Collections.sort(value...
java
@Nonnull public static ValidationSource create (@Nullable final String sSystemID, @Nonnull final Node aNode) { ValueEnforcer.notNull (aNode, "Node"); // Use the owner Document as fixed node return new ValidationSource (sSystemID, XMLHelper.getOwnerDocument (aNode), false); }
java
@Nonnull public static ValidationSource createXMLSource (@Nonnull final IReadableResource aResource) { // Read on demand only return new ValidationSource (aResource.getPath (), () -> DOMReader.readXMLDOM (aResource), false) { @Override @Nonnull public Source getAsTransformSource () ...
java
public static void initUBL20 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL20NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL20Doc...
java
public static void initUBL21 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL21NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL21Doc...
java
public static void initUBL22 (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL22NamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final EUBL22Doc...
java
public static void initSimplerInvoicing (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (UBL21NamespaceContext.getInstance ()); // SimplerInvoicing is self-contained final boo...
java
@Nonnull public <T extends IValidationExecutorSet> T registerValidationExecutorSet (@Nonnull final T aVES) { ValueEnforcer.notNull (aVES, "VES"); final VESID aKey = aVES.getID (); m_aRWLock.writeLocked ( () -> { if (m_aMap.containsKey (aKey)) throw new IllegalStateException ("Another vali...
java
@Nullable public IValidationExecutorSet getOfID (@Nullable final VESID aID) { if (aID == null) return null; return m_aRWLock.readLocked ( () -> m_aMap.get (aID)); }
java
@SuppressWarnings ("deprecation") public static void initStandard (@Nonnull final ValidationExecutorSetRegistry aRegistry) { // For better error messages LocationBeautifierSPI.addMappings (UBL21NamespaceContext.getInstance ()); PeppolValidation350.init (aRegistry); PeppolValidation360.init (aRegist...
java
public static void initCIID16B (@Nonnull final ValidationExecutorSetRegistry aRegistry) { ValueEnforcer.notNull (aRegistry, "Registry"); // For better error messages LocationBeautifierSPI.addMappings (CIID16BNamespaceContext.getInstance ()); final boolean bNotDeprecated = false; for (final ECIID...
java
@Nonnull public final ValidationExecutionManager addExecutors (@Nullable final IValidationExecutor... aExecutors) { if (aExecutors != null) for (final IValidationExecutor aExecutor : aExecutors) addExecutor (aExecutor); return this; }
java
@Nonnull public ValidationResultList executeValidation (@Nonnull final IValidationSource aSource) { return executeValidation (aSource, (Locale) null); }
java
@Nonnull public static ValidationExecutorSet createDerived (@Nonnull final IValidationExecutorSet aBaseVES, @Nonnull final VESID aID, @Nonnull @Nonempty final String sDisplayName, ...
java
@Nonnegative public int getAllCount (@Nullable final Predicate <? super IError> aFilter) { int ret = 0; for (final ValidationResult aItem : this) ret += aItem.getErrorList ().getCount (aFilter); return ret; }
java
public void forEachFlattened (@Nonnull final Consumer <? super IError> aConsumer) { for (final ValidationResult aItem : this) aItem.getErrorList ().forEach (aConsumer); }
java
public static String md5Hex(final String input) { if (input == null) { throw new NullPointerException("String is null"); } MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // this should never happen throw...
java
private static synchronized void startup() { try { CONFIG = ApiConfigurations.fromProperties(); String clientName = ApiClients.getApiClient(LogManager.class, "/stackify-api-common.properties", "stackify-api-common"); LOG_APPENDER = new LogAppender<LogEvent>(clientName, new LogEventAdapter(CONFIG.getEnvD...
java
public static synchronized void shutdown() { if (LOG_APPENDER != null) { try { LOG_APPENDER.close(); } catch (Throwable t) { LOGGER.error("Exception stopping Stackify Log API service", t); } } }
java
public boolean errorShouldBeSent(final StackifyError error) { if (error == null) { throw new NullPointerException("StackifyError is null"); } boolean shouldBeProcessed = false; long epochMinute = getUnixEpochMinutes(); synchronized (errorCounter) { // increment the counter ...
java
public static void putTransactionId(final String transactionId) { if ((transactionId != null) && (0 < transactionId.length())) { MDC.put(TRANSACTION_ID, transactionId); } }
java
public static void putUser(final String user) { if ((user != null) && (0 < user.length())) { MDC.put(USER, user); } }
java
public static void putWebRequest(final WebRequestDetail webRequest) { if (webRequest != null) { try { String value = JSON.writeValueAsString(webRequest); MDC.put(WEB_REQUEST, value); } catch (Throwable t) { // do nothing } } }
java
public void update(final int numSent) { // Reset the last HTTP error lastHttpError = 0; // adjust the schedule delay based on the number of messages sent in the last iteration if (100 <= numSent) { // messages are coming in quickly so decrease our delay // minimum delay is 1 second scheduleDelay ...
java
public static List<Throwable> getCausalChain(final Throwable throwable) { if (throwable == null) { throw new NullPointerException("Throwable is null"); } List<Throwable> causes = new ArrayList<Throwable>(); causes.add(throwable); Throwable cause = throwable.getCause(); while ((cause != null) && ...
java
public static ErrorItem toErrorItem(final String logMessage, final Throwable t) { // get a flat list of the throwable and the causal chain List<Throwable> throwables = Throwables.getCausalChain(t); // create and populate builders for all throwables List<ErrorItem.Builder> builders = new ArrayList<Erro...
java
private static ErrorItem.Builder toErrorItemBuilderWithoutCause(final String logMessage, final Throwable t) { ErrorItem.Builder builder = ErrorItem.newBuilder(); builder.message(toErrorItemMessage(logMessage, t.getMessage())); builder.errorType(t.getClass().getCanonicalName()); List<TraceFrame> stackFrames =...
java
private static String toErrorItemMessage(final String logMessage, final String throwableMessage) { StringBuilder sb = new StringBuilder(); if ((throwableMessage != null) && (!throwableMessage.isEmpty())) { sb.append(throwableMessage); if ((logMessage != null) && (!logMessage.isEmpty())) { sb.a...
java
public static Map<String, String> fromProperties(final Properties props) { Map<String, String> propMap = new HashMap<String, String>(); for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); propMap.put(key, props.getProperty(key)); } return C...
java
private void executeMask(final LogMsgGroup group) { if (masker != null) { if (group.getMsgs().size() > 0) { for (LogMsg logMsg : group.getMsgs()) { if (logMsg.getEx() != null) { executeMask(logMsg.getEx().getError()); } logMsg.setData(masker.mask(logMsg.getData())); logMsg.setMsg(mask...
java
public int send(final LogMsgGroup group) throws IOException { Preconditions.checkNotNull(group); executeMask(group); executeSkipJsonTag(group); HttpClient httpClient = new HttpClient(apiConfig); // retransmit any logs on the resend queue resendQueue.drain(httpClient, LOG_SAVE_PATH, true); // convert ...
java
public static EnvironmentDetail getEnvironmentDetail(final String application, final String environment) { // lookup the host name String hostName = getHostName(); // lookup the current path String currentPath = System.getProperty("user.dir"); // build the environment details EnvironmentDeta...
java
public static void queueMessage(final String level, final String message) { try { LogAppender<LogEvent> appender = LogManager.getAppender(); if (appender != null) { LogEvent.Builder builder = LogEvent.newBuilder(); builder.level(level); builder.message(message); if ((level != null) && ("ER...
java
public static String getApiClient(final Class<?> apiClass, final String fileName, final String defaultClientName) { InputStream propertiesStream = null; try { propertiesStream = apiClass.getResourceAsStream(fileName); if (propertiesStream != null) { Properties props = new Properties(); pr...
java
public static String getUniqueKey(final ErrorItem errorItem) { if (errorItem == null) { throw new NullPointerException("ErrorItem is null"); } String type = errorItem.getErrorType(); String typeCode = errorItem.getErrorTypeCode(); String method = errorItem.getSourceMethod(); String uniqueKey...
java
public int incrementCounter(final StackifyError error, long epochMinute) { if (error == null) { throw new NullPointerException("StackifyError is null"); } ErrorItem baseError = getBaseError(error); String uniqueKey = getUniqueKey(baseError); // get the counter for this error int...
java
public void purgeCounters(final long epochMinute) { for (Iterator<Map.Entry<String, MinuteCounter>> it = errorCounter.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String, MinuteCounter> entry = it.next(); if (entry.getValue().getEpochMinute() < epochMinute) { it.remove(); ...
java
public static TraceFrame toTraceFrame(final StackTraceElement element) { TraceFrame.Builder builder = TraceFrame.newBuilder(); builder.codeFileName(element.getFileName()); if (0 < element.getLineNumber()) { builder.lineNum(element.getLineNumber()); } builder.method(element.getClassName() + "." + elem...
java
public void offer(final byte[] request, final HttpException e) { if (!e.isClientError()) { resendQueue.offer(new HttpResendQueueItem(request)); } }
java