Example usage for java.lang Exception getCause

List of usage examples for java.lang Exception getCause

Introduction

In this page you can find the example usage for java.lang Exception getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.app.inventario.controlador.Controlador.java

@RequestMapping(value = "/agregar-proveedor", method = RequestMethod.POST)
public @ResponseBody Map agregarProveedor(@ModelAttribute("proveedor") Proveedor proveedor,
        HttpServletRequest request, HttpServletResponse response) {
    Map map = new HashMap();
    try {/* w  w w . j  a  v  a2s. c  o m*/
        proveedorServicio.guardar(proveedor);
        response.setStatus(HttpServletResponse.SC_OK);
        map.put("Status", "OK");
        map.put("Message", "Agregado Correctamente");
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        map.put("Status", "FAIL");
        map.put("Message", ex.getCause().getCause().getCause().getMessage());
    }
    return map;
}

From source file:com.sisrni.managedbean.RolesMB.java

public void editar() throws Exception {
    try {/* w  w  w  .j  a va 2 s.c  om*/
        rolesService.getDao().merge(ssRoles);
        getRoles();
        RequestContext.getCurrentInstance().update("formAdmin");
        RequestContext.getCurrentInstance().update("formRol");
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error class RolesOpcionesMB - Editar()\n" + e.getMessage(), e.getCause());
    } finally {
        this.ssRoles = null;
        this.ssRoles = new SsRoles();
        setActualizar(false);
    }
}

From source file:com.mweagle.tereus.commands.CreateCommand.java

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "DM_EXIT", "OBL_UNSATISFIED_OBLIGATION" })
@SuppressWarnings("unchecked")
@Override//from  w  w  w.  j a v a  2  s  . com
public void run() {
    int exitCode = 0;
    try {
        final String argumentJSON = (null != this.jsonParamAndTagsPath)
                ? new String(Files.readAllBytes(Paths.get(this.jsonParamAndTagsPath)), Charsets.UTF_8)
                : null;

        Map<String, Object> jsonJavaRootObject = (null != argumentJSON)
                ? new Gson().fromJson(argumentJSON, Map.class)
                : Collections.emptyMap();
        Map<String, Object> parameters = (Map<String, Object>) jsonJavaRootObject
                .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.PARAMETERS, new HashMap<>());
        final String jsonS3BucketName = ((String) parameters
                .getOrDefault(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, "")).trim();
        final String cliS3BucketName = (null == this.s3BucketName) ? "" : this.s3BucketName.trim();

        if (!jsonS3BucketName.isEmpty() && !cliS3BucketName.isEmpty()) {
            final String msg = String.format("S3 bucketname defined in both %s and via command line argument",
                    this.jsonParamAndTagsPath);
            throw new IllegalArgumentException(msg);
        } else if (!cliS3BucketName.isEmpty()) {
            parameters.put(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, cliS3BucketName);
        }

        Map<String, Object> tags = (Map<String, Object>) jsonJavaRootObject
                .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.TAGS, Collections.emptyMap());

        TereusInput tereusInput = new TereusInput(this.stackTemplatePath, this.region, parameters, tags,
                this.dryRun);

        Optional<OutputStream> osSink = Optional.empty();
        try {
            if (null != this.outputFilePath) {
                final Path outputPath = Paths.get(this.outputFilePath);
                osSink = Optional.of(new FileOutputStream(outputPath.toFile()));
            }
            this.create(tereusInput, osSink);
        } catch (Exception ex) {
            LogManager.getLogger().error(ex.getCause());
            exitCode = 2;
        } finally {
            if (osSink.isPresent()) {
                try {
                    osSink.get().close();
                } catch (Exception e) {
                    // NOP
                }
            }
        }
    } catch (Exception ex) {
        LogManager.getLogger().error(ex);
        Help.help(this.helpOption.commandMetadata);
        exitCode = 1;
    }
    System.exit(exitCode);
}

From source file:Thumbnail.java

