Example usage for java.lang IllegalStateException getMessage

List of usage examples for java.lang IllegalStateException getMessage

Introduction

In this page you can find the example usage for java.lang IllegalStateException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.lockss.subscription.SubscriptionManager.java

/**
 * Adds subscriptions to the system.//from   ww w . j  a  v a2  s .  c  o m
 * 
 * @param subscriptions
 *          A Collection<Subscription> with the subscriptions to be added.
 * @param status
 *          A SubscriptionOperationStatus where to return the status of the
 *          operation.
 */
public void addSubscriptions(Collection<Subscription> subscriptions, SubscriptionOperationStatus status) {
    final String DEBUG_HEADER = "addSubscriptions(): ";
    if (log.isDebug2()) {
        if (subscriptions != null) {
            log.debug2(DEBUG_HEADER + "subscriptions.size() = " + subscriptions.size());
        } else {
            log.debug2(DEBUG_HEADER + "subscriptions is null");
        }
    }

    // Force a re-calculation of the relative weights of the repositories.
    repositories = null;

    Connection conn = null;

    try {
        // Get a connection to the database.
        conn = dbManager.getConnection();
    } catch (DbException dbe) {
        log.error(CANNOT_CONNECT_TO_DB_ERROR_MESSAGE, dbe);

        for (Subscription subscription : subscriptions) {
            status.addStatusEntry(subscription.getPublication().getPublicationName(), false, dbe.getMessage(),
                    null);
        }

        if (log.isDebug2())
            log.debug(DEBUG_HEADER + "Done.");
        return;
    }

    BatchAuStatus bas;

    try {
        // Loop through all the subscriptions.
        for (Subscription subscription : subscriptions) {
            if (log.isDebug3())
                log.debug3(DEBUG_HEADER + "subscription = " + subscription);

            try {
                // Persist the subscription in the database.
                persistSubscription(conn, subscription);

                List<BibliographicPeriod> subscribedRanges = subscription.getSubscribedRanges();
                if (log.isDebug3())
                    log.debug3(DEBUG_HEADER + "subscribedRanges = " + subscribedRanges);

                // Check whether the added subscription may imply the configuration of
                // some archival unit.
                if (subscribedRanges != null && subscribedRanges.size() > 0
                        && (subscribedRanges.size() > 1 || !subscribedRanges.iterator().next().isEmpty())) {
                    // Yes: Configure the archival units that correspond to this
                    // subscription.
                    bas = configureAus(conn, subscription);
                } else {
                    bas = null;
                }

                DbManager.commitOrRollback(conn, log);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), bas);
            } catch (IllegalStateException ise) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, ise);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ise.getMessage(), null);
            } catch (IOException ioe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, ioe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ioe.getMessage(), null);
            } catch (DbException dbe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, dbe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        dbe.getMessage(), null);
            } catch (SubscriptionException se) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot add subscription " + subscription, se);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        se.getMessage(), null);
            }
        }
    } finally {
        DbManager.safeRollbackAndClose(conn);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}

From source file:org.lockss.subscription.SubscriptionManager.java

/**
 * Updates existing subscriptions./*w w  w . j  av a  2  s.  c om*/
 * 
 * @param subscriptions
 *          A Collection<Subscription> with the subscriptions to be updated.
 * @param status
 *          A SubscriptionOperationStatus where to return the status of the
 *          operation.
 */
