List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.apache.manifoldcf.crawler.connectors.jira.JiraRepositoryConnector.java
/** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above./*from w w w.ja v a 2 s.c om*/ *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { // Forced acls String[] acls = getAcls(spec); if (acls != null) java.util.Arrays.sort(acls); for (String documentIdentifier : documentIdentifiers) { if (documentIdentifier.startsWith("I-")) { // It is an issue String versionString; String[] aclsToUse; String issueID; JiraIssue jiraFile; issueID = documentIdentifier.substring(2); jiraFile = getIssue(issueID); if (jiraFile == null) { activities.deleteDocument(documentIdentifier); continue; } Date rev = jiraFile.getUpdatedDate(); if (rev == null) { //a jira document that doesn't contain versioning information will NEVER be processed. // I don't know what this means, and whether it can ever occur. activities.deleteDocument(documentIdentifier); continue; } StringBuilder sb = new StringBuilder(); if (acls == null) { // Get acls from issue List<String> users = getUsers(issueID); aclsToUse = (String[]) users.toArray(new String[0]); java.util.Arrays.sort(aclsToUse); } else { aclsToUse = acls; } // Acls packList(sb, aclsToUse, '+'); if (aclsToUse.length > 0) { sb.append('+'); pack(sb, defaultAuthorityDenyToken, '+'); } else sb.append('-'); sb.append(rev.toString()); versionString = sb.toString(); if (activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) continue; if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("JIRA: Processing document identifier '" + documentIdentifier + "'"); } long startTime = System.currentTimeMillis(); String errorCode = null; String errorDesc = null; Long fileSize = null; try { // Now do standard stuff String mimeType = "text/plain"; Date createdDate = jiraFile.getCreatedDate(); Date modifiedDate = jiraFile.getUpdatedDate(); String documentURI = composeDocumentURI(getBaseUrl(session), jiraFile.getKey()); if (!activities.checkURLIndexable(documentURI)) { errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('" + documentURI + "')"; activities.noDocument(documentIdentifier, versionString); continue; } if (!activities.checkMimeTypeIndexable(mimeType)) { errorCode = activities.EXCLUDED_MIMETYPE; errorDesc = "Excluded because of mime type ('" + mimeType + "')"; activities.noDocument(documentIdentifier, versionString); continue; } if (!activities.checkDateIndexable(modifiedDate)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of date (" + modifiedDate + ")"; activities.noDocument(documentIdentifier, versionString); continue; } //otherwise process RepositoryDocument rd = new RepositoryDocument(); // Turn into acls and add into description String[] denyAclsToUse; if (aclsToUse.length > 0) denyAclsToUse = new String[] { defaultAuthorityDenyToken }; else denyAclsToUse = new String[0]; rd.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT, aclsToUse, denyAclsToUse); rd.setMimeType(mimeType); if (createdDate != null) rd.setCreatedDate(createdDate); if (modifiedDate != null) rd.setModifiedDate(modifiedDate); rd.addField("key", jiraFile.getKey()); rd.addField("self", jiraFile.getSelf()); rd.addField("description", jiraFile.getDescription()); // Get general document metadata Map<String, String[]> metadataMap = jiraFile.getMetadata(); for (Entry<String, String[]> entry : metadataMap.entrySet()) { rd.addField(entry.getKey(), entry.getValue()); } String document = getJiraBody(jiraFile); try { byte[] documentBytes = document.getBytes(StandardCharsets.UTF_8); long fileLength = documentBytes.length; if (!activities.checkLengthIndexable(fileLength)) { errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of document length (" + fileLength + ")"; activities.noDocument(documentIdentifier, versionString); continue; } InputStream is = new ByteArrayInputStream(documentBytes); try { rd.setBinary(is, fileLength); activities.ingestDocumentWithException(documentIdentifier, versionString, documentURI, rd); // No errors. Record the fact that we made it. errorCode = "OK"; fileSize = new Long(fileLength); } finally { is.close(); } } catch (java.io.IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(e); } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) errorCode = null; throw e; } finally { if (errorCode != null) activities.recordActivity(new Long(startTime), ACTIVITY_READ, fileSize, documentIdentifier, errorCode, errorDesc, null); } } else { // Unrecognized identifier type activities.deleteDocument(documentIdentifier); continue; } } }
From source file:com.amalto.core.server.DefaultItem.java
/** * Returns an ordered collection of results searched in a cluster and specifying an optional condition<br/> * The results are xml objects made of elements constituted by the specified viewablePaths * * @param dataClusterPOJOPK The Data Cluster where to run the query * @param forceMainPivot An optional pivot that will appear first in the list of pivots in the query<br> * : This allows forcing cartesian products: for instance Order Header vs Order Line * @param viewablePaths The list of elements returned in each result * @param whereItem The condition//w ww . j a v a 2 s .c o m * @param spellThreshold The condition spell checking threshold. A negative value de-activates spell * @param orderBy The full path of the item user to order * @param direction One of {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_ASCENDING} or * {@link com.amalto.xmlserver.interfaces.IXmlServerSLWrapper#ORDER_DESCENDING} * @param start The first item index (starts at zero) * @param limit The maximum number of items to return * @param returnCount True if total search count should be returned as first result. * @return The ordered list of results * @throws com.amalto.core.util.XtentisException In case of error in MDM code. */ @Override public ArrayList<String> xPathsSearch(DataClusterPOJOPK dataClusterPOJOPK, String forceMainPivot, ArrayList<String> viewablePaths, IWhereItem whereItem, int spellThreshold, String orderBy, String direction, int start, int limit, boolean returnCount) throws XtentisException { try { if (viewablePaths.size() == 0) { String err = "The list of viewable xPaths must contain at least one element"; LOGGER.error(err); throw new XtentisException(err); } // Check if user is allowed to read the cluster ILocalUser user = LocalUser.getLocalUser(); boolean authorized = false; String dataModelName = dataClusterPOJOPK.getUniqueId(); if (MDMConfiguration.getAdminUser().equals(user.getUsername())) { authorized = true; } else if (user.userCanRead(DataClusterPOJO.class, dataModelName)) { authorized = true; } if (!authorized) { throw new XtentisException("Unauthorized read access on data cluster '" + dataModelName + "' by user '" + user.getUsername() + "'"); } Server server = ServerContext.INSTANCE.get(); String typeName = StringUtils.substringBefore(viewablePaths.get(0), "/"); //$NON-NLS-1$ StorageAdmin storageAdmin = server.getStorageAdmin(); Storage storage = storageAdmin.get(dataModelName, storageAdmin.getType(dataModelName)); MetadataRepository repository = storage.getMetadataRepository(); ComplexTypeMetadata type = repository.getComplexType(typeName); UserQueryBuilder qb = from(type); qb.where(UserQueryHelper.buildCondition(qb, whereItem, repository)); qb.start(start); qb.limit(limit); if (orderBy != null) { List<TypedExpression> fields = UserQueryHelper.getFields(type, StringUtils.substringAfter(orderBy, "/")); //$NON-NLS-1$ if (fields == null) { throw new IllegalArgumentException("Field '" + orderBy + "' does not exist."); } OrderBy.Direction queryDirection; if ("ascending".equals(direction)) { //$NON-NLS-1$ queryDirection = OrderBy.Direction.ASC; } else { queryDirection = OrderBy.Direction.DESC; } for (TypedExpression field : fields) { qb.orderBy(field, queryDirection); } } // Select fields for (String viewablePath : viewablePaths) { String viewableTypeName = StringUtils.substringBefore(viewablePath, "/"); //$NON-NLS-1$ String viewableFieldName = StringUtils.substringAfter(viewablePath, "/"); //$NON-NLS-1$ if (!viewableFieldName.isEmpty()) { qb.select(repository.getComplexType(viewableTypeName), viewableFieldName); } else { qb.selectId(repository.getComplexType(viewableTypeName)); // Select id if xPath is 'typeName' and not 'typeName/field' } } ArrayList<String> resultsAsString = new ArrayList<String>(); StorageResults results; try { storage.begin(); if (returnCount) { results = storage.fetch(qb.getSelect()); resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$ } results = storage.fetch(qb.getSelect()); DataRecordWriter writer = new DataRecordDefaultWriter(); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (DataRecord result : results) { try { writer.write(result, output); } catch (IOException e) { throw new XmlServerException(e); } String document = new String(output.toByteArray()); resultsAsString.add(document); output.reset(); } storage.commit(); } catch (Exception e) { storage.rollback(); throw new XmlServerException(e); } return resultsAsString; } catch (XtentisException e) { throw (e); } catch (Exception e) { String err = "Unable to single search: " + ": " + e.getClass().getName() + ": " + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }
From source file:org.openhab.io.transport.modbus.internal.ModbusManagerImpl.java
/** * Execute operation using a retry mechanism. * * This is a helper function for executing read and write operations and handling the exceptions in a common way. * * With some connection types, the connection is reseted (disconnected), and new connection is received from the * pool. This means that potentially other operations queuing for the connection can be executed in-between. * * With some other connection types, the operation is retried without reseting the connection type. * * @param task//from w w w. j a v a 2 s . c om * @param oneOffTask * @param operation */ private <R extends ModbusRequestBlueprint, C extends ModbusCallback, T extends TaskWithEndpoint<R, C>> void executeOperation( @NonNull T task, boolean oneOffTask, ModbusOperation<T> operation) { AggregateStopWatch timer = new AggregateStopWatch(); timer.total.resume(); String operationId = timer.operationId; ModbusSlaveConnectionFactoryImpl connectionFactory = this.connectionFactory; if (connectionFactory == null) { // deactivated manager logger.trace("Deactivated manager - aborting operation."); return; } logTaskQueueInfo(); R request = task.getRequest(); ModbusSlaveEndpoint endpoint = task.getEndpoint(); @Nullable C callback = task.getCallback(); int maxTries = task.getMaxTries(); AtomicReference<@Nullable Exception> lastError = new AtomicReference<>(); long retryDelay = Optional.ofNullable(connectionFactory.getEndpointPoolConfiguration(endpoint)) .map(cfg -> cfg.getInterTransactionDelayMillis()).orElse(0L); if (maxTries <= 0) { throw new IllegalArgumentException("maxTries should be positive"); } Optional<ModbusSlaveConnection> connection = Optional.empty(); try { logger.trace("Starting new operation with task {}. Trying to get connection [operation ID {}]", task, operationId); connection = getConnection(timer, oneOffTask, task); logger.trace("Operation with task {}. Got a connection {} [operation ID {}]", task, connection.isPresent() ? "successfully" : "which was unconnected (connection issue)", operationId); if (!connection.isPresent()) { // Could not acquire connection, time to abort // Error logged already, error callback called as well logger.trace("Initial connection was not successful, aborting. [operation ID {}]", operationId); return; } if (scheduledThreadPoolExecutor == null) { logger.debug("Manager has been shut down, aborting proecssing request {} [operation ID {}]", request, operationId); return; } int tryIndex = 0; /** * last execution is tracked such that the endpoint is not spammed on retry. First retry can be executed * right away since getConnection ensures enough time has passed since last transaction. More precisely, * ModbusSlaveConnectionFactoryImpl sleeps on activate() (i.e. before returning connection). */ @Nullable Long lastTryMillis = null; while (tryIndex < maxTries) { logger.trace("Try {} out of {} [operation ID {}]", tryIndex + 1, maxTries, operationId); if (!connection.isPresent()) { // Connection was likely reseted with previous try, and connection was not successfully // re-established. Error has been logged, time to abort. logger.trace("Try {} out of {}. Connection was not successful, aborting. [operation ID {}]", tryIndex + 1, maxTries, operationId); return; } if (Thread.interrupted()) { logger.warn("Thread interrupted. Aborting operation [operation ID {}]", operationId); return; } // Check poll task is still registered (this is all asynchronous) if (!oneOffTask && task instanceof PollTask) { verifyTaskIsRegistered((PollTask) task); } // Let's ensure that enough time is between the retries logger.trace( "Ensuring that enough time passes before retrying again. Sleeping if necessary [operation ID {}]", operationId); long slept = ModbusSlaveConnectionFactoryImpl.waitAtleast(lastTryMillis, retryDelay); logger.trace("Sleep ended, slept {} [operation ID {}]", slept, operationId); boolean willRetry = false; try { tryIndex++; willRetry = tryIndex < maxTries; operation.accept(timer, task, connection.get()); lastError.set(null); break; } catch (IOException e) { lastError.set(new ModbusSlaveIOExceptionImpl(e)); // IO exception occurred, we re-establish new connection hoping it would fix the issue (e.g. // broken pipe on write) if (willRetry) { logger.warn( "Try {} out of {} failed when executing request ({}). Will try again soon. Error was I/O error, so reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, maxTries, request, e.getClass().getName(), e.getMessage(), operationId); } else { logger.error( "Last try {} failed when executing request ({}). Aborting. Error was I/O error, so reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, request, e.getClass().getName(), e.getMessage(), operationId); } // Invalidate connection, and empty (so that new connection is acquired before new retry) timer.connection.timeConsumer(c -> invalidate(endpoint, c), connection); connection = Optional.empty(); continue; } catch (ModbusIOException e) { lastError.set(new ModbusSlaveIOExceptionImpl(e)); // IO exception occurred, we re-establish new connection hoping it would fix the issue (e.g. // broken pipe on write) if (willRetry) { logger.warn( "Try {} out of {} failed when executing request ({}). Will try again soon. Error was I/O error, so reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, maxTries, request, e.getClass().getName(), e.getMessage(), operationId); } else { logger.error( "Last try {} failed when executing request ({}). Aborting. Error was I/O error, so reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, request, e.getClass().getName(), e.getMessage(), operationId); } // Invalidate connection, and empty (so that new connection is acquired before new retry) timer.connection.timeConsumer(c -> invalidate(endpoint, c), connection); connection = Optional.empty(); continue; } catch (ModbusSlaveException e) { lastError.set(new ModbusSlaveErrorResponseExceptionImpl(e)); // Slave returned explicit error response, no reason to re-establish new connection if (willRetry) { logger.warn( "Try {} out of {} failed when executing request ({}). Will try again soon. Error was: {} {} [operation ID {}]", tryIndex, maxTries, request, e.getClass().getName(), e.getMessage(), operationId); } else { logger.error( "Last try {} failed when executing request ({}). Aborting. Error was: {} {} [operation ID {}]", tryIndex, request, e.getClass().getName(), e.getMessage(), operationId); } continue; } catch (ModbusUnexpectedTransactionIdException e) { lastError.set(e); // transaction error details already logged if (willRetry) { logger.warn( "Try {} out of {} failed when executing request ({}). Will try again soon. The response transaction ID did not match the request. Reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, maxTries, request, e.getClass().getName(), e.getMessage(), operationId); } else { logger.error( "Last try {} failed when executing request ({}). Aborting. The response transaction ID did not match the request. Reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, request, e.getClass().getName(), e.getMessage(), operationId); } // Invalidate connection, and empty (so that new connection is acquired before new retry) timer.connection.timeConsumer(c -> invalidate(endpoint, c), connection); connection = Optional.empty(); continue; } catch (ModbusException e) { lastError.set(e); // Some other (unexpected) exception occurred if (willRetry) { logger.warn( "Try {} out of {} failed when executing request ({}). Will try again soon. Error was unexpected error, so reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, maxTries, request, e.getClass().getName(), e.getMessage(), operationId, e); } else { logger.error( "Last try {} failed when executing request ({}). Aborting. Error was unexpected error, so reseting the connection. Error details: {} {} [operation ID {}]", tryIndex, request, e.getClass().getName(), e.getMessage(), operationId, e); } // Invalidate connection, and empty (so that new connection is acquired before new retry) timer.connection.timeConsumer(c -> invalidate(endpoint, c), connection); connection = Optional.empty(); continue; } finally { lastTryMillis = System.currentTimeMillis(); // Connection was reseted in error handling and needs to be reconnected. // Try to re-establish connection. if (willRetry && !connection.isPresent()) { connection = getConnection(timer, oneOffTask, task); } } } Exception exception = lastError.get(); if (exception != null) { // All retries failed with some error if (callback != null) { timer.callback.timeRunnable(() -> { invokeCallbackWithError(request, callback, exception); }); } } } catch (PollTaskUnregistered e) { logger.warn( "Poll task was unregistered -- not executing/proceeding with the poll: {} [operation ID {}]", e.getMessage(), operationId); return; } catch (InterruptedException e) { logger.warn("Poll task was canceled -- not executing/proceeding with the poll: {} [operation ID {}]", e.getMessage(), operationId); // Invalidate connection, and empty (so that new connection is acquired before new retry) timer.connection.timeConsumer(c -> invalidate(endpoint, c), connection); connection = Optional.empty(); } finally { timer.connection.timeConsumer(c -> returnConnection(endpoint, c), connection); logger.trace("Connection was returned to the pool, ending operation [operation ID {}]", operationId); timer.suspendAllRunning(); logger.debug("Modbus operation ended, timing info: {} [operation ID {}]", timer, operationId); } }
From source file:org.apache.synapse.transport.passthru.SourceHandler.java
public void logIOException(NHttpServerConnection conn, IOException e) { // this check feels like crazy! But weird things happened, when load testing. if (e == null) { return;// w w w . ja v a 2s.c o m } if (e instanceof ConnectionClosedException || (e.getMessage() != null && (e.getMessage().toLowerCase().contains("connection reset by peer") || e.getMessage().toLowerCase().contains("forcibly closed")))) { if (log.isDebugEnabled()) { log.debug( conn + ": I/O error (Probably the keepalive connection " + "was closed):" + e.getMessage()); } } else if (e.getMessage() != null) { String msg = e.getMessage().toLowerCase(); if (msg.indexOf("broken") != -1) { log.warn("I/O error (Probably the connection " + "was closed by the remote party):" + e.getMessage()); } else { log.error("I/O error: " + e.getMessage(), e); } metrics.incrementFaultsReceiving(); } else { log.error("Unexpected I/O error: " + e.getClass().getName(), e); metrics.incrementFaultsReceiving(); } }
From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuator.java
/** * Get an {@link InputStream} which picks up starting {@code bytesRead} bytes from the beginning of the logical * object being downloaded. Implementations should compare headers across all requests and responses to ensure that * the object being downloaded has not changed between the initial and subsequent requests. * * @param ex the exception which occurred while downloading (either the first response or a continuation) * @param bytesRead byte offset at which the new stream should start * @return another stream which continues to deliver the bytes from the initial request * @throws HttpDownloadContinuationException if the provided {@link IOException} is not recoverable or the number of * retries has been reached, or there is an error * @throws HttpDownloadContinuationUnexpectedResponseException if the continuation response was incompatible or * indicated that the remote object has somehow changed *//*from w ww . java 2 s .c o m*/ @Override public InputStream buildContinuation(final IOException ex, final long bytesRead) throws IOException { requireNonNull(ex); if (!isRecoverable(ex)) { throw ex; } this.continuation++; if (this.maxContinuations != INFINITE_CONTINUATIONS && this.maxContinuations <= this.continuation) { throw new HttpDownloadContinuationException( String.format("Maximum number of continuations reached [%s], aborting auto-retry: %s", this.maxContinuations, ex.getMessage()), ex); } LOG.debug( "Attempting to build a continuation for " + "[{}] request " + "to path [{}] " + "to recover at byte offset {} " + "from exception {}", this.request.getMethod(), this.request.getRequestLine().getUri(), bytesRead, ex.getMessage()); // if an IOException occurs while reading EOF the user may ask us for a continuation // starting after the last valid byte. if (bytesRead == this.marker.getTotalRangeSize()) { if (this.metricRegistry != null) { this.metricRegistry.counter(METRIC_NAME_RECOVERED_EXCEPTION_PREFIX + ex.getClass().getSimpleName()) .inc(); this.metricRegistry.counter(METRIC_NAME_RECOVERED_EOF).inc(); } return ClosedInputStream.CLOSED_INPUT_STREAM; } try { this.marker.updateRangeStart(bytesRead); } catch (final IllegalArgumentException iae) { // we should wrap and rethrow this so that the caller doesn't get stuck in a loop throw new HttpDownloadContinuationException("Failed to update download continuation offset", iae); } this.request.setHeader(RANGE, this.marker.getCurrentRange().render()); // not yet trying to handle exceptions during request execution final HttpResponse response; try { final HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(CONTEXT_ATTRIBUTE_MANTA_RETRY_DISABLE, true); response = this.client.execute(this.request, httpContext); } catch (final IOException ioe) { throw new HttpDownloadContinuationException( "Exception occurred while attempting to build continuation: " + ioe.getMessage(), ioe); } final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != SC_PARTIAL_CONTENT) { throw new HttpDownloadContinuationUnexpectedResponseException(String .format("Invalid response code: expecting [%d], got [%d]", SC_PARTIAL_CONTENT, statusCode)); } try { validateResponseWithMarker(extractDownloadResponseFingerprint(response, false)); } catch (final HttpException he) { throw new HttpDownloadContinuationUnexpectedResponseException( "Continuation request failed validation: " + he.getMessage(), he); } final InputStream content; try { final HttpEntity entity = response.getEntity(); if (entity == null) { throw new HttpDownloadContinuationUnexpectedResponseException( "Entity missing from continuation response"); } content = entity.getContent(); if (content == null) { throw new HttpDownloadContinuationUnexpectedResponseException( "Entity content missing from continuation response"); } } catch (final UnsupportedOperationException | IOException uoe) { throw new HttpDownloadContinuationUnexpectedResponseException(uoe); } if (this.metricRegistry != null) { this.metricRegistry.counter(METRIC_NAME_RECOVERED_EXCEPTION_PREFIX + ex.getClass().getSimpleName()) .inc(); } LOG.debug("Successfully constructed continuation at byte offset {} to recover from {}", bytesRead, ex); return content; }
From source file:org.apache.syncope.client.console.panels.WorkflowDirectoryPanel.java
@Override public ActionsPanel<WorkflowDefinitionTO> getActions(final IModel<WorkflowDefinitionTO> model) { final ActionsPanel<WorkflowDefinitionTO> panel = super.getActions(model); panel.add(new ActionLink<WorkflowDefinitionTO>() { private static final long serialVersionUID = -184018732772021627L; @Override/*from w ww . ja v a 2 s . com*/ public void onClick(final AjaxRequestTarget target, final WorkflowDefinitionTO ignore) { final IModel<String> wfDefinition = new Model<>(); try { wfDefinition.setObject(IOUtils.toString( restClient.getDefinition(MediaType.APPLICATION_XML_TYPE, model.getObject().getKey()))); } catch (IOException e) { LOG.error("Could not get workflow definition", e); } utility.header(Model.of(model.getObject().getKey())); utility.setContent(new XMLEditorPanel(utility, wfDefinition, false, pageRef) { private static final long serialVersionUID = -7688359318035249200L; @Override public void onSubmit(final AjaxRequestTarget target, final Form<?> form) { if (StringUtils.isNotBlank(wfDefinition.getObject())) { try { restClient.setDefinition(MediaType.APPLICATION_XML_TYPE, model.getObject().getKey(), wfDefinition.getObject()); SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED)); target.add(container); utility.show(false); utility.close(target); } catch (SyncopeClientException e) { SyncopeConsoleSession.get() .error(StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage()); } ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target); } } }); utility.show(target); target.add(utility); } }, ActionLink.ActionType.EDIT, StandardEntitlement.WORKFLOW_DEF_SET); panel.add(new ActionLink<WorkflowDefinitionTO>() { private static final long serialVersionUID = 3109256773218160485L; @Override public void onClick(final AjaxRequestTarget target, final WorkflowDefinitionTO ignore) { modal.header(Model.of(model.getObject().getKey())); modal.setContent( new ImageModalPanel<>(modal, restClient.getDiagram(model.getObject().getKey()), pageRef)); modal.show(target); target.add(modal); } }, ActionLink.ActionType.VIEW, StandardEntitlement.WORKFLOW_DEF_GET); panel.add(new ActionLink<WorkflowDefinitionTO>() { private static final long serialVersionUID = -184018732772021627L; @Override public Class<? extends Page> getPageClass() { return ModelerPopupPage.class; } @Override public PageParameters getPageParameters() { PageParameters parameters = new PageParameters(); if (modelerCtx != null) { parameters.add(Constants.MODELER_CONTEXT, modelerCtx); } parameters.add(Constants.MODEL_ID_PARAM, model.getObject().getModelId()); return parameters; } @Override protected boolean statusCondition(final WorkflowDefinitionTO modelObject) { return modelerCtx != null; } @Override public void onClick(final AjaxRequestTarget target, final WorkflowDefinitionTO ignore) { // do nothing } }, ActionLink.ActionType.WORKFLOW_MODELER, StandardEntitlement.WORKFLOW_DEF_SET); panel.add(new ActionLink<WorkflowDefinitionTO>() { private static final long serialVersionUID = -7978723352517770644L; @Override protected boolean statusCondition(final WorkflowDefinitionTO modelObject) { return !modelObject.isMain(); } @Override public void onClick(final AjaxRequestTarget target, final WorkflowDefinitionTO ignore) { try { restClient.deleteDefinition(model.getObject().getKey()); SyncopeConsoleSession.get().info(getString(Constants.OPERATION_SUCCEEDED)); target.add(container); } catch (SyncopeClientException e) { LOG.error("While deleting workflow definition {}", model.getObject().getName(), e); SyncopeConsoleSession.get() .error(StringUtils.isBlank(e.getMessage()) ? e.getClass().getName() : e.getMessage()); } ((BasePage) pageRef.getPage()).getNotificationPanel().refresh(target); } }, ActionLink.ActionType.DELETE, StandardEntitlement.WORKFLOW_DEF_DELETE, true); return panel; }
From source file:de.j4velin.wifiAutoOff.Locations.java
@Override protected void onActivityResult(int requestCode, int resultCode, final Intent data) { if (requestCode == REQUEST_LOCATION) { if (resultCode == RESULT_OK) { LatLng location = data.getParcelableExtra("location"); String locationName = "UNKNOWN"; if (Geocoder.isPresent()) { Geocoder gc = new Geocoder(this); try { List<Address> result = gc.getFromLocation(location.latitude, location.longitude, 1); if (result != null && !result.isEmpty()) { Address address = result.get(0); locationName = address.getAddressLine(0); if (address.getLocality() != null) { locationName += ", " + address.getLocality(); }//from www. j av a 2s.c o m } } catch (IOException e) { if (BuildConfig.DEBUG) Logger.log(e); e.printStackTrace(); } } Database db = Database.getInstance(this); db.addLocation(locationName, location); db.close(); locations.add(new Location(locationName, location)); mAdapter.notifyDataSetChanged(); } } else if (requestCode == REQUEST_BUY) { if (resultCode == RESULT_OK) { if (data.getIntExtra("RESPONSE_CODE", 0) == 0) { try { JSONObject jo = new JSONObject(data.getStringExtra("INAPP_PURCHASE_DATA")); PREMIUM_ENABLED = jo.getString("productId").equals("de.j4velin.wifiautomatic.billing.pro") && jo.getString("developerPayload").equals(getPackageName()); getSharedPreferences("settings", Context.MODE_PRIVATE).edit() .putBoolean("pro", PREMIUM_ENABLED).commit(); if (PREMIUM_ENABLED) { Toast.makeText(this, "Thank you!", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { if (BuildConfig.DEBUG) Logger.log(e); Toast.makeText(this, e.getClass().getName() + ": " + e.getMessage(), Toast.LENGTH_LONG) .show(); } } } } else { super.onActivityResult(requestCode, resultCode, data); } }
From source file:edu.ku.brc.specify.tools.LocalizerSearchHelper.java
/** * /*from www. j a va 2 s.co m*/ */ protected void indexSourceFiles() { if (FILE_INDEX_DIR.exists()) { try { FileUtils.deleteDirectory(FILE_INDEX_DIR); } catch (IOException e) { e.printStackTrace(); UIRegistry.displayErrorDlg( "Cannot save index to '" + FILE_INDEX_DIR + "' directory, please delete it first"); System.exit(1); } } if (!FILE_INDEX_DIR.mkdirs()) { // error } if (srcCodeFilesDir == null || !srcCodeFilesDir.exists()) { UIRegistry.displayErrorDlg( "Cannot save index to '" + srcCodeFilesDir + "' directory, please delete it first"); System.exit(1); } Date start = new Date(); try { IndexWriter writer = new IndexWriter(FSDirectory.open(FILE_INDEX_DIR), new IndexWriterConfig(Version.LUCENE_47, new StandardAnalyzer(Version.LUCENE_47))); log.debug("Indexing to directory '" + FILE_INDEX_DIR + "'..."); indexDocs(writer, srcCodeFilesDir); //log.debug("Optimizing..."); //writer.optimize(); writer.close(); Date end = new Date(); log.debug(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { log.debug(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
From source file:com.github.opensensingcity.lindt.api.QueryEndpoint.java
@OnMessage public void handleMessage(String message, Session session) throws IOException, InterruptedException { appender.putSession(Thread.currentThread(), session); try {/*from w w w . j av a 2s . c o m*/ session.getBasicRemote().sendText(gson.toJson(new Response("", "", "", true))); } catch (IOException ex) { java.util.logging.Logger.getLogger(QueryEndpoint.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } if (message.getBytes().length > 10 * Math.pow(2, 10)) { LOG.error("In this web interface request size cannot exceed 10 kB."); appender.removeSession(Thread.currentThread()); return; } Model model = ModelFactory.createDefaultModel(); try { Request request = gson.fromJson(message, Request.class); Query query = QueryFactory.create(request.query); RDFDataMgr.read(model, IOUtils.toInputStream(request.graph, "UTF-8"), base, Lang.TTL); QueryExecution ex = QueryExecutionFactory.create(query, model); Prologue pm = query.getPrologue(); pm.getPrefixMapping().setNsPrefixes(model.getNsPrefixMap()); if (query.isSelectType()) { String result = ResultSetFormatter.asText(ex.execSelect(), pm); session.getBasicRemote().sendText(gson.toJson(new Response("", result, "mappings", false))); } else if (query.isConstructType()) { StringWriter sb = new StringWriter(); Model result = ex.execConstruct(); result.setNsPrefixes(pm.getPrefixMapping()); result.write(sb, "TTL", "http://example.org/"); session.getBasicRemote().sendText(gson.toJson(new Response("", sb.toString(), "graph", false))); } } catch (IllegalArgumentException | IOException | RiotException | QueryParseException | UnsupportedOperationException ex) { LOG.error(ex.getClass().getName() + ": " + ex.getMessage()); return; } appender.removeSession(Thread.currentThread()); }
From source file:shnakkydoodle.measuring.provider.MetricsProviderSQLServer.java
/** * Create database and tables/*from w w w. j av a2 s . c o m*/ * * @param resourcePath */ private boolean ReadExecuteScript(String resourcePath) { boolean flag = false; try { InputStream in = getClass().getResourceAsStream(resourcePath); BufferedReader input = new BufferedReader(new InputStreamReader(in)); StringBuilder content = new StringBuilder(); String line; line = input.readLine(); while (line != null) { content.append(line + "\n"); line = input.readLine(); } input.close(); if (content.length() > 0) { Connection conn = null; Statement stmt = null; Class.forName("net.sourceforge.jtds.jdbc.Driver"); conn = DriverManager .getConnection(this.host + ";user=" + this.username + ";password=" + this.password); stmt = conn.createStatement(); stmt.executeUpdate(content.toString()); flag = true; stmt.close(); conn.close(); } else { System.err.println("No database metrics create tables script."); } } catch (IOException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } catch (SQLException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); e.printStackTrace(); } return flag; }