/**
* Reads an image in a file and creates a thumbnail in another file.
* largestDimension is the largest dimension of the thumbnail, the other dimension is scaled accordingly.
* Utilises weighted stepping method to gradually reduce the image size for better results,
* i.e. larger steps to start with then smaller steps to finish with.
* Note: always writes a JPEG because GIF is protected or something - so always make your outFilename end in 'jpg'.
* PNG's with transparency are given white backgrounds
*//*w  w w.  j av a2 s  . c o  m*/
public String createThumbnail(String inFilename, String outFilename, int largestDimension) {
    try {
        double scale;
        int sizeDifference, originalImageLargestDim;
        if (!inFilename.endsWith(".jpg") && !inFilename.endsWith(".jpeg") && !inFilename.endsWith(".gif")
                && !inFilename.endsWith(".png")) {
            return "Error: Unsupported image type, please only either JPG, GIF or PNG";
        } else {
            Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
            if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
                return "Error loading file: \"" + inFilename + "\"";
            } else {
                //find biggest dimension       
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) largestDimension / (double) inImage.getWidth(null);
                    sizeDifference = inImage.getWidth(null) - largestDimension;
                    originalImageLargestDim = inImage.getWidth(null);
                } else {
                    scale = (double) largestDimension / (double) inImage.getHeight(null);
                    sizeDifference = inImage.getHeight(null) - largestDimension;
                    originalImageLargestDim = inImage.getHeight(null);
                }
                //create an image buffer to draw to
                BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles
                Graphics2D g2d;
                AffineTransform tx;
                if (scale < 1.0d) //only scale if desired size is smaller than original
                {
                    int numSteps = sizeDifference / 100;
                    int stepSize = sizeDifference / numSteps;
                    int stepWeight = stepSize / 2;
                    int heavierStepSize = stepSize + stepWeight;
                    int lighterStepSize = stepSize - stepWeight;
                    int currentStepSize, centerStep;
                    double scaledW = inImage.getWidth(null);
                    double scaledH = inImage.getHeight(null);
                    if (numSteps % 2 == 1) //if there's an odd number of steps
                        centerStep = (int) Math.ceil((double) numSteps / 2d); //find the center step
                    else
                        centerStep = -1; //set it to -1 so it's ignored later
                    Integer intermediateSize = originalImageLargestDim,
                            previousIntermediateSize = originalImageLargestDim;
                    Integer calculatedDim;
                    for (Integer i = 0; i < numSteps; i++) {
                        if (i + 1 != centerStep) //if this isn't the center step
                        {
                            if (i == numSteps - 1) //if this is the last step
                            {
                                //fix the stepsize to account for decimal place errors previously
                                currentStepSize = previousIntermediateSize - largestDimension;
                            } else {
                                if (numSteps - i > numSteps / 2) //if we're in the first half of the reductions
                                    currentStepSize = heavierStepSize;
                                else
                                    currentStepSize = lighterStepSize;
                            }
                        } else //center step, use natural step size
                        {
                            currentStepSize = stepSize;
                        }
                        intermediateSize = previousIntermediateSize - currentStepSize;
                        scale = (double) intermediateSize / (double) previousIntermediateSize;
                        scaledW = (int) scaledW * scale;
                        scaledH = (int) scaledH * scale;
                        outImage = new BufferedImage((int) scaledW, (int) scaledH, BufferedImage.TYPE_INT_RGB);
                        g2d = outImage.createGraphics();
                        g2d.setBackground(Color.WHITE);
                        g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        tx = new AffineTransform();
                        tx.scale(scale, scale);
                        g2d.drawImage(inImage, tx, null);
                        g2d.dispose();
                        inImage = new ImageIcon(outImage).getImage();
                        previousIntermediateSize = intermediateSize;
                    }
                } else {
                    //just copy the original
                    outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null),
                            BufferedImage.TYPE_INT_RGB);
                    g2d = outImage.createGraphics();
                    g2d.setBackground(Color.WHITE);
                    g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
                    tx = new AffineTransform();
                    tx.setToIdentity(); //use identity matrix so image is copied exactly
                    g2d.drawImage(inImage, tx, null);
                    g2d.dispose();
                }
                //JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(outFilename);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
            }
        }
    } catch (Exception ex) {
        String errorMsg = "";
        errorMsg += "<br>Exception: " + ex.toString();
        errorMsg += "<br>Cause = " + ex.getCause();
        errorMsg += "<br>Stack Trace = ";
        StackTraceElement stackTrace[] = ex.getStackTrace();
        for (int traceLine = 0; traceLine < stackTrace.length; traceLine++) {
            errorMsg += "<br>" + stackTrace[traceLine];
        }
        return errorMsg;
    }
    return ""; //success
}

From source file:com.sisrni.managedbean.RolesMB.java

public void preEliminar(SsRoles ssRoles) throws Exception {
    try {/* www  .jav  a2  s.c  o m*/
        this.ssRoles = ssRoles;
        RequestContext.getCurrentInstance().update("formAdmin");
        RequestContext.getCurrentInstance().update("formRol");
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error class RolesOpcionesMB - preEliminar()\n" + e.getMessage(), e.getCause());
    } finally {

    }
}

From source file:org.codehaus.grepo.core.config.GenericRepositoryScanBeanDefinitionParser.java

/**
 * @param element The element.//www . jav  a 2  s  .  co m
 * @param scanner The scanner.
 * @param readerContext The reader context.
 */
