Search in sources :

Example 1 with MutableLong

use of com.helger.commons.mutable.MutableLong in project as2-lib by phax.

the class TempSharedFileInputStream method storeContentToTempFile.

/**
 * Stores the content of the input {@link InputStream} in a temporary file (in
 * the system temporary directory.
 *
 * @param aIS
 *        {@link InputStream} to read from
 * @param sName
 *        name to use in the temporary file to link it to the delivered
 *        message. May be null
 * @return The created {@link File}
 * @throws IOException
 *         in case of IO error
 */
@Nonnull
protected static File storeContentToTempFile(@Nonnull @WillClose final InputStream aIS, @Nonnull final String sName) throws IOException {
    // create temp file and write steam content to it
    // name may contain ":" on Windows and that would fail the tests!
    final String sSuffix = FilenameHelper.getAsSecureValidASCIIFilename(StringHelper.hasText(sName) ? sName : "tmp");
    final File aDestFile = File.createTempFile("AS2TempSharedFileIS", sSuffix);
    try (final FileOutputStream aOS = new FileOutputStream(aDestFile)) {
        final MutableLong aCount = new MutableLong(0);
        StreamHelper.copyByteStream().from(aIS).closeFrom(true).to(aOS).closeTo(false).copyByteCount(aCount).build();
        if (LOGGER.isInfoEnabled()) {
            // Avoid logging in tests
            if (aCount.longValue() > 1024)
                LOGGER.info(aCount.longValue() + " bytes copied to " + aDestFile.getAbsolutePath());
        }
    }
    return aDestFile;
}
Also used : MutableLong(com.helger.commons.mutable.MutableLong) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Nonnull(javax.annotation.Nonnull)

Example 2 with MutableLong

use of com.helger.commons.mutable.MutableLong in project phoss-smp by phax.

the class SMPParticipantMigrationManagerJDBC method setParticipantMigrationState.

@Nonnull
public EChange setParticipantMigrationState(@Nullable final String sParticipantMigrationID, @Nonnull final EParticipantMigrationState eNewState) {
    ValueEnforcer.notNull(eNewState, "NewState");
    final MutableLong aUpdated = new MutableLong(-1);
    final DBExecutor aExecutor = newExecutor();
    final ESuccess eSuccess = aExecutor.performInTransaction(() -> {
        // Update existing
        final long nUpdated = aExecutor.insertOrUpdateOrDelete("UPDATE smp_pmigration SET state=? WHERE id=?", new ConstantPreparedStatementDataProvider(eNewState.getID(), sParticipantMigrationID));
        aUpdated.set(nUpdated);
    });
    if (eSuccess.isFailure()) {
        // DB error
        AuditHelper.onAuditModifyFailure(SMPParticipantMigration.OT, "set-migration-state", sParticipantMigrationID, eNewState, "database-error");
        return EChange.UNCHANGED;
    }
    if (aUpdated.is0()) {
        // No such participant migration ID
        AuditHelper.onAuditModifyFailure(SMPParticipantMigration.OT, "set-migration-state", sParticipantMigrationID, "no-such-id");
        return EChange.UNCHANGED;
    }
    AuditHelper.onAuditModifySuccess(SMPParticipantMigration.OT, "set-migration-state", sParticipantMigrationID, eNewState);
    return EChange.CHANGED;
}
Also used : ESuccess(com.helger.commons.state.ESuccess) MutableLong(com.helger.commons.mutable.MutableLong) DBExecutor(com.helger.db.jdbc.executor.DBExecutor) ConstantPreparedStatementDataProvider(com.helger.db.jdbc.callback.ConstantPreparedStatementDataProvider) Nonnull(javax.annotation.Nonnull)

Example 3 with MutableLong

use of com.helger.commons.mutable.MutableLong in project ph-web by phax.

the class UnifiedResponse method _applyContent.