public void updateSubscriptions(Collection<Subscription> subscriptions, SubscriptionOperationStatus status) {
    final String DEBUG_HEADER = "updateSubscriptions(): ";
    if (log.isDebug2()) {
        if (subscriptions != null) {
            log.debug2(DEBUG_HEADER + "subscriptions.size() = " + subscriptions.size());
        } else {
            log.debug2(DEBUG_HEADER + "subscriptions is null");
        }
    }

    // Force a re-calculation of the relative weights of the repositories.
    repositories = null;

    Connection conn = null;

    try {
        // Get a connection to the database.
        conn = dbManager.getConnection();
    } catch (DbException dbe) {
        log.error(CANNOT_CONNECT_TO_DB_ERROR_MESSAGE, dbe);

        for (Subscription subscription : subscriptions) {
            status.addStatusEntry(subscription.getPublication().getPublicationName(), false, dbe.getMessage(),
                    null);
        }

        if (log.isDebug2())
            log.debug(DEBUG_HEADER + "Done.");
        return;
    }

    BatchAuStatus bas;

    try {
        // Loop through all the subscriptions.
        for (Subscription subscription : subscriptions) {
            if (log.isDebug3())
                log.debug3(DEBUG_HEADER + "subscription = " + subscription);

            try {
                // Update the subscription in the database.
                updateSubscription(conn, subscription);

                List<BibliographicPeriod> subscribedRanges = subscription.getSubscribedRanges();
                if (log.isDebug3())
                    log.debug3(DEBUG_HEADER + "subscribedRanges = " + subscribedRanges);

                // Check whether the updated subscription may imply the configuration
                // of some archival unit.
                if (subscribedRanges != null && subscribedRanges.size() > 0
                        && (subscribedRanges.size() > 1 || !subscribedRanges.iterator().next().isEmpty())) {
                    // Yes: Configure the archival units that correspond to this
                    // subscription.
                    bas = configureAus(conn, subscription);
                } else {
                    bas = null;
                }

                DbManager.commitOrRollback(conn, log);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), bas);
            } catch (IllegalStateException ise) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, ise);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ise.getMessage(), null);
            } catch (IOException ioe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, ioe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        ioe.getMessage(), null);
            } catch (DbException dbe) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, dbe);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        dbe.getMessage(), null);
            } catch (SubscriptionException se) {
                try {
                    if ((conn != null) && !conn.isClosed()) {
                        conn.rollback();
                    }
                } catch (SQLException sqle) {
                    log.error(CANNOT_ROLL_BACK_DB_CONNECTION_ERROR_MESSAGE, sqle);
                }
                log.error("Cannot update subscription " + subscription, se);
                status.addStatusEntry(subscription.getPublication().getPublicationName(), false,
                        se.getMessage(), null);
            }
        }
    } finally {
        DbManager.safeRollbackAndClose(conn);
    }

    if (log.isDebug2())
        log.debug2(DEBUG_HEADER + "Done.");
}

From source file:com.serenegiant.media.TLMediaEncoder.java

/**
 * drain encoded data and write them to intermediate file
 *//*from   w  w  w  . j  a  v a 2 s . com*/
protected void drain() {
    if (mMediaCodec == null)
        return;
    int encoderStatus;
    while (mIsRunning && (mState == STATE_RUNNING)) {
        // get encoded data with maximum timeout duration of TIMEOUT_USEC(=10[msec])
        try {
            encoderStatus = mMediaCodec.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
        } catch (IllegalStateException e) {
            break;
        }
        if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
            // wait 5 counts(=TIMEOUT_USEC x 5 = 50msec) until data/EOS come
            if (!mIsEOS) {
                break; // out of while
            }
        } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
            if (DEBUG)
                Log.v(TAG, "INFO_OUTPUT_BUFFERS_CHANGED");
            // this should not come when encoding
            encoderOutputBuffers = mMediaCodec.getOutputBuffers();
        } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
            if (DEBUG)
                Log.v(TAG, "INFO_OUTPUT_FORMAT_CHANGED");
            // this status indicate the output format of codec is changed
            // this should come only once before actual encoded data
            // but this status never come on Android4.3 or less
            // and in that case, you should treat when MediaCodec.BUFFER_FLAG_CODEC_CONFIG come.
            // get output format from codec and pass them to muxer
            // getOutputFormat should be called after INFO_OUTPUT_FORMAT_CHANGED otherwise crash.
            if (mSequence == 0) { // sequence 0 is for saving MediaFormat
                final MediaFormat format = mMediaCodec.getOutputFormat(); // API >= 16
                try {
                    writeFormat(mCurrentOutputStream, mConfigFormat, format);
                    //                  changeOutputStream();
                } catch (IOException e) {
                    Log.e(TAG, "drain:failed to write MediaFormat ", e);
                }
            }
        } else if (encoderStatus < 0) {
            // unexpected status
            if (DEBUG)
                Log.w(TAG, "drain:unexpected result from encoder#dequeueOutputBuffer: " + encoderStatus);
        } else {
            final ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
            if (encodedData == null) {
                // this never should come...may be a MediaCodec internal error
                throw new RuntimeException("encoderOutputBuffer " + encoderStatus + " was null");
            }
            if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                // You should set output format to muxer here when you target Android4.3 or less
                // but MediaCodec#getOutputFormat can not call here(because INFO_OUTPUT_FORMAT_CHANGED don't come yet)
                // therefor we should expand and prepare output format from buffer data.
                // This sample is for API>=18(>=Android 4.3), just ignore this flag here
                if (DEBUG)
                    Log.d(TAG, "drain:BUFFER_FLAG_CODEC_CONFIG");
                mBufferInfo.size = 0;
            }

            if (mBufferInfo.size != 0) {
                mFrameCounts++;
                if (mCurrentOutputStream == null) {
                    throw new RuntimeException("drain:temporary file not ready");
                }
                // write encoded data to muxer(need to adjust presentationTimeUs.
                mBufferInfo.presentationTimeUs = getPTSUs();
                try {
                    writeStream(mCurrentOutputStream, mSequence, mFrameCounts, mBufferInfo, encodedData,
                            writeBuffer);
                } catch (IOException e) {
                    throw new RuntimeException("drain:failed to writeStream:" + e.getMessage());
                }
                prevOutputPTSUs = mBufferInfo.presentationTimeUs;
            }
            // return buffer to encoder
            mMediaCodec.releaseOutputBuffer(encoderStatus, false);
            if ((mNumFrames > 0) && (mFrameCounts >= mNumFrames)) {
                setState(STATE_PAUSING, null); // request pause
            }
            if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                // when EOS come.
                mIsRunning = false;
                break; // out of while
            }
        }
    }
}