protected void parseTypeFilters(Element element, GenericRepositoryBeanDefinitionScanner scanner,
        XmlReaderContext readerContext) {

    // Parse exclude and include filter elements.
    ClassLoader classLoader = scanner.getResourceLoader().getClassLoader();
    NodeList nodeList = element.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            String localName = node.getLocalName();
            try {
                if (INCLUDE_FILTER_ELEMENT.equals(localName)) {
                    // Note: that we use the composite type filter for include-filter,
                    // because we always want repositories of appropriate interface type...
                    CompositeTypeFilter typeFilter = new CompositeTypeFilter();
                    typeFilter.addTypeFilter(new AssignableTypeFilter(requiredGenericRepositoryType));
                    typeFilter.addTypeFilter(createTypeFilter((Element) node, classLoader));
                    scanner.addIncludeFilter(typeFilter);
                } else if (EXCLUDE_FILTER_ELEMENT.equals(localName)) {
                    TypeFilter typeFilter = createTypeFilter((Element) node, classLoader);
                    scanner.addExcludeFilter(typeFilter);
                }
            } catch (Exception ex) {
                readerContext.error(ex.getMessage(), readerContext.extractSource(element), ex.getCause());
            }
        }
    }
}

From source file:se.skltp.cooperation.web.rest.v1.controller.ConnectionPointControllerTest.java

@Test
public void get_shouldThrowNotFoundException() throws Exception {

    when(connectionPointServiceMock.find(anyLong())).thenReturn(null);
    try {//w w w.  j av  a  2s  . c  o  m
        mockMvc.perform(get("/api/v1/connectionPoints/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound());
        fail("Should thrown a exception");
    } catch (Exception e) {
        assertEquals(e.getCause().getClass(), ResourceNotFoundException.class);
    }
}

From source file:org.obiba.opal.rest.client.magma.RestDatasource.java

private synchronized void refresh() {
    try {/*  ww  w  . j ava 2s .  co m*/
        DatasourceDto d = opalClient.getResource(DatasourceDto.class, datasourceURI,
                DatasourceDto.newBuilder());
        Value currentTimestamp = DateTimeType.get().valueOf(d.getTimestamps().getLastUpdate());

        if (timestamps != null && timestamps.getLastUpdate().equals(currentTimestamp)) {
            log.debug("RestDatasource is up to date. Skipping refresh.");
            return; //Cache is up to date
        }

        log.debug("Refreshing data source value tables.");

        Set<String> cachedTableNames = ImmutableSet
                .copyOf(Iterables.transform(super.getValueTables(), new Function<ValueTable, String>() {
                    @Override
                    public String apply(ValueTable input) {
                        return input.getName();
                    }
                }));

        timestamps = new TimestampsBean(DateTimeType.get().valueOf(d.getTimestamps().getCreated()),
                DateTimeType.get().valueOf(d.getTimestamps().getLastUpdate()));
        Set<String> currentTables = ImmutableSet.copyOf(d.getTableList());

        for (String tableName : cachedTableNames) {
            ValueTable table = getCachedValueTable(tableName);
            removeValueTable(table);
        }

        for (String tableName : currentTables) {
            addValueTable(tableName);
        }
    } catch (Exception e) {
        log.error("Failed refreshing value tables from Opal server: {}", e.getMessage(), e);

        if (e.getCause() instanceof ConnectException) {
            log.error("Failed connecting to Opal server: {}", e.getMessage(), e);
        } else {
            log.error("Unexpected error while communicating with Opal server: {}", e.getMessage(), e);
        }

        throw new MagmaRuntimeException(e.getMessage(), e);
    }
}

From source file:com.sisrni.managedbean.RolesMB.java

/***
* 
* @param country//from w w  w  .java 2  s .c  om
* @throws Exception
*/

public void preEditar(SsRoles ssRoles) throws Exception {
    try {
        this.ssRoles = ssRoles;
        setActualizar(true);
        RequestContext.getCurrentInstance().update("formAdmin");
        RequestContext.getCurrentInstance().update("formMenu");
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error class RolesOpcionesMB - preEditar()\n" + e.getMessage(), e.getCause());
    } finally {

    }
}

From source file:gov.nih.nci.caarray.application.project.FileUploadUtils.java

private void addEntryToProject(Project project, ZipInputStream input, String entryName)
        throws InvalidFileException {
    LOG.info("Adding entry  " + entryName + " to project " + project.getId());
    try {//from w w w.j  a v a 2  s  . c o  m
        final ProjectManagementService pms = getProjectManagementService();
        pms.addFile(project, input, entryName);
        result.addSuccessfulFile(entryName);
    } catch (final Exception e) {
        LOG.error("Error adding file", e);
        if (e.getCause() instanceof InvalidStateException) {
            result.addConflictingFile(entryName);
        } else {
            throw new InvalidFileException(entryName, ADDING_FILE_ERROR_KEY, result, ADDING_FILE_ERROR_MESSAGE,
                    e);
        }
    }
}