private void _applyContent(@Nonnull final HttpServletResponse aHttpResponse, final boolean bStatusCodeWasAlreadySet) throws IOException {
    if (m_aContentArray != null) {
        // We're having a fixed byte array of content
        final int nContentLength = m_nContentArrayLength;
        // Determine the response stream type to use
        final EResponseStreamType eResponseStreamType = ResponseHelper.getBestSuitableOutputStreamType(m_aHttpRequest);
        if (eResponseStreamType.isUncompressed()) {
            // Must be set before the content itself arrives
            // Note: Set it only if the content is uncompressed, because we cannot
            // determine the length of the compressed text in advance without
            // computational overhead
            ResponseHelper.setContentLength(aHttpResponse, nContentLength);
        }
        // Don't emit empty content or content for HEAD method
        if (nContentLength > 0 && m_eHttpMethod.isContentAllowed()) {
            // Create the correct stream
            try (final OutputStream aOS = ResponseHelper.getBestSuitableOutputStream(m_aHttpRequest, aHttpResponse)) {
                // Emit main content to stream
                aOS.write(m_aContentArray, m_nContentArrayOfs, nContentLength);
                aOS.flush();
            }
            _applyLengthChecks(nContentLength);
        }
    // Don't send 204, as this is most likely not handled correctly on the
    // client side
    } else if (m_aContentISP != null) {
        // We have a dynamic content input stream
        // -> no content length can be determined!
        final InputStream aContentIS = m_aContentISP.getInputStream();
        if (aContentIS == null) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error("Failed to open input stream from " + m_aContentISP);
            // Handle it gracefully with a 404 and not with a 500
            aHttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else {
            // Don't emit content for HEAD method
            if (m_eHttpMethod.isContentAllowed()) {
                // We do have an input stream
                // -> copy it to the response
                final OutputStream aOS = aHttpResponse.getOutputStream();
                final MutableLong aByteCount = new MutableLong(0);
                if (StreamHelper.copyByteStream().from(aContentIS).closeFrom(true).to(aOS).closeTo(true).copyByteCount(aByteCount).build().isSuccess()) {
                    // Copying succeeded
                    final long nBytesCopied = aByteCount.longValue();
                    // Don't apply additional Content-Length header after the resource
                    // was streamed!
                    _applyLengthChecks(nBytesCopied);
                } else {
                    // Copying failed -> this is a 500
                    final boolean bResponseCommitted = aHttpResponse.isCommitted();
                    logError("Copying from " + m_aContentISP + " failed after " + aByteCount.longValue() + " bytes! Response is committed: " + bResponseCommitted);
                    if (!bResponseCommitted)
                        aHttpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            }
        }
    } else if (!bStatusCodeWasAlreadySet) {
        // Set status 204 - no content; this is most likely a programming
        // error
        aHttpResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        logWarn("No content present for the response");
    }
}
Also used : MutableLong(com.helger.commons.mutable.MutableLong) IHasInputStream(com.helger.commons.io.IHasInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream)

Example 4 with MutableLong

use of com.helger.commons.mutable.MutableLong in project ph-commons by phax.

the class StreamHelperTest method testCopyInputStreamToOutputStream.

/**
 * Test method copyInputStreamToOutputStream
 */
@Test
@SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION")
public void testCopyInputStreamToOutputStream() {
    final byte[] aInput = "Hallo".getBytes(StandardCharsets.ISO_8859_1);
    final NonBlockingByteArrayInputStream aBAIS = new NonBlockingByteArrayInputStream(aInput);
    final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream();
    assertTrue(StreamHelper.copyInputStreamToOutputStream(aBAIS, aBAOS).isSuccess());
    assertArrayEquals(aInput, aBAOS.toByteArray());
    // try with null streams
    assertTrue(StreamHelper.copyInputStreamToOutputStream(aBAIS, null).isFailure());
    assertTrue(StreamHelper.copyInputStreamToOutputStream(null, aBAOS).isFailure());
    assertTrue(StreamHelper.copyInputStreamToOutputStream(aBAIS, aBAOS, new byte[10]).isSuccess());
    final MutableLong aML = new MutableLong(0);
    aBAIS.reset();
    assertTrue(StreamHelper.copyInputStreamToOutputStream(aBAIS, false, aBAOS, false, new byte[10], null, null, aML).isSuccess());
    assertEquals(aML.longValue(), aInput.length);
    // Must be a ByteArrayInputStream so that an IOException can be thrown!
    assertTrue(StreamHelper.copyInputStreamToOutputStream(new WrappedInputStream(aBAIS) {

        @Override
        public int read(final byte[] aBuf, final int nOfs, final int nLen) throws IOException {
            throw new MockIOException();
        }
    }, aBAOS).isFailure());
    // null buffer is handled internally
    StreamHelper.copyInputStreamToOutputStream(aBAIS, aBAOS, (byte[]) null);
    // empty buffer is handled internally
    StreamHelper.copyInputStreamToOutputStream(aBAIS, aBAOS, new byte[0]);
}
Also used : MutableLong(com.helger.commons.mutable.MutableLong) MockIOException(com.helger.commons.exception.mock.MockIOException) MockIOException(com.helger.commons.exception.mock.MockIOException) IOException(java.io.IOException) Test(org.junit.Test) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 5 with MutableLong

use of com.helger.commons.mutable.MutableLong in project ph-commons by phax.

the class JsonWriterTest method testMutableValues.

@Test
public void testMutableValues() {
    assertEquals("true", JsonConverter.convertToJson(new MutableBoolean(true)).getAsJsonString());
    assertEquals("0", JsonConverter.convertToJson(new MutableByte(0)).getAsJsonString());
    assertEquals("\"\\u0000\"", JsonConverter.convertToJson(new MutableChar('\0')).getAsJsonString());
    assertEquals("3.1234", JsonConverter.convertToJson(new MutableDouble(3.1234D)).getAsJsonString());
    assertEquals("3.1234", JsonConverter.convertToJson(new MutableFloat(3.1234F)).getAsJsonString());
    assertEquals("15", JsonConverter.convertToJson(new MutableInt(15)).getAsJsonString());
    assertEquals("15", JsonConverter.convertToJson(new MutableLong(15L)).getAsJsonString());
    assertEquals("15", JsonConverter.convertToJson(new MutableShort((short) 15)).getAsJsonString());
}
Also used : MutableChar(com.helger.commons.mutable.MutableChar) MutableFloat(com.helger.commons.mutable.MutableFloat) MutableLong(com.helger.commons.mutable.MutableLong) MutableByte(com.helger.commons.mutable.MutableByte) MutableDouble(com.helger.commons.mutable.MutableDouble) MutableBoolean(com.helger.commons.mutable.MutableBoolean) MutableInt(com.helger.commons.mutable.MutableInt) MutableShort(com.helger.commons.mutable.MutableShort) Test(org.junit.Test)

Aggregations

MutableLong (com.helger.commons.mutable.MutableLong)9 DBExecutor (com.helger.db.jdbc.executor.DBExecutor)3 Nonnull (javax.annotation.Nonnull)3 Test (org.junit.Test)3 MockIOException (com.helger.commons.exception.mock.MockIOException)2 MutableBoolean (com.helger.commons.mutable.MutableBoolean)2 MutableByte (com.helger.commons.mutable.MutableByte)2 MutableChar (com.helger.commons.mutable.MutableChar)2 MutableDouble (com.helger.commons.mutable.MutableDouble)2 MutableFloat (com.helger.commons.mutable.MutableFloat)2 MutableInt (com.helger.commons.mutable.MutableInt)2 MutableShort (com.helger.commons.mutable.MutableShort)2 ESuccess (com.helger.commons.state.ESuccess)2 ConstantPreparedStatementDataProvider (com.helger.db.jdbc.callback.ConstantPreparedStatementDataProvider)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 IOException (java.io.IOException)2 IHasInputStream (com.helger.commons.io.IHasInputStream)1 MutableBigDecimal (com.helger.commons.mutable.MutableBigDecimal)1 MutableBigInteger (com.helger.commons.mutable.MutableBigInteger)1 SMPDBExecutor (com.helger.phoss.smp.backend.sql.SMPDBExecutor)1