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:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 */// www  .j a  va 2  s .c  o  m
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}

From source file:com.amazonaws.eclipse.sdk.ui.AbstractSdkManager.java

/**
 * Copies the SDK given into the workspace's private state storage for this
 * plugin.//from w  ww .ja  v a 2 s . c  o m
 */
private void copySdk(AbstractSdkInstall install, IProgressMonitor monitor) {
    monitor.subTask("Copying SDK to workspace metadata");
    try {
        File sdkDir = getSDKInstallDir();
        File versionDir = new File(sdkDir, install.getVersion());

        if (versionDir.exists() && sdkInstallFactory.createSdkInstallFromDisk(versionDir).isValidSdkInstall())
            return;
        if (!versionDir.exists() && !versionDir.mkdirs())
            throw new Exception("Couldn't make SDK directory " + versionDir);

        FileUtils.copyDirectory(install.getRootDirectory(), versionDir);
        monitor.worked(20);
    } catch (IllegalStateException e) {
        JavaSdkPlugin.getDefault().getLog()
                .log(new Status(Status.WARNING, JavaSdkPlugin.PLUGIN_ID, "No state directory to cache SDK", e));
    } catch (Exception e) {
        JavaSdkPlugin.getDefault().getLog()
                .log(new Status(Status.ERROR, JavaSdkPlugin.PLUGIN_ID, e.getMessage(), e));
    }
}

From source file:org.elasticsearch.client.RestHighLevelClientTests.java

public void testParseEntity() throws IOException {
    {/*from www  . j a  va2s  .  c om*/
        IllegalStateException ise = expectThrows(IllegalStateException.class,
                () -> restHighLevelClient.parseEntity(null, null));
        assertEquals("Response body expected but not returned", ise.getMessage());
    }
    {
        IllegalStateException ise = expectThrows(IllegalStateException.class,
                () -> restHighLevelClient.parseEntity(new StringEntity("", (ContentType) null), null));
        assertEquals("Elasticsearch didn't return the [Content-Type] header, unable to parse response body",
                ise.getMessage());
    }
    {
        StringEntity entity = new StringEntity("", ContentType.APPLICATION_SVG_XML);
        IllegalStateException ise = expectThrows(IllegalStateException.class,
                () -> restHighLevelClient.parseEntity(entity, null));
        assertEquals("Unsupported Content-Type: " + entity.getContentType().getValue(), ise.getMessage());
    }
    {
        CheckedFunction<XContentParser, String, IOException> entityParser = parser -> {
            assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
            assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
            assertTrue(parser.nextToken().isValue());
            String value = parser.text();
            assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
            return value;
        };
        HttpEntity jsonEntity = new StringEntity("{\"field\":\"value\"}", ContentType.APPLICATION_JSON);
        assertEquals("value", restHighLevelClient.parseEntity(jsonEntity, entityParser));
        HttpEntity yamlEntity = new StringEntity("---\nfield: value\n", ContentType.create("application/yaml"));
        assertEquals("value", restHighLevelClient.parseEntity(yamlEntity, entityParser));
        HttpEntity smileEntity = createBinaryEntity(SmileXContent.contentBuilder(),
                ContentType.create("application/smile"));
        assertEquals("value", restHighLevelClient.parseEntity(smileEntity, entityParser));
        HttpEntity cborEntity = createBinaryEntity(CborXContent.contentBuilder(),
                ContentType.create("application/cbor"));
        assertEquals("value", restHighLevelClient.parseEntity(cborEntity, entityParser));
    }
}

From source file:de.zib.gndms.dspace.service.SliceServiceImpl.java

