Java Code Examples for org.apache.commons.lang3.exception.ExceptionUtils

The following examples show how to use org.apache.commons.lang3.exception.ExceptionUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tomee   Source File: SimpleTomEEFormatterTest.java    License: Apache License 2.0 7 votes vote down vote up
@Test
public void formatNotNullThrown() throws Exception {
    final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);

    try {
        final String lineSeparatorValue = "\n";
        final String logMessage = "An example log record";
        final Level level = Level.CONFIG;
        final String exceptionMessage = "An example exception";
        final Throwable thrown = new Exception(exceptionMessage);

        System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
        final LogRecord logRecordInput = new LogRecord(level, logMessage);
        logRecordInput.setThrown(thrown);

        final Formatter formatter = new SimpleTomEEFormatter();
        final String actualFormatOutput = formatter.format(logRecordInput);

        final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + lineSeparatorValue + ExceptionUtils.getStackTrace(thrown);

        assertEquals(expectedFormatOutput, actualFormatOutput);
    } finally {
        System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
    }
}
 
Example 2
Source Project: cuba   Source File: MssqlDateOutOfRangeExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handle(Throwable exception, WindowManager windowManager) {
    List<Throwable> list = ExceptionUtils.getThrowableList(exception);
    for (Throwable throwable : list) {
        if (className.contains(throwable.getClass().getName()) && isDateOutOfRangeMessage(throwable.getMessage())) {
            doHandle(windowManager);
            return true;
        }
        if (throwable instanceof RemoteException) {
            RemoteException remoteException = (RemoteException) throwable;
            for (RemoteException.Cause cause : remoteException.getCauses()) {
                if (className.contains(cause.getClassName()) && isDateOutOfRangeMessage(throwable.getMessage())) {
                    doHandle(windowManager);
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 3
Source Project: WePush   Source File: WxMpTemplateMsgSender.java    License: MIT License 6 votes vote down vote up
@Override
public SendResult send(String[] msgData) {
    SendResult sendResult = new SendResult();

    try {
        String openId = msgData[0];
        WxMpTemplateMessage wxMessageTemplate = wxMpTemplateMsgMaker.makeMsg(msgData);
        wxMessageTemplate.setToUser(openId);
        if (PushControl.dryRun) {
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMessageTemplate);
        }
    } catch (Exception e) {
        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(ExceptionUtils.getStackTrace(e));
        return sendResult;
    }

    sendResult.setSuccess(true);
    return sendResult;
}
 
Example 4
@Override
public boolean handleException(final JobServiceConfiguration jobServiceConfiguration, final JobInfo job, final Throwable exception) {
    if (HANDLER_TYPE_BREAK_POINT.equals(job.getJobHandlerType())) {
        LOGGER.debug("break point execution throws an exception which will be swallowed", exception);
        jobServiceConfiguration.getCommandExecutor().execute( 
                commandContext -> {
                    JobEntity jobEntity = jobServiceConfiguration.getJobService().findJobById(job.getId());
                    SuspendedJobEntity suspendedJobEntity = jobServiceConfiguration.getJobService().moveJobToSuspendedJob(jobEntity);
                    if (exception != null) {
                        LOGGER.info("Debugger exception ", exception);
                        suspendedJobEntity.setExceptionMessage(exception.getMessage());
                        suspendedJobEntity.setExceptionStacktrace(ExceptionUtils.getStackTrace(exception));
                    }
                    return null;
                }
        );
        return true;
    }
    return false;
}
 
Example 5
Source Project: WePush   Source File: WxMaTemplateMsgSender.java    License: MIT License 6 votes vote down vote up
@Override
public SendResult send(String[] msgData) {
    SendResult sendResult = new SendResult();

    try {
        String openId = msgData[0];
        WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
        wxMaSubscribeMessage.setToUser(openId);
        wxMaSubscribeMessage.setTemplateId(msgData[1]);
        if (PushControl.dryRun) {
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
        }
    } catch (Exception e) {
        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(ExceptionUtils.getStackTrace(e));
        return sendResult;
    }

    sendResult.setSuccess(true);
    return sendResult;
}
 
Example 6
Source Project: pulsar   Source File: PulsarMetadata.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<String> listSchemaNames(ConnectorSession session) {
    List<String> prestoSchemas = new LinkedList<>();
    try {
        List<String> tenants = pulsarAdmin.tenants().getTenants();
        for (String tenant : tenants) {
            prestoSchemas.addAll(pulsarAdmin.namespaces().getNamespaces(tenant).stream().map(namespace ->
                rewriteNamespaceDelimiterIfNeeded(namespace, pulsarConnectorConfig)).collect(Collectors.toList()));
        }
    } catch (PulsarAdminException e) {
        if (e.getStatusCode() == 401) {
            throw new PrestoException(QUERY_REJECTED, "Failed to get schemas from pulsar: Unauthorized");
        }
        throw new RuntimeException("Failed to get schemas from pulsar: "
                + ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
    }
    return prestoSchemas;
}
 
Example 7
/**
    * Clean return of Exception in JSon format & log Exception.
    * 
    * @param request
    * @param response
    * @param out
    * @param exception
    */
   public static void logAndReturnException(HttpServletRequest request,
    HttpServletResponse response, PrintWriter out,
    Exception exception) {

try {
    JsonErrorReturn jsonErrorReturn = new JsonErrorReturn(response,
	    HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
	    JsonErrorReturn.ERROR_ACEQL_ERROR, exception.getMessage(),
	    ExceptionUtils.getStackTrace(exception));

    out.println(jsonErrorReturn.build());
    LoggerUtil.log(request, exception);
} catch (Exception e) {
    // Should never happen
    e.printStackTrace();
}

   }
 
Example 8
Source Project: sputnik   Source File: ReviewRunner.java    License: Apache License 2.0 6 votes vote down vote up
public void review(@NotNull ReviewProcessor processor) {
    log.info("Review started for processor {}", processor.getName());
    long start = System.currentTimeMillis();
    ReviewResult reviewResult = null;

    try {
        reviewResult = processor.process(review);
    } catch (ReviewException e) {
        log.error("Processor {} error", processor.getName(), e);
        review.addProblem(processor.getName(), ExceptionUtils.getRootCauseMessage(e));

    }
    log.info("Review finished for processor {}. Took {} s", processor.getName(), (System.currentTimeMillis() - start) / THOUSAND);

    if (reviewResult == null) {
        log.warn("Review for processor {} returned empty review", processor.getName());
    } else {
        log.info("Review for processor {} returned {} violations", processor.getName(), reviewResult.getViolations().size());
        review.add(processor.getName(), reviewResult);
    }
}
 
Example 9
Source Project: fastjgame   Source File: RpcSupportHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onComplete(ListenableFuture<Object> future) throws Exception {
    if (context.session.isClosed()) {
        return;
    }

    final RpcErrorCode errorCode;
    final Object body;
    if (future.isCompletedExceptionally()) {
        errorCode = RpcErrorCode.SERVER_EXCEPTION;
        // 不返回完整信息,意义不大
        body = ExceptionUtils.getRootCauseMessage(future.cause());
    } else {
        errorCode = RpcErrorCode.SUCCESS;
        body = future.getNow();
    }

    // 此时已经在网络线程,直接write,但还是需要流经整个管道
    final RpcResponseMessage responseMessage = new RpcResponseMessage(context.requestGuid, context.sync, errorCode, body);
    context.session.fireWrite(responseMessage);
}
 
Example 10
Source Project: cuba   Source File: AbstractUiExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean handle(Throwable exception, UiContext context) {
    List<Throwable> list = ExceptionUtils.getThrowableList(exception);
    for (Throwable throwable : list) {
        if (classNames.contains(throwable.getClass().getName())
                && canHandle(throwable.getClass().getName(), throwable.getMessage(), throwable)) {
            doHandle(throwable.getClass().getName(), throwable.getMessage(), throwable, context);
            return true;
        }
        if (throwable instanceof RemoteException) {
            RemoteException remoteException = (RemoteException) throwable;
            for (RemoteException.Cause cause : remoteException.getCauses()) {
                if (classNames.contains(cause.getClassName())
                        && canHandle(cause.getClassName(), cause.getMessage(), cause.getThrowable())) {
                    doHandle(cause.getClassName(), cause.getMessage(), cause.getThrowable(), context);
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 11
Source Project: feast   Source File: KafkaRecordToFeatureRowDoFn.java    License: Apache License 2.0 6 votes vote down vote up
@ProcessElement
public void processElement(ProcessContext context) {
  byte[] value = context.element().getKV().getValue();
  FeatureRow featureRow;

  try {
    featureRow = FeatureRow.parseFrom(value);
  } catch (InvalidProtocolBufferException e) {
    context.output(
        getFailureTag(),
        FailedElement.newBuilder()
            .setTransformName("KafkaRecordToFeatureRow")
            .setStackTrace(ExceptionUtils.getStackTrace(e))
            .setJobName(context.getPipelineOptions().getJobName())
            .setPayload(new String(Base64.getEncoder().encode(value)))
            .setErrorMessage(e.getMessage())
            .build());
    return;
  }
  context.output(featureRow);
}
 
Example 12
/**
 * move partitions to the target host
 * @param datastreamName
 *    Name of the datastream to move.
 * @param partitions
 *    partitions that need to be moved, separate by comma, ex topicA-0,topicB-1
 * @param targetHost
 *    the target host the partition assignment
 * @throws RemoteInvocationException
 */
public void movePartitions(String datastreamName, String partitions, String targetHost) throws RemoteInvocationException {
  Instant startTime = Instant.now();
  PollUtils.poll(() -> {
    try {
      ActionRequest<Void> request = _builders.actionMovePartitions().id(datastreamName).
          partitionsParam(partitions).targetHostParam(targetHost).build();
      ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
      return datastreamResponseFuture.getResponse();
    } catch (RemoteInvocationException e) {
      if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
        LOG.warn("Timeout: movePartitions. May retry...", e);
        return null;
      }
      if (isNotFoundHttpStatus(e)) {
        LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
        throw new DatastreamNotFoundException(datastreamName, e);
      } else {
        String errorMessage = String.format("move partitions failed with error, Datastream {%s}.", datastreamName);
        ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
      }
      return null; // not reachable
    }
  }, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
  LOG.info("move partitions for datastream {} took {} ms", datastreamName, Duration.between(startTime, Instant.now()).toMillis());
}
 
Example 13
Source Project: zeppelin   Source File: InterpreterRestApi.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Add new repository.
 *
 * @param message Repository
 */
@POST
@Path("repository")
@ZeppelinApi
public Response addRepository(String message) {
  try {
    Repository request = Repository.fromJson(message);
    interpreterSettingManager.addRepository(request.getId(), request.getUrl(),
        request.isSnapshot(), request.getAuthentication(), request.getProxy());
    logger.info("New repository {} added", request.getId());
  } catch (Exception e) {
    logger.error("Exception in InterpreterRestApi while adding repository ", e);
    return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR, e.getMessage(),
        ExceptionUtils.getStackTrace(e)).build();
  }
  return new JsonResponse(Status.OK).build();
}
 
Example 14
Source Project: beihu-boot   Source File: AbstractTransmission.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void acquire() {
    lock.lock();
    try {
        acquireCnt++;
        while (!acquirable()) {
            try {
                doWait();
            } catch (InterruptedException e) {
                ExceptionUtils.wrapAndThrow(e);
            }
        }
        onAcquired();
    } finally {
        acquireCnt--;
        lock.unlock();
    }
}
 
Example 15
Source Project: tinkerpop   Source File: GremlinDriverIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReportErrorWhenRequestCantBeSerialized() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V3D0).create();
    final Client client = cluster.connect().alias("g");

    try {
        final Map<String,Object> params = new HashMap<>();
        params.put("r", Color.RED);
        client.submit("r", params).all().get();
        fail("Should have thrown exception over bad serialization");
    } catch (Exception ex) {
        final Throwable inner = ExceptionUtils.getRootCause(ex);
        assertThat(inner, instanceOf(ResponseException.class));
        assertEquals(ResponseStatusCode.REQUEST_ERROR_SERIALIZATION, ((ResponseException) inner).getResponseStatusCode());
        assertTrue(ex.getMessage().contains("An error occurred during serialization of this request"));
    }

    // should not die completely just because we had a bad serialization error.  that kind of stuff happens
    // from time to time, especially in the console if you're just exploring.
    assertEquals(2, client.submit("1+1").all().get().get(0).getInt());

    cluster.close();
}
 
Example 16
Source Project: zeppelin   Source File: UniverseClient.java    License: Apache License 2.0 6 votes vote down vote up
public boolean closeSession(String paragraphId) throws UniverseException {
  try {
    if (tokens.containsKey(paragraphId)) {
      HttpPost httpPost = new HttpPost(String.format("%s%s", apiUrl, "/logoff"));
      setHeaders(httpPost, tokens.get(paragraphId));
      HttpResponse response = httpClient.execute(httpPost);
      if (response.getStatusLine().getStatusCode() == 200) {
        return true;
      }
    }

    return false;
  } catch (Exception e) {
    throw new UniverseException(String.format(errorMessageTemplate, "UniverseClient "
        + "(close session): Request failed", ExceptionUtils.getStackTrace(e)));
  } finally {
    tokens.remove(paragraphId);
  }
}
 
Example 17
Source Project: tinkerpop   Source File: GremlinServerSslIntegrateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEnableSslAndFailIfCiphersDontMatch() {
    final Cluster cluster = TestClientFactory.build().enableSsl(true).keyStore(JKS_SERVER_KEY).keyStorePassword(KEY_PASS)
            .sslSkipCertValidation(true).sslCipherSuites(Arrays.asList("SSL_RSA_WITH_RC4_128_SHA")).create();
    final Client client = cluster.connect();

    try {
        client.submit("'test'").one();
        fail("Should throw exception because ssl client requires TLSv1.2 whereas server supports only TLSv1.1");
    } catch (Exception x) {
        final Throwable root = ExceptionUtils.getRootCause(x);
        assertThat(root, instanceOf(TimeoutException.class));
    } finally {
        cluster.close();
    }
}
 
Example 18
Source Project: cuba   Source File: WebDialogs.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void show() {
    if (throwable == null) {
        throw new IllegalStateException("throwable should not be null");
    }

    Throwable rootCause = ExceptionUtils.getRootCause(throwable);
    if (rootCause == null) {
        rootCause = throwable;
    }

    ExceptionDialog dialog = new ExceptionDialog(rootCause, caption, message);
    for (com.vaadin.ui.Window window : ui.getWindows()) {
        if (window.isModal()) {
            dialog.setModal(true);
            break;
        }
    }
    ui.addWindow(dialog);
    dialog.focus();
}
 
Example 19
@Override
public BackgroundException map(final ApiException failure) {
    for(Throwable cause : ExceptionUtils.getThrowableList(failure)) {
        if(cause instanceof SocketException) {
            // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe
            return new DefaultSocketExceptionMappingService().map((SocketException) cause);
        }
        if(cause instanceof HttpResponseException) {
            return new DefaultHttpResponseExceptionMappingService().map((HttpResponseException) cause);
        }
        if(cause instanceof IOException) {
            return new DefaultIOExceptionMappingService().map((IOException) cause);
        }
        if(cause instanceof IllegalStateException) {
            // Caused by: ch.cyberduck.core.sds.io.swagger.client.ApiException: javax.ws.rs.ProcessingException: java.lang.IllegalStateException: Connection pool shut down
            return new ConnectionCanceledException(cause);
        }
    }
    return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getCode(), failure.getMessage()));
}
 
Example 20
@BeforeClass
public static void setup() throws Exception {
    try {
        System.setProperty("org.apache.commons.logging.Log", "org.openas2.logging.Log");
        //System.setProperty("org.openas2.logging.defaultlog", "TRACE");
        FilenameParsingTest.session = new XMLSession(RESOURCE.get("MyCompany", "config", "config.xml").getAbsolutePath());
        msg = new AS2Message();
        msg.setAttribute(FileAttribute.MA_FILENAME, testFileName);
        PartnershipFactory pf = session.getPartnershipFactory();
        Partnership myPartnership = msg.getPartnership();
        myPartnership.setSenderID(Partnership.PID_AS2, myCompanyOid);
        myPartnership.setReceiverID(Partnership.PID_AS2, myPartnerOid);
        myPartnership.setSenderID(Partnership.PID_AS2, myCompanyOid);


        Partnership configuredPartnership = pf.getPartnership(myPartnership, false);
        configuredPartnership.setAttribute(Partnership.PAIB_VALUES_REGEX_ON_FILENAME, fileNameRegex);
        configuredPartnership.setAttribute(Partnership.PAIB_NAMES_FROM_FILENAME, attribNamesFromFileName);
        configuredPartnership.setAttribute(Partnership.PA_SUBJECT, subjectAttrib);
        // update the message's partnership with any stored information
        pf.updatePartnership(msg, true);

    } catch (Throwable e) {
        // aid for debugging JUnit tests
        System.err.println("ERROR occurred: " + ExceptionUtils.getStackTrace(e));
        throw new Exception(e);
    }
}
 
Example 21
public ScheduleLogRequest(JobExecutionContext jobExecutionContext, JobExecutionException jobExecutionException) {
	JobDetail jobDetail = jobExecutionContext.getJobDetail();
	this.className = jobDetail.getKey().getName();
	this.application = jobDetail.getKey().getGroup();
	this.node = jobDetail.getDescription();
	this.type = jobExecutionContext.getTrigger().getDescription();
	this.elapsed = jobExecutionContext.getJobRunTime();
	this.fireTime = jobExecutionContext.getFireTime();
	if (null != jobExecutionException) {
		this.stackTrace = ExceptionUtils.getStackTrace(jobExecutionException);
		this.success = false;
	} else {
		this.success = true;
	}
}
 
Example 22
private static void processValidateCCDAException(ValidationResultsMetaData resultsMetaData,
		String serviceErrorStart, String validationObjective, Exception exception) {
	resultsMetaData.setServiceError(true);
	String fullErrorWithStackTrace = serviceErrorStart + ExceptionUtils.getStackTrace(exception);
	if (exception.getMessage() != null) {
		String fullError = serviceErrorStart + exception.getMessage();
		resultsMetaData.setServiceErrorMessage(fullError);
	} else {
		resultsMetaData.setServiceErrorMessage(fullErrorWithStackTrace);
	}
	logger.error(fullErrorWithStackTrace);
	resultsMetaData.setObjectiveProvided(validationObjective);
}
 
Example 23
Source Project: sailfish-core   Source File: ServiceActions.java    License: Apache License 2.0 5 votes vote down vote up
@CommonColumns(@CommonColumn(value = Column.ServiceName, required = true))
@ActionMethod
   public void initService(IActionContext actionContext, HashMap<?, ?> message) throws IllegalAccessException, InvocationTargetException, InterruptedException, IOException {
	ServiceName serviceName = ServiceName.parse(actionContext.getServiceName());
	IActionServiceManager serviceManager = actionContext.getServiceManager();

	try {
           IServiceSettings serviceSettings = serviceManager.getServiceSettings(serviceName);
		BeanMap beanMap = new BeanMap(serviceSettings);
		Set<String> editedProperty = new HashSet<>();
		Set<String> incorrectProperty = new HashSet<>();
		for (Entry<?, ?> entry : message.entrySet()) {
			String property = convertProperty(entry.getKey().toString());
			if (beanMap.containsKey(property)){
				BeanUtils.setProperty(serviceSettings, property, converter.get().convert((Object)unwrapFilters(entry.getValue()), beanMap.getType(property)));
                   editedProperty.add(property);
			} else {
				incorrectProperty.add(property);
			}
		}

		if (!incorrectProperty.isEmpty()) {
			throw new EPSCommonException(serviceSettings.getClass().getName() + " does not contain properties: " + incorrectProperty);
		}

           serviceManager.updateService(serviceName, serviceSettings, null).get();

		try (FileOutputStream out = new FileOutputStream(actionContext.getReport().createFile(StatusType.NA, servicesFolder, changingSettingFolder, serviceName + FORMATTER.format(DateTimeUtility.nowLocalDateTime()) + servicesFileExpression))) {
               actionContext.getServiceManager().serializeServiceSettings(serviceName, out);
           }
       } catch (ExecutionException e) {
           ExceptionUtils.rethrow(ObjectUtils.defaultIfNull(e.getCause(), e));
       }
}
 
Example 24
Source Project: cia   Source File: UiInstanceErrorHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void error(final ErrorEvent event) {
	if (ExceptionUtils.getRootCause(event.getThrowable()) instanceof AccessDeniedException) {
		final AccessDeniedException accessDeniedException = (AccessDeniedException) ExceptionUtils.getRootCause(event.getThrowable());
		Notification.show(accessDeniedException.getMessage(), Notification.Type.ERROR_MESSAGE);
		ui.getNavigator().navigateTo(CommonsViews.MAIN_VIEW_NAME);
	} else {
		LOGGER.warn(LOG_WARN_VAADIN_ERROR, event.getThrowable());
	}
}
 
Example 25
Source Project: jackdaw   Source File: ProcessorContextHolder.java    License: Apache License 2.0 5 votes vote down vote up
public static void withContext(final ProcessorContext context, final Runnable runnable) {
    Validate.notNull(context, "Processor context must be defined");
    Validate.notNull(runnable, "Operation must be defined");

    CONTEXT.set(context);
    try {
        runnable.run();
    } catch (final Exception ex) {
        MessageUtils.error(ExceptionUtils.getMessage(ex));
    }  finally {
        CONTEXT.remove();
    }
}
 
Example 26
Source Project: px2rwd-intellij-plugin   Source File: LogicUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 重写默认的accept函数
 *
 * @param t 接受的泛型参数
 */
@Override
default void accept(T t) {
    try {
        acceptException(t);
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getRootCause(e).getMessage());
    }
}
 
Example 27
Source Project: MyTown2   Source File: MyTownDatasource.java    License: The Unlicense 5 votes vote down vote up
public boolean deleteBlock(TownBlock block) {
    try {
        // Delete Block from Datasource
        PreparedStatement deleteBlockStatement = prepare("DELETE FROM " + prefix + "Blocks WHERE dim=? AND x=? AND z=?", true);
        deleteBlockStatement.setInt(1, block.getDim());
        deleteBlockStatement.setInt(2, block.getX());
        deleteBlockStatement.setInt(3, block.getZ());
        deleteBlockStatement.execute();

        if (block.isChunkloaded()) {
            block.getTown().ticketMap.chunkUnload(block);
        }

        // Delete Block from Town
        block.getTown().townBlocksContainer.remove(block);

        // Delete Plots contained in the Block
        for (Plot p : ImmutableList.copyOf(block.plotsContainer)) {
            deletePlot(p);
        }
        // Remove Block from Map
        MyTownUniverse.instance.removeTownBlock(block);
    } catch (SQLException e) {
        LOG.error("Failed to delete Block {}!", block.getKey());
        LOG.error(ExceptionUtils.getStackTrace(e));
        return false;
    }
    return true;
}
 
Example 28
Source Project: px2rwd-intellij-plugin   Source File: LogicUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 重写默认的apply函数
 *
 * @param t 接受的泛型参数
 * @return 返回泛型R
 */
@Override
default R apply(T t) {
    try {
        return applyException(t);
    } catch (Exception e) {
        throw new RuntimeException(ExceptionUtils.getRootCause(e).getMessage());
    }
}
 
Example 29
Source Project: WePush   Source File: TxYunMsgSender.java    License: MIT License 5 votes vote down vote up
@Override
public SendResult send(String[] msgData) {
    SendResult sendResult = new SendResult();
    try {
        int templateId = TxYunMsgMaker.templateId;
        String smsSign = App.config.getTxyunSign();
        String[] params = txYunMsgMaker.makeMsg(msgData);
        String telNum = msgData[0];
        if (PushControl.dryRun) {
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            SmsSingleSenderResult result = smsSingleSender.sendWithParam("86", telNum,
                    templateId, params, smsSign, "", "");

            if (result.result == 0) {
                sendResult.setSuccess(true);
            } else {
                sendResult.setSuccess(false);
                sendResult.setInfo(result.toString());
            }
        }
    } catch (Exception e) {
        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(ExceptionUtils.getStackTrace(e));
    }

    return sendResult;
}
 
Example 30
Source Project: macrobase   Source File: MultipleRowSetResource.java    License: Apache License 2.0 5 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_JSON)
public MultipleRowSetResponse getRows(MultipleRowSetRequest request) {
    MultipleRowSetResponse response = new MultipleRowSetResponse();

    try {
        conf.set(MacroBaseConf.DB_URL, request.pgUrl);

        // Need a CSV ingester. Changing so it's not fixed during construction (used to be final, but changed as
        // this is set in AnalyzeResource after construction)
        configuredIngester = conf.getString(MacroBaseConf.DATA_LOADER_TYPE, MacroBaseDefaults.DATA_LOADER_TYPE.toString());

        DataIngester loader = getLoader();
        List<RowSet> lr = new ArrayList<RowSet>();
        for (List<RowSetResource.RowSetRequest.RowRequestPair> columnValue : request.columnValues) {
            HashMap<String, String> preds = new HashMap<>();
            columnValue.stream().forEach(a -> preds.put(a.column, a.value));
            lr.add(loader.getRows(request.baseQuery,
                                  preds,
                                  request.limit,
                                  request.offset));
        }

        response.rowSets = lr;
    } catch (Exception e) {
        log.error("An error occurred while processing a request:", e);
        response.errorMessage = ExceptionUtils.getStackTrace(e);
    }

    return response;
}