@Override public void destroy() { super.destroy(); try { expireFuture.cancel(true); } catch (Throwable t) { LOGGER.warn(t.getMessage(), t); } try { for (Notifier notifier : notifiers.values()) { notifier.shutdown(); } } catch (Throwable t) { LOGGER.warn(t.getMessage(), t); } for (Map.Entry<String, JedisPool> entry : jedisPools.entrySet()) { JedisPool jedisPool = entry.getValue(); try { jedisPool.destroy(); } catch (Throwable t) { LOGGER.warn( "Failed to destroy the redis registry client. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); } } }
private static void assertExceptionOccurred( boolean shouldOccur, AbstractExceptionCase exceptionCase, String expectedErrorMsg) throws Throwable { boolean wasThrown = false; try { exceptionCase.tryClosure(); } catch (Throwable e) { if (shouldOccur) { wasThrown = true; final String errorMessage = exceptionCase.getAssertionErrorMessage(); assertEquals(errorMessage, exceptionCase.getExpectedExceptionClass(), e.getClass()); if (expectedErrorMsg != null) { assertEquals("Compare error messages", expectedErrorMsg, e.getMessage()); } } else if (exceptionCase.getExpectedExceptionClass().equals(e.getClass())) { wasThrown = true; System.out.println(""); e.printStackTrace(System.out); fail("Exception isn't expected here. Exception message: " + e.getMessage()); } else { throw e; } } finally { if (shouldOccur && !wasThrown) { fail(exceptionCase.getAssertionErrorMessage()); } } }
@Test public void testConnectionResetByHttpClientUtils() throws IOException { testConnectionResetCount = 0; httpClientUtils = new HttpClientUtils(); httpClientUtils.initHttpClient(); Logger.info(this, "-------------- HttpClient initialized -------------"); String resp = null; try { resp = httpClientUtils.get("http://localhost:65532/soso"); } catch (IOException e) { Throwable ee = ExceptionUtils.getRootCause(e); if (ee == null) { ee = e; } Logger.error(this, "", ee); Assert.assertNotSame(NoHttpResponseException.class, ee.getClass()); Assert.assertSame(SocketException.class, ee.getClass()); Assert.assertTrue( "Connection reset".equals(ee.getMessage()) || "Socket closed".equals(ee.getMessage()) || "Unexpected end of file from server".equals(ee.getMessage())); } finally { Logger.info( this, "resp[HttpURLConnection]-[" + testConnectionResetCount + "]=========[" + resp + "]========="); } Assert.assertEquals(1, testConnectionResetCount); }
/** * 运行时,添加JVM参数“-Dsun.net.http.retryPost=false”,可阻止自动重连。 * * @see 'http://www.coderanch.com/t/490463/sockets/java/Timeout-retry-URLHTTPRequest' */ @Test public void testConnectionResetByHttpURLConnection() throws IOException { testConnectionResetCount = 0; String resp = null; try { HttpURLConnection conn = (HttpURLConnection) new URL("http://localhost:65532/soso").openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.getOutputStream().write("username".getBytes()); resp = conn.getResponseCode() + ""; } catch (IOException e) { Throwable ee = ExceptionUtils.getRootCause(e); if (ee == null) { ee = e; } Logger.error(this, "", ee); Assert.assertNotSame(NoHttpResponseException.class, ee.getClass()); Assert.assertSame(SocketException.class, ee.getClass()); Assert.assertTrue( "Connection reset".equals(ee.getMessage()) || "Socket closed".equals(ee.getMessage()) || "Unexpected end of file from server".equals(ee.getMessage())); } finally { Logger.info( this, "resp[HttpURLConnection]-[" + testConnectionResetCount + "]=========[" + resp + "]========="); } Assert.assertEquals(2, testConnectionResetCount); }
/** * Returns the set of nodes for the project * * @return an instance of {@link INodeSet} */ @Override public INodeSet getNodeSet() { // iterate through sources, and add nodes final NodeSetMerge list = getNodeSetMerge(); Map<String, Exception> exceptions = Collections.synchronizedMap(new HashMap<String, Exception>()); int index = 1; Set<String> validSources = new HashSet<>(); for (final ResourceModelSource nodesSource : getResourceModelSources()) { try { INodeSet nodes = nodesSource.getNodes(); if (null == nodes) { logger.warn("Empty nodes result from [" + nodesSource.toString() + "]"); } else { list.addNodeSet(nodes); } boolean hasErrors = false; if (nodesSource instanceof ResourceModelSourceErrors) { ResourceModelSourceErrors nodeerrors = (ResourceModelSourceErrors) nodesSource; List<String> modelSourceErrors = nodeerrors.getModelSourceErrors(); if (modelSourceErrors != null && modelSourceErrors.size() > 0) { hasErrors = true; logger.error( "Some errors getting nodes from [" + nodesSource.toString() + "]: " + modelSourceErrors); exceptions.put( index + ".source", new ResourceModelSourceException( TextUtils.join( modelSourceErrors.toArray(new String[modelSourceErrors.size()]), ';'))); } } if (!hasErrors) { validSources.add(index + ".source"); } } catch (ResourceModelSourceException | RuntimeException e) { logger.error("Cannot get nodes from [" + nodesSource.toString() + "]: " + e.getMessage()); logger.debug( "Cannot get nodes from [" + nodesSource.toString() + "]: " + e.getMessage(), e); exceptions.put(index + ".source", new ResourceModelSourceException(e.getMessage(), e)); } catch (Throwable e) { logger.error("Cannot get nodes from [" + nodesSource.toString() + "]: " + e.getMessage()); logger.debug( "Cannot get nodes from [" + nodesSource.toString() + "]: " + e.getMessage(), e); exceptions.put(index + ".source", new ResourceModelSourceException(e.getMessage())); } index++; } synchronized (nodesSourceExceptions) { nodesSourceExceptions.putAll(exceptions); for (String validSource : validSources) { nodesSourceExceptions.remove(validSource); } } return list; }
private void finishBuild(Throwable error, boolean hadBuildErrors, boolean markedUptodateFiles) { CmdlineRemoteProto.Message lastMessage = null; try { if (error != null) { Throwable cause = error.getCause(); if (cause == null) { cause = error; } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream stream = new PrintStream(out); try { cause.printStackTrace(stream); } finally { stream.close(); } final StringBuilder messageText = new StringBuilder(); messageText .append("Internal error: (") .append(cause.getClass().getName()) .append(") ") .append(cause.getMessage()); final String trace = out.toString(); if (!trace.isEmpty()) { messageText.append("\n").append(trace); } lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createFailure(messageText.toString(), cause)); } else { CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.SUCCESS; if (myCanceled) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED; } else if (hadBuildErrors) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.ERRORS; } else if (!markedUptodateFiles) { status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.UP_TO_DATE; } lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createBuildCompletedEvent("build completed", status)); } } catch (Throwable e) { lastMessage = CmdlineProtoUtil.toMessage( mySessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e)); } finally { try { Channels.write(myChannel, lastMessage).await(); } catch (InterruptedException e) { LOG.info(e); } } }
public void run() { final Connection conn = packet.getConn(); final ClientEndpoint endpoint = getEndpoint(conn); ClientRequest request = null; try { final Data data = packet.getData(); request = (ClientRequest) serializationService.toObject(data); if (endpoint.isAuthenticated() || request instanceof AuthenticationRequest) { request.setEndpoint(endpoint); final String serviceName = request.getServiceName(); if (serviceName != null) { final Object service = nodeEngine.getService(serviceName); if (service == null) { if (nodeEngine.isActive()) { throw new IllegalArgumentException( "No service registered with name: " + serviceName); } throw new HazelcastInstanceNotActiveException(); } request.setService(service); } request.setClientEngine(ClientEngineImpl.this); final SecurityContext securityContext = getSecurityContext(); if (securityContext != null && request instanceof SecureRequest) { final Permission permission = ((SecureRequest) request).getRequiredPermission(); if (permission != null) { securityContext.checkPermission(endpoint.getSubject(), permission); } } request.process(); } else { Exception exception; if (nodeEngine.isActive()) { String message = "Client " + conn + " must authenticate before any operation."; logger.severe(message); exception = new AuthenticationException(message); } else { exception = new HazelcastInstanceNotActiveException(); } sendResponse(endpoint, exception); removeEndpoint(conn); } } catch (Throwable e) { final Level level = nodeEngine.isActive() ? Level.SEVERE : Level.FINEST; String message = request != null ? "While executing request: " + request + " -> " + e.getMessage() : e.getMessage(); logger.log(level, message, e); sendResponse(endpoint, e); } }
private ArithmeticException exception(int ofs, String txt, Throwable thr) { return new ArithmeticException( txt + " at offset " + ofs + " in expression \"" + expression + "\"" + " (Cause: " + (thr.getMessage() != null ? thr.getMessage() : thr.toString()) + ")"); }
private void throwRootCause(String tagName, String tagNamespace, int lineNumber, Throwable e) { Throwable cause = GrailsExceptionResolver.getRootCause(e); if (cause instanceof GrailsTagException) { // catch and rethrow with context throw new GrailsTagException(cause.getMessage(), getGroovyPageFileName(), lineNumber); } else { throw new GrailsTagException( "Error executing tag <" + tagNamespace + ":" + tagName + ">: " + e.getMessage(), e, getGroovyPageFileName(), lineNumber); } }
/** * Method called to create a "default instance" of the bean, currently only needed for obtaining * default field values which may be used for suppressing serialization of fields that have "not * changed". * * @param fixAccess If true, method is allowed to fix access to the default constructor (to be * able to call non-public constructor); if false, has to use constructor as is. * @return Instance of class represented by this descriptor, if suitable default constructor was * found; null otherwise. */ public Object instantiateBean(boolean fixAccess) { AnnotatedConstructor ac = _classInfo.getDefaultConstructor(); if (ac == null) { return null; } if (fixAccess) { ac.fixAccess(); } try { return ac.getAnnotated().newInstance(); } catch (Exception e) { Throwable t = e; while (t.getCause() != null) { t = t.getCause(); } if (t instanceof Error) throw (Error) t; if (t instanceof RuntimeException) throw (RuntimeException) t; throw new IllegalArgumentException( "Failed to instantiate bean of type " + _classInfo.getAnnotated().getName() + ": (" + t.getClass().getName() + ") " + t.getMessage(), t); } }
public String getAlternativeISBN(String isbnToModify) { String isbnToReturn = isbnToModify; try { if (!this.isNormalizable(isbnToModify)) { return isbnToModify; } String tIsbnToModify = this.normalizeISBN(isbnToModify); if (this.isValidISBN10(tIsbnToModify)) { // String isbnToReturn1 = this.isbnShortToLong(tIsbnToModify); // String isbnTorReturn2 = this.isbnShortToLongVuFind(tIsbnToModify); // assert isbnToReturn1.equalsIgnoreCase(isbnTorReturn2); isbnToReturn = this.isbnShortToLongVuFind(tIsbnToModify); } else if (this.isValidISBN13(tIsbnToModify)) { isbnToReturn = this.isbnLongToShort(tIsbnToModify); } } catch (Throwable ex) { // todo: activate logging System.out.println(ex.getMessage()); // isbnToReturn = isbnToModify; } return isbnToReturn; }
private void handleHookDataIntegrityIssues( final JsonCommand command, final DataIntegrityViolationException dve) { final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("hook_name")) { final String name = command.stringValueOfParameterNamed("name"); throw new PlatformDataIntegrityException( "error.msg.hook.duplicate.name", "A hook with name '" + name + "' already exists", "name", name); } throw new PlatformDataIntegrityException( "error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); }
/** * Use reflection to invoke the requested method. Cache the method object to speed up the process * will be invoked * * @param methodName The method to call. * @param params The arguments passed to the called method. */ private Object doPrivileged(final String methodName, Object[] params) { try { return invokeMethod(context, methodName, params); } catch (Throwable t) { throw new RuntimeException(t.getMessage()); } }
public ContextImpl( @NotNull JavaCompiler compiler, @NotNull DiagnosticOutputConsumer outConsumer, @NotNull OutputFileConsumer sink, CanceledStatus canceledStatus, boolean canUseOptimizedmanager) { myOutConsumer = outConsumer; myOutputFileSink = sink; myCanceledStatus = canceledStatus; StandardJavaFileManager stdManager = null; if (canUseOptimizedmanager) { final Class<StandardJavaFileManager> optimizedManagerClass = ClasspathBootstrap.getOptimizedFileManagerClass(); if (optimizedManagerClass != null) { try { stdManager = optimizedManagerClass.newInstance(); } catch (Throwable e) { if (SystemInfo.isWindows) { System.err.println( "Failed to load JPS optimized file manager for javac: " + e.getMessage()); } } } } if (stdManager != null) { myStdManager = stdManager; } else { myStdManager = compiler.getStandardFileManager(outConsumer, Locale.US, null); } }
/** Sends a single invite request and checks whether it arrives normally at the other end. */ public void testSendRequest() { try { // create an empty invite request. Request invite = createTiInviteRequest(null, null, null); Request receivedRequest = null; try { // Send using TI and collect using RI eventCollector.collectRequestEvent(riSipProvider); waitForMessage(); tiSipProvider.sendRequest(invite); waitForMessage(); RequestEvent receivedRequestEvent = eventCollector.extractCollectedRequestEvent(); assertNotNull("The sent request was not received at the other end!", receivedRequestEvent); assertNotNull( "The sent request was not received at the other end!", receivedRequestEvent.getRequest()); } catch (TooManyListenersException ex) { throw new TckInternalError( "The following exception was thrown while trying to add " + "a SipListener to an RI SipProvider", ex); } catch (SipException ex) { ex.printStackTrace(); fail("A SipException exception was thrown while " + "trying to send a request."); } } catch (Throwable exc) { exc.printStackTrace(); fail(exc.getClass().getName() + ": " + exc.getMessage()); } assertTrue(new Exception().getStackTrace()[0].toString(), true); }
public final Response executeCommand( Object inputPar, UserSessionParameters userSessionPars, HttpServletRequest request, HttpServletResponse response, HttpSession userSession, ServletContext context) { try { String tableName = ((Object[]) inputPar)[0].toString(); ArrayList oldVOs = (ArrayList) ((Object[]) inputPar)[1]; ArrayList newVOs = (ArrayList) ((Object[]) inputPar)[2]; VariantTypes bean = (VariantTypes) JAIOBeanFactory.getInstance().getBean(VariantTypes.class); Response answer = bean.updateVariantTypes( tableName, oldVOs, newVOs, ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(), userSessionPars.getUsername()); return answer; } catch (Throwable ex) { Logger.error( userSessionPars.getUsername(), this.getClass().getName(), "executeCommand", "Error while processing request", ex); return new ErrorResponse(ex.getMessage()); } }
public final Response executeCommand( Object inputPar, UserSessionParameters userSessionPars, HttpServletRequest request, HttpServletResponse response, HttpSession userSession, ServletContext context) { ArrayList vos = (ArrayList) inputPar; try { ItemDiscounts bean = (ItemDiscounts) JAIOBeanFactory.getInstance().getBean(ItemDiscounts.class); Response answer = bean.deleteItemDiscounts( vos, ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(), userSessionPars.getUsername()); return answer; } catch (Throwable ex) { Logger.error( userSessionPars.getUsername(), this.getClass().getName(), "executeCommand", "Error while processing request", ex); return new ErrorResponse(ex.getMessage()); } }
/** * Convert logging event to map * * @param e * @return */ public static Map<String, Object> toMap(LoggingEvent e) { final Map<String, Object> m = Objects.newHashMap( "name", e.getLoggerName(), "date", new Date(e.getTimeStamp()), "level", e.getLevel().toString(), "thread", e.getThreadName(), "message", "" + e.getMessage(), "fileName", e.getLocationInformation().getFileName(), "methodName", e.getLocationInformation().getMethodName(), "lineNumber", e.getLocationInformation().getLineNumber(), "requestId", e.getMDC("requestId"), "sessionId", e.getMDC("sessionId"), "freeMemory", Runtime.getRuntime().freeMemory(), "throwable", null); if (e.getThrowableInformation() != null && e.getThrowableInformation().getThrowable() != null) { Throwable t = e.getThrowableInformation().getThrowable(); m.put( "throwable", Objects.newHashMap( "message", t.getMessage(), "class", t.getClass().getName(), "stackTrace", getStackTrace(t))); } return m; }
protected IDatabaseManager.DatabaseType getType(DataSource dataSource) throws ApsSystemException { String typeString = null; try { String driverClassName = this.invokeGetMethod("getDriverClassName", dataSource); Iterator<Object> typesIter = this.getDatabaseTypeDrivers().keySet().iterator(); while (typesIter.hasNext()) { String typeCode = (String) typesIter.next(); List<String> driverClassNames = (List<String>) this.getDatabaseTypeDrivers().get(typeCode); if (null != driverClassNames && driverClassNames.contains(driverClassName)) { typeString = typeCode; break; } } if (null == typeString) { ApsSystemUtils.getLogger() .severe( "Type not recognized for Driver '" + driverClassName + "' - " + "Recognized types '" + IDatabaseManager.DatabaseType.values() + "'"); return IDatabaseManager.DatabaseType.UNKNOWN; } return Enum.valueOf(IDatabaseManager.DatabaseType.class, typeString.toUpperCase()); } catch (Throwable t) { ApsSystemUtils.getLogger() .severe("Invalid type for db - '" + typeString + "' - " + t.getMessage()); throw new ApsSystemException("Invalid type for db - '" + typeString + "'", t); } }
public <T> List<Class<T>> getInterfaceImplementations(Class<T> interfaceClass, File f) throws IOException, ClassNotFoundException { ArrayList<Class<T>> list = new ArrayList<>(); List<String> classes = null; if (f.isDirectory()) { classes = getClassesFromDir(f); } else { classes = getClassesFromJar(f); } URL url = f.toURI().toURL(); ClassLoader cl = new URLClassLoader(new URL[] {url}, this.getClass().getClassLoader()); for (String klazz : classes) { try { Class<?> c = cl.loadClass(klazz); if (interfaceClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) { list.add((Class<T>) c); } } catch (Throwable t) { LOGGER.warn( String.format( "Error checking if class %s from file %s is implementing %s: %s", klazz, f, interfaceClass.getName(), t.getMessage())); } } return list; }
public final Response executeCommand( Object inputPar, UserSessionParameters userSessionPars, HttpServletRequest request, HttpServletResponse response, HttpSession userSession, ServletContext context) { GridParams gridParams = (GridParams) inputPar; try { String companyCode = (String) gridParams.getOtherGridParams().get(ApplicationConsts.COMPANY_CODE_SYS01); BigDecimal progressiveHie02 = (BigDecimal) gridParams.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE02); ItemFields bean = (ItemFields) JAIOBeanFactory.getInstance().getBean(ItemFields.class); Response answer = bean.loadItemFields( companyCode, progressiveHie02, ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(), userSessionPars.getUsername()); return answer; } catch (Throwable ex) { Logger.error( userSessionPars.getUsername(), this.getClass().getName(), "executeCommand", "Error while processing request", ex); return new ErrorResponse(ex.getMessage()); } }
public JilterStatus eom(JilterEOMActions eomActions, Properties properties) { logger.debug("jilter eom()"); try { bos.close(); // close stream } catch (IOException io) { logger.error("jilter failed to close io stream during eom", io); } byte[] messageBytes = bos.toByteArray(); bos = new ByteArrayOutputStream(); ByteArrayInputStream bis = new ByteArrayInputStream(messageBytes); try { logger.debug("jilter store callback execute"); Config.getStopBlockFactory() .detectBlock("milter server", Thread.currentThread(), this, IDLE_TIMEOUT); callback.store(bis, host); logger.debug("jilter store callback finished"); } catch (ArchiveException e) { logger.error("failed to store the message via milter", e); if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.REJECT) { logger.debug("jilter reject"); return JilterStatus.SMFIS_REJECT; } else if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.RETRYLATER) { logger.debug("jilter temp fail"); return JilterStatus.SMFIS_TEMPFAIL; } } catch (Throwable oome) { logger.error("failed to store message:" + oome.getMessage(), oome); return JilterStatus.SMFIS_REJECT; } finally { Config.getStopBlockFactory().endDetectBlock(Thread.currentThread()); } return JilterStatus.SMFIS_CONTINUE; }
protected void addTest(Class<?> clazz, ITestResult result) { try { TestCase test_case = new TestCase( result.getStatus(), clazz.getName(), getMethodName(result), result.getStartMillis(), result.getEndMillis()); switch (result.getStatus()) { case ITestResult.FAILURE: case ITestResult.SKIP: Throwable ex = result.getThrowable(); if (ex != null) { String failure_type = ex.getClass().getName(); String failure_msg = ex.getMessage(); String stack_trace = printException(ex); test_case.setFailure(failure_type, failure_msg, stack_trace); } else test_case.setFailure("exception", "SKIPPED", null); break; } synchronized ( this) { // handle concurrent access by different threads, if test methods are run in // parallel DataOutputStream output = tests.get(clazz); test_case.writeTo(output); } } catch (Exception e) { error(e.toString()); } }
public Connection executeBatch() throws Sql2oException { long start = System.currentTimeMillis(); try { logExecution(); PreparedStatement statement = buildPreparedStatement(); connection.setBatchResult(statement.executeBatch()); this.currentBatchRecords = 0; try { connection.setKeys(this.returnGeneratedKeys ? statement.getGeneratedKeys() : null); connection.setCanGetKeys(this.returnGeneratedKeys); } catch (SQLException sqlex) { throw new Sql2oException( "Error while trying to fetch generated keys from database. If you are not expecting any generated keys, fix this error by setting the fetchGeneratedKeys parameter in the createQuery() method to 'false'", sqlex); } } catch (Throwable e) { this.connection.onException(); throw new Sql2oException("Error while executing batch operation: " + e.getMessage(), e); } finally { closeConnectionIfNecessary(); } long end = System.currentTimeMillis(); logger.debug( "total: {} ms; executed batch [{}]", new Object[] {end - start, this.getName() == null ? "No name" : this.getName()}); return this.connection; }
/** Tests sending a request from a ClientTransaction. */ public void testSendRequest() { try { Request invite = createTiInviteRequest(null, null, null); RequestEvent receivedRequestEvent = null; ClientTransaction tran = null; try { tran = tiSipProvider.getNewClientTransaction(invite); eventCollector.collectRequestEvent(riSipProvider); tran.sendRequest(); waitForMessage(); receivedRequestEvent = eventCollector.extractCollectedRequestEvent(); assertNotNull("The sent request was not received by the RI!", receivedRequestEvent); assertNotNull( "The sent request was not received by the RI!", receivedRequestEvent.getRequest()); } catch (TransactionUnavailableException exc) { throw new TiUnexpectedError( "A TransactionUnavailableException was thrown while trying to " + "create a new client transaction", exc); } catch (SipException exc) { exc.printStackTrace(); fail("The SipException was thrown while trying to send the request."); } catch (TooManyListenersException exc) { throw new TckInternalError( "A TooManyListenersException was thrown while trying " + "to add a SipListener to an RI SipProvider", exc); } } catch (Throwable exc) { exc.printStackTrace(); fail(exc.getClass().getName() + ": " + exc.getMessage()); } assertTrue(new Exception().getStackTrace()[0].toString(), true); }
public void recordStatus(OperationResultStatus status, Throwable cause) { this.status = status; this.cause = cause; // No other message was given, so use message from the exception // not really correct, but better than nothing. message = cause.getMessage(); }
@Override public StepExecutionResult executeImplementation(StepExecutionContext context) throws MuseExecutionError { StepConfiguration config = getConfiguration(); HashMap<String, Object> values = new HashMap<>(); for (String name : config.getSourceNames()) { MuseValueSource source = getValueSource(config, name, false, context.getProject()); values.put(name, getValue(source, context, true, Object.class)); } try { JavascriptRunner runner = new JavascriptStepRunner(); runner.evalScript(_origin); Object result = runner.invokeFunction(EXECUTE_FUNCTION, context, values); if (result instanceof StepExecutionResult) return (StepExecutionResult) result; else context.raiseEvent( new ScriptFailureEvent( "Script did not return a StepExecutionResult. Instead, it returned: " + result, null)); // TODO do something better than n/a } catch (Throwable t) { LOG.error("unable to execute script: ", t); context.raiseEvent( new ScriptFailureEvent( "Script threw an exception: " + t.getMessage(), t)); // TODO do something better than n/a } return new BasicStepExecutionResult(StepExecutionStatus.FAILURE); }
private Object executeTaskAndGet(final DistributedTask task) { try { factory.getExecutorService().execute(task); try { return task.get(3, TimeUnit.SECONDS); } catch (Throwable e) { logger.log(Level.FINEST, e.getMessage(), e); return null; } } catch (Throwable e) { if (running.get() && factory.node.isActive()) { logger.log(Level.WARNING, e.getMessage(), e); } return null; } }
protected void initializeLogging() { if (settings.getGrailsHome() == null) { return; } try { Class<?> cls = Thread.currentThread() .getContextClassLoader() .loadClass("org.apache.log4j.PropertyConfigurator"); Method configure = cls.getMethod("configure", URL.class); configure.setAccessible(true); File f = new File(settings.getGrailsHome() + "/grails-scripts/src/main/scripts/log4j.properties"); if (f.exists()) { configure.invoke(cls, f.toURI().toURL()); } else { f = new File(settings.getGrailsHome() + "/scripts/log4j.properties"); configure.invoke(cls, f.toURI().toURL()); } } catch (Throwable e) { console.verbose( "Log4j was not found on the classpath and will not be used for command line logging. Cause " + e.getClass().getName() + ": " + e.getMessage()); } }
@Override public void parseRequestParameters( final Map<String, String> params, final Map<String, com.bradmcevoy.http.FileItem> files) throws RequestParseException { try { if (isMultiPart()) { parseQueryString(params, req.getQueryString()); @SuppressWarnings("unchecked") final List<FileItem> items = new ServletFileUpload().parseRequest(req); for (final FileItem item : items) { if (item.isFormField()) params.put(item.getFieldName(), item.getString()); else files.put(item.getFieldName(), new FileItemWrapper(item)); } } else { final Enumeration<String> en = req.getParameterNames(); while (en.hasMoreElements()) { final String nm = en.nextElement(); final String val = req.getParameter(nm); params.put(nm, val); } } } catch (final FileUploadException ex) { throw new RequestParseException("FileUploadException", ex); } catch (final Throwable ex) { throw new RequestParseException(ex.getMessage(), ex); } }