@Override
@RequestMapping(value = "/_{subspaceId}/_{sliceKindId}/_{sliceId}/_{fileName:.*}", method = RequestMethod.GET)
@Secured("ROLE_USER")
public ResponseEntity<Integer> listFileContent(@PathVariable final String subspaceId,
        @PathVariable final String sliceKindId, @PathVariable final String sliceId,
        @PathVariable final String fileName,
        @RequestParam(value = "attrs", required = false) final List<String> attrs,
        @RequestHeader("DN") final String dn, final OutputStream out) {
    GNDMSResponseHeader headers = setHeaders(subspaceId, sliceKindId, sliceId, dn);

    try {/*www.  java 2s .co m*/
        Subspace space = subspaceProvider.get(subspaceId);
        Slice slice = findSliceOfKind(subspaceId, sliceKindId, sliceId);
        String path = space.getPathForSlice(slice);
        File file = new File(path + File.separatorChar + fileName);

        if (out == null) {
            final IllegalStateException illegalStateException = new IllegalStateException(
                    "OutputStream not defined.");
            logger.warn(illegalStateException.getMessage());
            throw illegalStateException;
        }

        if (file.exists() && file.canRead() && file.isFile()) {
            // TODO get requested file attributes

            if (attrs == null || attrs.contains("contents")) {
                FileCopyUtils.copy(new FileInputStream(file), out);
            }

            return new ResponseEntity<Integer>(0, headers, HttpStatus.OK);
        } else {
            logger.warn("File " + file + " cannot be read or is no file.");
            return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
        }

    } catch (NoSuchElementException ne) {
        logger.warn(ne.getMessage());
        return new ResponseEntity<Integer>(0, headers, HttpStatus.NOT_FOUND);
    } catch (FileNotFoundException e) {
        logger.warn(e.getMessage());
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    } catch (IOException e) {
        logger.warn(e.getMessage());
        return new ResponseEntity<Integer>(0, headers, HttpStatus.FORBIDDEN);
    }
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

/**
 * Overridden doFilter method.//from   ww  w.  java 2 s  . c  o m
 * @param request ServletRequest representing the incoming user http(s)
 *                request.
 * @param request ServletResponse representing the associated response
 *                                that will eventually be passed on to the
 *                                next servlet.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    // Output HttpServletRequest diagnostic information
    logger.info("Request URL: " + req.getMethod() + " - " + req.getRequestURL().toString());

    doDiagnostics(req);

    try {
        boolean hasAuthToken = hasAuthToken(req.getCookies());
        Cookie internalCookie = hasAuthToken ? doCookie(req) : doHeader(req, res);
        chain.doFilter(new PastaRequestWrapper(req, internalCookie), res);
    } catch (IllegalStateException e) {
        res.setStatus(BAD_REQUEST_CODE);
        PrintWriter out = res.getWriter();
        out.println(e);
    } catch (UnauthorizedException e) {
        res.setStatus(UNAUTHORIZED_CODE);
        PrintWriter out = res.getWriter();
        out.println(e.getMessage());
    } catch (IllegalArgumentException e) {
        res.setStatus(UNAUTHORIZED_CODE);
        PrintWriter out = res.getWriter();
        out.println(e.getMessage());
    }

}

From source file:org.finra.herd.dao.IndexSearchDaoTest.java

@Test
public void indexSearchTestInvalidSearchResultIndexName() throws IOException {
    // Create a set of fields.
    final Set<String> fields = Sets.newHashSet(DISPLAY_NAME_FIELD, SHORT_DESCRIPTION_FIELD);

    // Try to call the method under test.
    try {/*from w  ww  .  j av a  2 s.  com*/
        testIndexSearch(SEARCH_TERM, fields, NO_MATCH, null, null, NO_ENABLE_HIT_HIGHLIGHTING, false, true,
                DISABLE_COLUMN_FIELDS);
        fail();
    } catch (IllegalStateException e) {
        assertEquals("Unexpected response received when attempting to retrieve search results.",
                e.getMessage());
    }

    // Verify external calls.
    verify(jsonHelper, times(2)).objectToJson(any());
}

From source file:org.apache.jackrabbit.oak.explorer.NodeStoreTree.java

@Override
public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
    if (node == null) {
        return;/*from   w  ww.  ja v a  2  s  .c  om*/
    }
    // load child nodes:
    try {
        addChildren(node);
        updateStats(node);
    } catch (IllegalStateException ex) {
        ex.printStackTrace();

        StringBuilder sb = new StringBuilder();
        sb.append(ex.getMessage());
        sb.append(newline);

        NamePathModel model = (NamePathModel) node.getUserObject();
        NodeState state = model.getState();
        String recordId = backend.getRecordId(state);
        if (recordId != null) {
            sb.append("Record ");
            sb.append(recordId);
            sb.append(newline);
        }
        setText(sb.toString());
    }
}

From source file:org.apache.phoenix.mapreduce.OrphanViewTool.java

/**
 * Examples for input arguments:/*  w  w  w .jav  a  2  s  . co  m*/
 * -c : cleans orphan views
 * -c -op /tmp/ : cleans orphan views and links, and logs their names to the files named Orphan*.txt in /tmp/
 * -i : identifies orphan views and links, and prints their names on the console
 * -i -op /tmp/ : identifies orphan views and links, and logs the name of their names to files named Orphan*.txt in /tmp/
 * -c -ip /tmp/ : cleans the views listed in files at /tmp/
 */