From source file:org.apache.openjpa.kernel.BrokerImpl.java

public Object newInstance(Class cls) {
    assertOpen();/*  www  . j  a  v a 2s.c  o  m*/

    if (!cls.isInterface() && Modifier.isAbstract(cls.getModifiers()))
        throw new UnsupportedOperationException(_loc.get("new-abstract", cls).getMessage());

    // 1.5 doesn't initialize classes without a true Class.forName
    if (!PCRegistry.isRegistered(cls)) {
        try {
            Class.forName(cls.getName(), true,
                    AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls)));
        } catch (Throwable t) {
        }
    }

    if (_repo.getMetaData(cls, getClassLoader(), false) == null)
        throw new IllegalArgumentException(_loc.get("no-interface-metadata", cls.getName()).getMessage());

    try {
        return PCRegistry.newInstance(cls, null, false);
    } catch (IllegalStateException ise) {
        IllegalArgumentException iae = new IllegalArgumentException(ise.getMessage());
        iae.setStackTrace(ise.getStackTrace());
        throw iae;
    }
}

From source file:org.finra.herd.service.BusinessObjectFormatServiceTest.java

@Test
public void testUpdateBusinessObjectFormatAlreadyExistingDuplicateAttributes() {
    // Create and persist a business object format with duplicate attributes.
    businessObjectFormatDaoTestHelper.createBusinessObjectFormatEntity(NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE,
            FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, FORMAT_DESCRIPTION, FORMAT_DOCUMENT_SCHEMA,
            FORMAT_DOCUMENT_SCHEMA_URL, LATEST_VERSION_FLAG_SET, PARTITION_KEY, NO_PARTITION_KEY_GROUP,
            Arrays.asList(new Attribute(ATTRIBUTE_NAME_1_MIXED_CASE.toLowerCase(), ATTRIBUTE_VALUE_1),
                    new Attribute(ATTRIBUTE_NAME_1_MIXED_CASE.toUpperCase(), ATTRIBUTE_VALUE_2)));

    // Try to update a business object format instance that already has duplicate attributes.
    try {/*from   w w  w.j  a v a  2  s . c  o m*/
        businessObjectFormatService.updateBusinessObjectFormat(
                new BusinessObjectFormatKey(NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE,
                        FORMAT_VERSION),
                businessObjectFormatServiceTestHelper.createBusinessObjectFormatUpdateRequest(
                        FORMAT_DESCRIPTION_2, FORMAT_DOCUMENT_SCHEMA_2, FORMAT_DOCUMENT_SCHEMA_URL,
                        Arrays.asList(
                                new Attribute(ATTRIBUTE_NAME_3_MIXED_CASE.toLowerCase(), ATTRIBUTE_VALUE_3)),
                        businessObjectFormatServiceTestHelper.getTestSchema2()));
        fail("Should throw an IllegalStateException when business object format has duplicate attributes.");
    } catch (IllegalStateException e) {
        assertEquals(
                String.format("Found duplicate attribute with name \"%s\" for business object format {%s}.",
                        ATTRIBUTE_NAME_1_MIXED_CASE.toLowerCase(),
                        businessObjectFormatServiceTestHelper.getExpectedBusinessObjectFormatKeyAsString(
                                NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE,
                                FORMAT_VERSION)),
                e.getMessage());
    }
}