@Override
public int run(String[] args) throws Exception {
    Connection connection = null;
    try {
        final Configuration configuration = HBaseConfiguration.addHbaseResources(getConf());

        try {
            parseOptions(args);
        } catch (IllegalStateException e) {
            printHelpAndExit(e.getMessage(), getOptions());
        }
        if (outputPath != null) {
            // Create files to log orphan views and links
            for (int i = VIEW; i < ORPHAN_TYPE_COUNT; i++) {
                File file = new File(outputPath + fileName[i]);
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                writer[i] = new BufferedWriter(new FileWriter(file));
            }
        }
        Properties props = new Properties();
        long scn = System.currentTimeMillis() - ageMs;
        props.setProperty("CurrentSCN", Long.toString(scn));
        connection = ConnectionUtil.getInputConnection(configuration, props);
        PhoenixConnection phoenixConnection = connection.unwrap(PhoenixConnection.class);
        identifyOrphanViews(phoenixConnection);
        if (clean) {
            // Close the connection with SCN
            phoenixConnection.close();
            connection = ConnectionUtil.getInputConnection(configuration);
            phoenixConnection = connection.unwrap(PhoenixConnection.class);
            // Take a snapshot of system tables to be modified
            createSnapshot(phoenixConnection, scn);
        }
        for (Map.Entry<Key, View> entry : orphanViewSet.entrySet()) {
            try {
                dropOrLogOrphanViews(phoenixConnection, configuration, entry.getKey());
            } catch (Exception e) {
                // Ignore
            }
        }
        ;
        if (clean) {
            // Wait for the view drop tasks in the SYSTEM.TASK table to be processed
            long timeInterval = configuration.getLong(QueryServices.TASK_HANDLING_INTERVAL_MS_ATTRIB,
                    QueryServicesOptions.DEFAULT_TASK_HANDLING_INTERVAL_MS);
            Thread.sleep(maxViewLevel * timeInterval);
            // Clean up any remaining orphan view records from system tables
            for (Map.Entry<Key, View> entry : orphanViewSet.entrySet()) {
                try {
                    forcefullyDropView(phoenixConnection, entry.getKey());
                } catch (Exception e) {
                    // Ignore
                }
            }
            ;
        }
        if (inputPath == null) {
            removeOrLogOrphanLinks(phoenixConnection);
        } else {
            readAndRemoveOrphanLinks(phoenixConnection);
        }
        return 0;
    } catch (Exception ex) {
        LOG.error("Orphan View Tool : An exception occurred " + ExceptionUtils.getMessage(ex) + " at:\n"
                + ExceptionUtils.getStackTrace(ex));
        return -1;
    } finally {
        closeConnectionAndFiles(connection);
    }
}

From source file:it.greenvulcano.gvesb.api.controller.GvConfigurationControllerRest.java

@POST
@Path("/deploy/{configId}")
@RolesAllowed({ Authority.ADMINISTRATOR, Authority.MANAGER })
public void deploy(@PathParam("configId") String id) {

    try {/*from   w  w w. j  a  va  2  s .  c o  m*/
        gvConfigurationManager.deploy(id);
        gvConfigurationManager.reload();

    } catch (IllegalStateException e) {
        LOG.error("Deploy failed, a deploy is already in progress", e);
        throw new WebApplicationException(
                Response.status(Response.Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).build());

    } catch (Exception e) {
        LOG.error("Deploy failed, something bad appened", e);
        throw new WebApplicationException(
                Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build());

    }
}

From source file:org.finra.herd.dao.impl.S3DaoImplTest.java

@Test
public void testDeleteDirectoryMultiObjectDeleteException() {
    // Create an S3 file transfer request parameters DTO to access S3 objects.
    S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
    s3FileTransferRequestParamsDto.setS3BucketName(S3_BUCKET_NAME);
    s3FileTransferRequestParamsDto.setS3KeyPrefix(S3_KEY_PREFIX);

    // Create a retry policy.
    RetryPolicy retryPolicy = new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION,
            PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, INTEGER_VALUE, true);

    // Create an S3 version summary.
    S3VersionSummary s3VersionSummary = new S3VersionSummary();
    s3VersionSummary.setKey(S3_KEY);//w w w  .  j a  va 2 s. c  om
    s3VersionSummary.setVersionId(S3_VERSION_ID);

    // Create a version listing.
    VersionListing versionListing = new VersionListing();
    versionListing.setVersionSummaries(Collections.singletonList(s3VersionSummary));

    // Create a delete error.
    MultiObjectDeleteException.DeleteError deleteError = new MultiObjectDeleteException.DeleteError();
    deleteError.setKey(S3_KEY);
    deleteError.setVersionId(S3_VERSION_ID);
    deleteError.setCode(ERROR_CODE);
    deleteError.setMessage(ERROR_MESSAGE);

    // Create a multi object delete exception.
    MultiObjectDeleteException multiObjectDeleteException = new MultiObjectDeleteException(
            Collections.singletonList(deleteError), new ArrayList<>());

    // Mock the external calls.
    when(retryPolicyFactory.getRetryPolicy()).thenReturn(retryPolicy);
    when(s3Operations.listVersions(any(ListVersionsRequest.class), any(AmazonS3Client.class)))
            .thenReturn(versionListing);
    when(s3Operations.deleteObjects(any(DeleteObjectsRequest.class), any(AmazonS3Client.class)))
            .thenThrow(multiObjectDeleteException);

    // Try to call the method under test.
    try {
        s3DaoImpl.deleteDirectory(s3FileTransferRequestParamsDto);
    } catch (IllegalStateException e) {
        assertEquals(String.format(
                "Failed to delete keys/key versions with prefix \"%s\" from bucket \"%s\". Reason: One or more objects could not be deleted "
                        + "(Service: null; Status Code: 0; Error Code: null; Request ID: null; S3 Extended Request ID: null)",
                S3_KEY_PREFIX, S3_BUCKET_NAME), e.getMessage());
    }

    // Verify the external calls.
    verify(retryPolicyFactory, times(2)).getRetryPolicy();
    verify(s3Operations).listVersions(any(ListVersionsRequest.class), any(AmazonS3Client.class));
    verify(s3Operations).deleteObjects(any(DeleteObjectsRequest.class), any(AmazonS3Client.class));
    verifyNoMoreInteractionsHelper();
}