From source file:org.apache.tinkerpop.gremlin.giraph.process.computer.GiraphGraphComputer.java

@Override
public int run(final String[] args) {
    final Storage storage = FileSystemStorage.open(this.giraphConfiguration);
    storage.rm(this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
    this.giraphConfiguration.setBoolean(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES,
            this.persist.equals(Persist.EDGES));
    try {//from  w w w.j a v a2 s  . c  o m
        // store vertex and edge filters (will propagate down to native InputFormat or else GiraphVertexInputFormat will process)
        final BaseConfiguration apacheConfiguration = new BaseConfiguration();
        apacheConfiguration.setDelimiterParsingDisabled(true);
        GraphFilterAware.storeGraphFilter(apacheConfiguration, this.giraphConfiguration, this.graphFilter);

        // it is possible to run graph computer without a vertex program (and thus, only map reduce jobs if they exist)
        if (null != this.vertexProgram) {
            // a way to verify in Giraph whether the traversal will go over the wire or not
            try {
                VertexProgram.createVertexProgram(this.hadoopGraph,
                        ConfUtil.makeApacheConfiguration(this.giraphConfiguration));
            } catch (final IllegalStateException e) {
                if (e.getCause() instanceof NumberFormatException)
                    throw new NotSerializableException(
                            "The provided traversal is not serializable and thus, can not be distributed across the cluster");
            }
            // remove historic combiners in configuration propagation (this occurs when job chaining)
            if (!this.vertexProgram.getMessageCombiner().isPresent())
                this.giraphConfiguration.unset(GiraphConstants.MESSAGE_COMBINER_CLASS.getKey());
            // split required workers across system (open map slots + max threads per machine = total amount of TinkerPop workers)
            if (!this.useWorkerThreadsInConfiguration) {
                final Cluster cluster = new Cluster(GiraphGraphComputer.this.giraphConfiguration);
                int totalMappers = cluster.getClusterStatus().getMapSlotCapacity() - 1; // 1 is needed for master
                cluster.close();
                if (this.workers <= totalMappers) {
                    this.giraphConfiguration.setWorkerConfiguration(this.workers, this.workers, 100.0F);
                    this.giraphConfiguration.setNumComputeThreads(1);
                } else {
                    if (totalMappers == 0)
                        totalMappers = 1; // happens in local mode
                    int threadsPerMapper = Long
                            .valueOf(Math.round((double) this.workers / (double) totalMappers)).intValue(); // TODO: need to find least common denominator
                    this.giraphConfiguration.setWorkerConfiguration(totalMappers, totalMappers, 100.0F);
                    this.giraphConfiguration.setNumComputeThreads(threadsPerMapper);
                }
            }
            // prepare the giraph vertex-centric computing job
            final GiraphJob job = new GiraphJob(this.giraphConfiguration,
                    Constants.GREMLIN_HADOOP_GIRAPH_JOB_PREFIX + this.vertexProgram);
            job.getInternalJob().setJarByClass(GiraphGraphComputer.class);
            this.logger.info(Constants.GREMLIN_HADOOP_GIRAPH_JOB_PREFIX + this.vertexProgram);
            // handle input paths (if any)
            String inputLocation = this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION, null);
            if (null != inputLocation && FileInputFormat.class.isAssignableFrom(this.giraphConfiguration
                    .getClass(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT, InputFormat.class))) {
                inputLocation = Constants.getSearchGraphLocation(inputLocation, storage)
                        .orElse(this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION));
                FileInputFormat.setInputPaths(job.getInternalJob(), new Path(inputLocation));
            }
            // handle output paths (if any)
            String outputLocation = this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION,
                    null);
            if (null != outputLocation && FileOutputFormat.class.isAssignableFrom(this.giraphConfiguration
                    .getClass(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT, OutputFormat.class))) {
                outputLocation = Constants.getGraphLocation(
                        this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
                FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(outputLocation));
            }
            // execute the job and wait until it completes (if it fails, throw an exception)
            if (!job.run(true))
                throw new IllegalStateException(
                        "The GiraphGraphComputer job failed -- aborting all subsequent MapReduce jobs: "
                                + job.getInternalJob().getStatus().getFailureInfo());
            // add vertex program memory values to the return memory
            for (final MemoryComputeKey memoryComputeKey : this.vertexProgram.getMemoryComputeKeys()) {
                if (!memoryComputeKey.isTransient() && storage.exists(Constants.getMemoryLocation(
                        this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                        memoryComputeKey.getKey()))) {
                    final ObjectWritableIterator iterator = new ObjectWritableIterator(this.giraphConfiguration,
                            new Path(Constants.getMemoryLocation(
                                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                                    memoryComputeKey.getKey())));
                    if (iterator.hasNext()) {
                        this.memory.set(memoryComputeKey.getKey(), iterator.next().getValue());
                    }
                    // vertex program memory items are not stored on disk
                    storage.rm(Constants.getMemoryLocation(
                            this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                            memoryComputeKey.getKey()));
                }
            }
            final Path path = new Path(Constants.getMemoryLocation(
                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                    Constants.HIDDEN_ITERATION));
            this.memory.setIteration(
                    (Integer) new ObjectWritableIterator(this.giraphConfiguration, path).next().getValue());
            storage.rm(Constants.getMemoryLocation(
                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                    Constants.HIDDEN_ITERATION));
        }
        // do map reduce jobs
        this.giraphConfiguration.setBoolean(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT_HAS_EDGES,
                this.giraphConfiguration.getBoolean(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES,
                        true));
        for (final MapReduce mapReduce : this.mapReducers) {
            this.memory.addMapReduceMemoryKey(mapReduce);
            MapReduceHelper.executeMapReduceJob(mapReduce, this.memory, this.giraphConfiguration);
        }

        // if no persistence, delete the graph and memory output
        if (this.persist.equals(Persist.NOTHING))
            storage.rm(this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
    } catch (final Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    return 0;
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageManagerResource.java

/**
 * <strong>Read Evaluate Report</strong> operation, specifying the
 * <em>transaction identifier</em> of the evaluate quality report document
 * to be read in the URI./*from  ww w.  jav  a2  s . c o m*/
 * 
 * <p>
 * If an HTTP Accept header with value 'text/html' is included in the
 * request, returns an HTML representation of the report. The default
 * representation is XML.
 * </p>
 * 
 * <p>
 * See the <code>Evaluate Data Package</code> service method for information
 * about how to obtain the transaction id.
 * </p>
 * 
 * <h4>Requests:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Request</b></th>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td><em>XML representation: </em><code>curl -i -X GET
 * https://pasta.lternet.edu/package/evaluate/report/eml/1364424858431</code>
 * </td>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td><em>HTML representation: </em>
 * <code>curl -i -H "Accept: text/html" -X GET
 * https://pasta.lternet.edu/package/evaluate/report/eml/31364424858431</code>
 * </td>
 * </tr>
 * </table>
 * 
 * <h4>Responses:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Status</b></th>
 * <th><b>Reason</b></th>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Message Body</b></th>
 * </tr>
 * <tr>
 * <td align=center>200 OK</td>
 * <td align=center>The request to read the quality report was successful</td>
 * <td align=center>The quality report document that describes the data
 * package</td>
 * <td align=center><code>application/xml</code> or <code>text/html</code></td>
 * <td>
 * 
 * <pre>
 * &lt;?xml version="1.0" encoding="UTF-8"?&gt;
 * &lt;qualityReport&gt;
 *   &lt;packageId&gt;knb-lter-lno.1.1&lt;/packageId&gt;
 * .
 * .
 * .
 * &lt;/qualityReport&gt;
 * </pre>
 * 
 * </td>
 * </tr>
 * <tr>
 * <td align=center>400 Bad Request</td>
 * <td align=center>The request contains an error, such as an illegal
 * identifier or revision value</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>401 Unauthorized</td>
 * <td align=center>The requesting user is not authorized to read the
 * specified data package</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>404 Not Found</td>
 * <td align=center>No data package matching the specified scope,
 * identifier, and revision values is found</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>405 Method Not Allowed</td>
 * <td align=center>The specified HTTP method is not allowed for the
 * requested resource</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>500 Internal Server Error</td>
 * <td align=center>The server encountered an unexpected condition which
 * prevented it from fulfilling the request</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * </table>
 * 
 * @param scope
 *            The scope of the data package
 * @param identifier
 *            The identifier of the data package
 * @param revision
 *            The revision of the data package
 * @param transaction
 *            The transaction identifier, e.g. "1364424858431"
 * @return A Response object containing the evaluate quality report
 */
@GET
@Path("/evaluate/report/eml/{transaction}")
@Produces({ "application/xml", "text/html" })
public Response readEvaluateReport(@Context HttpHeaders headers, @PathParam("transaction") String transaction) {
    AuthToken authToken = null;
    boolean produceHTML = false;
    final String serviceMethodName = "readEvaluateReport";
    Rule.Permission permission = Rule.Permission.read;
    String resourceId = "";
    String entryText = null;

    /*
     * Determine whether to produce an HTML representation
     */
    List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
    for (MediaType mediaType : mediaTypes) {
        String mediaTypeStr = mediaType.toString();
        if (mediaTypeStr.equals(MediaType.TEXT_HTML)) {
            produceHTML = true;
        }
    }

    ResponseBuilder responseBuilder = null;
    Response response = null;
    EmlPackageIdFormat emlPackageIdFormat = new EmlPackageIdFormat();
    authToken = getAuthToken(headers);
    String userId = authToken.getUserId();

    // Is user authorized to run the service method?
    boolean serviceMethodAuthorized = isServiceMethodAuthorized(serviceMethodName, permission, authToken);
    if (!serviceMethodAuthorized) {
        throw new UnauthorizedException(
                "User " + userId + " is not authorized to execute service method " + serviceMethodName);
    }

    try {
        DataPackageManager dataPackageManager = new DataPackageManager();

        File xmlFile = dataPackageManager.readEvaluateReport(transaction);

        if (xmlFile != null && xmlFile.exists()) {
            if (produceHTML) {
                Options options = ConfigurationListener.getOptions();
                String xslPath = null;
                if (options != null) {
                    xslPath = options.getOption("datapackagemanager.xslPath");
                }

                try {
                    String xmlString = FileUtility.fileToString(xmlFile);
                    String htmlResult = qualityReportXMLtoHTML(xmlString, xslPath);
                    responseBuilder = Response.ok(htmlResult);
                    if (responseBuilder != null) {
                        response = responseBuilder.build();
                    }
                } catch (IllegalStateException e) {
                    entryText = e.getMessage();
                    WebApplicationException webApplicationException = WebExceptionFactory
                            .make(Response.Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
                    response = webApplicationException.getResponse();
                }
            } else {
                responseBuilder = Response.ok(xmlFile);
                if (responseBuilder != null) {
                    response = responseBuilder.build();
                }
            }
        } else {
            ResourceNotFoundException e = new ResourceNotFoundException(String.format(
                    "Unable to access data package evaluate report file for transaction id: %s ", transaction));
            WebApplicationException webApplicationException = WebExceptionFactory.makeNotFound(e);
            entryText = e.getMessage();
            response = webApplicationException.getResponse();
        }
    } catch (IllegalArgumentException e) {
        entryText = e.getMessage();
        response = WebExceptionFactory.makeBadRequest(e).getResponse();
    } catch (UnauthorizedException e) {
        entryText = e.getMessage();
        response = WebExceptionFactory.makeUnauthorized(e).getResponse();
    } catch (Exception e) {
        entryText = e.getMessage();
        WebApplicationException webApplicationException = WebExceptionFactory
                .make(Response.Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
        response = webApplicationException.getResponse();
    }

    audit(serviceMethodName, authToken, response, resourceId, entryText);
    response = stampHeader(response);
    return response;
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageManagerResource.java

/**
 * <strong>Read Data Package Report</strong> operation, specifying the
 * scope, identifier, and revision of the data package quality report
 * document to be read in the URI.//from  w ww.  j a v  a2s  . c  o  m
 * 
 * <p>
 * If an HTTP Accept header with value 'text/html' is included in the
 * request, returns an HTML representation of the report. The default
 * representation is XML.
 * </p>
 * 
 * <h4>Requests:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Request</b></th>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td><em>XML representation: </em><code>curl -i -X GET
 * https://pasta.lternet.edu/package/report/eml/knb-lter-lno/1/3</code></td>
 * </tr>
 * <tr>
 * <td align=center>none</td>
 * <td align=center>none</td>
 * <td><em>HTML representation: </em>
 * <code>curl -i -X GET -H "Accept: text/html"
 * https://pasta.lternet.edu/package/report/eml/knb-lter-lno/1/3</code></td>
 * </tr>
 * </table>
 * 
 * <h4>Responses:</h4>
 * <table border="1" cellspacing="0" cellpadding="3">
 * <tr>
 * <th><b>Status</b></th>
 * <th><b>Reason</b></th>
 * <th><b>Message Body</b></th>
 * <th><b>MIME type</b></th>
 * <th><b>Sample Message Body</b></th>
 * </tr>
 * <tr>
 * <td align=center>200 OK</td>
 * <td align=center>The request to read the quality report was successful</td>
 * <td align=center>The quality report document that describes the data
 * package</td>
 * <td align=center><code>application/xml</code> or <code>text/html</code></td>
 * <td>
 * 
 * <pre>
 * &lt;?xml version="1.0" encoding="UTF-8"?&gt;
 * &lt;qualityReport&gt;
 *   &lt;packageId&gt;knb-lter-lno.1.3&lt;/packageId&gt;
 * .
 * .
 * .
 * &lt;/qualityReport&gt;
 * </pre>
 * 
 * </td>
 * </tr>
 * <tr>
 * <td align=center>400 Bad Request</td>
 * <td align=center>The request contains an error, such as an illegal
 * identifier or revision value</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>401 Unauthorized</td>
 * <td align=center>The requesting user is not authorized to read the
 * specified data package</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>404 Not Found</td>
 * <td align=center>No data package matching the specified scope,
 * identifier, and revision values is found</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>405 Method Not Allowed</td>
 * <td align=center>The specified HTTP method is not allowed for the
 * requested resource</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * <tr>
 * <td align=center>500 Internal Server Error</td>
 * <td align=center>The server encountered an unexpected condition which
 * prevented it from fulfilling the request</td>
 * <td align=center>An error message</td>
 * <td align=center><code>text/plain</code></td>
 * <td align=center><code>Error message</code></td>
 * </tr>
 * </table>
 * 
 * @param scope
 *            The scope of the data package
 * @param identifier
 *            The identifier of the data package
 * @param revision
 *            The revision of the data package
 * @return A Response object containing the data package quality report
 */
@GET
@Path("/report/eml/{scope}/{identifier}/{revision}")
@Produces({ "application/xml", "text/html" })
public Response readDataPackageReport(@Context HttpHeaders headers, @PathParam("scope") String scope,
        @PathParam("identifier") Integer identifier, @PathParam("revision") String revision) {
    AuthToken authToken = null;
    boolean produceHTML = false;
    final String serviceMethodName = "readDataPackageReport";
    Rule.Permission permission = Rule.Permission.read;
    String resourceId = null;
    String entryText = null;

    /*
     * Determine whether to produce an HTML representation
     */
    List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
    for (MediaType mediaType : mediaTypes) {
        String mediaTypeStr = mediaType.toString();
        if (mediaTypeStr.equals(MediaType.TEXT_HTML)) {
            produceHTML = true;
        }
    }

    ResponseBuilder responseBuilder = null;
    Response response = null;
    EmlPackageIdFormat emlPackageIdFormat = new EmlPackageIdFormat();
    authToken = getAuthToken(headers);
    String userId = authToken.getUserId();

    // Is user authorized to run the service method?
    boolean serviceMethodAuthorized = isServiceMethodAuthorized(serviceMethodName, permission, authToken);
    if (!serviceMethodAuthorized) {
        throw new UnauthorizedException(
                "User " + userId + " is not authorized to execute service method " + serviceMethodName);
    }

    try {
        DataPackageManager dataPackageManager = new DataPackageManager();
        EmlPackageId emlPackageId = emlPackageIdFormat.parse(scope, identifier.toString(), revision);
        String packageId = emlPackageIdFormat.format(emlPackageId);

        /*
         * Isolate the resourceId for the report so that its value can be
         * recorded in the audit log
         */
        Integer revisionInt = new Integer(revision);
        ArrayList<String> resources = dataPackageManager.getDataPackageResources(scope, identifier,
                revisionInt);
        if (resources != null && resources.size() > 0) {
            for (String resource : resources) {
                if (resource != null && resource.contains("/package/report/eml")) {
                    resourceId = resource;
                }
            }
        }

        File xmlFile = dataPackageManager.readDataPackageReport(scope, identifier, revision, emlPackageId,
                authToken, userId);

        if (xmlFile != null && xmlFile.exists()) {
            if (produceHTML) {
                Options options = ConfigurationListener.getOptions();
                String xslPath = null;
                if (options != null) {
                    xslPath = options.getOption("datapackagemanager.xslPath");
                }

                try {
                    String xmlString = FileUtility.fileToString(xmlFile);
                    String htmlResult = qualityReportXMLtoHTML(xmlString, xslPath);
                    responseBuilder = Response.ok(htmlResult);
                    if (responseBuilder != null) {
                        response = responseBuilder.build();
                    }
                } catch (IllegalStateException e) {
                    entryText = e.getMessage();
                    WebApplicationException webApplicationException = WebExceptionFactory
                            .make(Response.Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
                    response = webApplicationException.getResponse();
                }
            } else {
                responseBuilder = Response.ok(xmlFile);
                if (responseBuilder != null) {
                    response = responseBuilder.build();
                }
            }
        } else {
            ResourceNotFoundException e = new ResourceNotFoundException(
                    "Unable to access data package quality report file for packageId: " + packageId);
            WebApplicationException webApplicationException = WebExceptionFactory.makeNotFound(e);
            entryText = e.getMessage();
            response = webApplicationException.getResponse();
        }
    } catch (IllegalArgumentException e) {
        entryText = e.getMessage();
        response = WebExceptionFactory.makeBadRequest(e).getResponse();
    } catch (UnauthorizedException e) {
        entryText = e.getMessage();
        response = WebExceptionFactory.makeUnauthorized(e).getResponse();
    } catch (Exception e) {
        entryText = e.getMessage();
        WebApplicationException webApplicationException = WebExceptionFactory
                .make(Response.Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
        response = webApplicationException.getResponse();
    }

    audit(serviceMethodName, authToken, response, resourceId, entryText);
    response = stampHeader(response);
    return response;
}

From source file:org.sakaiproject.assignment.impl.BaseAssignmentService.java

/**
 * this is to mimic the Xml.decodeAttribute
 * @param el// w ww.j a  va  2  s .co m
 * @param tag
 * @return
 */
protected String xmlDecodeAttribute(Attributes attributes, String tag) {
    String charset = StringUtils.trimToNull(attributes.getValue("charset"));
    if (charset == null)
        charset = "UTF-8";

    String body = StringUtils.trimToNull(attributes.getValue(tag));
    if (body != null) {
        try {
            byte[] decoded = Base64.decodeBase64(body); // UTF-8 by default
            body = org.apache.commons.codec.binary.StringUtils.newString(decoded, charset);
        } catch (IllegalStateException e) {
            M_log.warn(" XmlDecodeAttribute: " + e.getMessage() + " tag=" + tag);
        }
    }

    if (body == null)
        body = "";

    return body;
}