Example usage for java.io IOException getStackTrace

List of usage examples for java.io IOException getStackTrace

Introduction

In this page you can find the example usage for java.io IOException getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:org.sakaiproject.nakamura.lite.storage.cassandra.CassandraClient.java

public void insert(String keySpace, String columnFamily, String key, Map<String, Object> values,
        boolean probablyNew) throws StorageClientException {
    try {//from  w w  w . j av a2  s  .com
        Map<String, Map<String, List<Mutation>>> mutation = new HashMap<String, Map<String, List<Mutation>>>();
        Map<String, List<Mutation>> columnMutations = new HashMap<String, List<Mutation>>();
        LOGGER.debug("Saving changes to {}:{}:{} ", new Object[] { keySpace, columnFamily, key });
        List<Mutation> keyMutations = Lists.newArrayList();
        columnMutations.put(columnFamily, keyMutations);
        mutation.put(key, columnMutations);

        for (Entry<String, Object> value : values.entrySet()) {
            String name = value.getKey();
            byte[] bname = null;
            try {
                bname = name.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e1) {
                LOGGER.debug(e1.getMessage());
            }

            Object v = value.getValue();
            if (v instanceof RemoveProperty) {
                Deletion deletion = new Deletion();
                SlicePredicate deletionPredicate = new SlicePredicate();
                deletionPredicate.addToColumn_names(bname);
                deletion.setPredicate(deletionPredicate);
                Mutation mu = new Mutation();
                mu.setDeletion(deletion);
                keyMutations.add(mu);
            } else {
                try {
                    byte b[] = Types.toByteArray(v);
                    Column column = new Column(bname, b, System.currentTimeMillis());
                    ColumnOrSuperColumn csc = new ColumnOrSuperColumn();
                    csc.setColumn(column);
                    Mutation mu = new Mutation();
                    mu.setColumn_or_supercolumn(csc);
                    keyMutations.add(mu);

                } catch (IOException e) {
                    LOGGER.debug("IOException. Stack trace:" + e.getStackTrace());
                }
            }
        }
        LOGGER.debug("Mutation {} ", mutation);
        batch_mutate(keySpace, mutation, ConsistencyLevel.ONE);
    } catch (InvalidRequestException e) {
        throw new StorageClientException(e.getMessage(), e);
    } catch (UnavailableException e) {
        throw new StorageClientException(e.getMessage(), e);
    } catch (TimedOutException e) {
        throw new StorageClientException(e.getMessage(), e);
    } catch (TException e) {
        throw new StorageClientException(e.getMessage(), e);
    }
}

From source file:de.crowdcode.movmvn.plugin.general.GeneralPlugin.java

private void moveFiles() {
    try {/*from   w  w  w  . j  a v  a 2 s .c om*/
        context.logInfo("Move files...");
        String projectSourceName = context.getProjectSourceName();
        String projectTargetName = context.getProjectTargetName();
        // Move files *.java from src -> src/main/java
        // Move files *.properties;*.txt;*.jpg -> src/main/resources
        // Move files *.java from test -> src/test/java
        // Move files *.properties;*.txt;*.jpg -> src/test/resources
        // Move files *.* from resources or resource -> src/main/resources
        // Move files from / to / but not .classpath, .project ->
        // src/main/resources
        // Move directory META-INF -> src/main/resources
        String[] extensionsJava = { "java" };
        Iterator<File> fileIterator = FileUtils.iterateFiles(new File(projectSourceName + "/src"),
                extensionsJava, true);
        for (Iterator<File> iterator = fileIterator; iterator.hasNext();) {
            File currentFile = iterator.next();
            log.info("File to be copied: " + currentFile.getCanonicalPath());
            String nameResultAfterSrc = StringUtils.substringAfterLast(currentFile.getAbsolutePath(), "src\\");
            nameResultAfterSrc = projectTargetName.concat("/src/main/java/").concat(nameResultAfterSrc);
            log.info("Target file: " + nameResultAfterSrc);
            File targetFile = new File(nameResultAfterSrc);
            FileUtils.copyFile(currentFile, targetFile, true);
        }

        // Check whether "resource" or "resources" exist?
        File directoryResources = new File(projectSourceName + "/resource");
        File targetResourcesDir = new File(projectTargetName.concat("/src/main/resources"));
        if (directoryResources.exists()) {
            // Move the files
            FileUtils.copyDirectory(directoryResources, targetResourcesDir);
        }

        directoryResources = new File(projectSourceName + "/resources");
        if (directoryResources.exists()) {
            // Move the files
            FileUtils.copyDirectory(directoryResources, targetResourcesDir);
        }

        // META-INF
        File directoryMetaInf = new File(projectSourceName + "/META-INF");
        if (directoryMetaInf.exists()) {
            FileUtils.copyDirectoryToDirectory(directoryMetaInf, targetResourcesDir);
        }

        // Directory . *.txt, *.doc*, *.png, *.jpg -> src/main/docs
        File targetDocsDir = new File(projectTargetName.concat("/src/main/docs"));
        String[] extensionsRootDir = { "txt", "doc", "docx", "png", "jpg" };
        fileIterator = FileUtils.iterateFiles(new File(projectSourceName), extensionsRootDir, false);
        for (Iterator<File> iterator = fileIterator; iterator.hasNext();) {
            File currentFile = iterator.next();
            log.info("File to be copied: " + currentFile.getCanonicalPath());
            FileUtils.copyFileToDirectory(currentFile, targetDocsDir);
        }

        // Directory . *.cmd, *.sh -> src/main/bin
        File targetBinDir = new File(projectTargetName.concat("/src/main/bin"));
        String[] extensionsRootBinDir = { "sh", "cmd", "properties" };
        fileIterator = FileUtils.iterateFiles(new File(projectSourceName), extensionsRootBinDir, false);
        for (Iterator<File> iterator = fileIterator; iterator.hasNext();) {
            File currentFile = iterator.next();
            log.info("File to be copied: " + currentFile.getCanonicalPath());
            FileUtils.copyFileToDirectory(currentFile, targetBinDir);
        }
    } catch (IOException e) {
        log.info(e.getStackTrace().toString());
    }
}

From source file:org.apache.pig.backend.local.executionengine.POStore.java

@Override
public Tuple getNext() throws IOException {
    // get all tuples from input, and store them.
    DataBag b = BagFactory.getInstance().newDefaultBag();
    Tuple t;/*w  ww.ja v a2 s . com*/
    while ((t = (Tuple) ((PhysicalOperator) opTable.get(inputs[0])).getNext()) != null) {
        b.add(t);
    }
    try {
        StoreFunc func = (StoreFunc) PigContext.instantiateFuncFromSpec(funcSpec);
        f.store(b, func, pigContext);

        // a result has materialized, track it!
        LocalResult materializedResult = new LocalResult(this.outFileSpec);

        materializedResults.put(logicalKey, materializedResult);
    } catch (IOException e) {
        throw e;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        IOException ne = new IOException(e.getClass().getName() + ": " + e.getMessage());
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    }

    return null;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@After
// Clean up the credentialManagerDirectory we created for testing
public void cleanUp() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException,
        KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    //      assertTrue(credentialManagerDirectory.exists());
    //      assertFalse(credentialManagerDirectory.listFiles().length == 0); // something was created there

    if (credentialManagerDirectory.exists()) {
        try {//from w  w w . j av a2 s. c om
            FileUtils.deleteDirectory(credentialManagerDirectory);
            System.out.println(
                    "Deleting Credential Manager's directory: " + credentialManagerDirectory.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }
    }

    // Reset the SSLSocketFactory in JVM so we always have a clean start
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSLv3");

    // Create a "default" JSSE X509KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    kmf.init(ks, "blah".toCharArray());

    // Create a "default" JSSE X509TrustManager.
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(null, null);
    tmf.init(ts);

    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    SSLContext.setDefault(sc);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

From source file:de.thischwa.pmcms.gui.listener.ListenerImageBulkImport.java

@Override
public void widgetSelected(SelectionEvent e) {
    final Shell shell = e.display.getActiveShell();
    File galleryDirectory = PoPathInfo.getSiteGalleryDirectory(this.gallery);
    FileDialog fileDialog = new FileDialog(shell, SWT.MULTI);
    fileDialog.setText("Select one or more images ...");
    List<String> exts = new ArrayList<String>();
    for (String extension : InitializationManager.getAllowedImageExtensions()) {
        exts.add("*." + extension);
    }// w  ww  .  j av  a  2 s . c  o  m
    exts.add(0, StringUtils.join(exts.iterator(), ';'));
    fileDialog.setFilterExtensions(exts.toArray(new String[exts.size()]));
    if (galleryDirectory.exists())
        fileDialog.setFilterPath(galleryDirectory.getAbsolutePath());
    if (fileDialog.open() != null) {
        // collecting files
        List<File> filesToCopy = new ArrayList<File>(fileDialog.getFileNames().length);
        for (String fileName : fileDialog.getFileNames())
            filesToCopy.add(new File(fileDialog.getFilterPath(), fileName));
        List<File> copiedFiles = null;
        if (!(new File(fileDialog.getFilterPath()).getAbsolutePath()
                .startsWith(galleryDirectory.getAbsolutePath()))) {
            try {
                copiedFiles = FileTool.copyToDirectoryUnique(filesToCopy, galleryDirectory);
            } catch (IOException e1) {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText(LabelHolder.get("popup.error")); //$NON-NLS-1$
                mb.setMessage("Error while copying files:\n" + e1.getStackTrace().toString());
                mb.open();
                return;
            }
        } else {
            logger.debug("Image files are not copied, because they are in the right directory!");
            copiedFiles = filesToCopy;
        }

        SiteHolder siteHolder = InitializationManager.getBean(SiteHolder.class);
        for (File file : copiedFiles) {
            Image image = new Image();
            image.setParent(this.gallery);
            image.setFileName(FilenameUtils.getName(file.getAbsolutePath()));
            siteHolder.mark(image);
            this.gallery.add(image);
            logger.debug("Image added: ".concat(image.getDecorationString()));
        }

        TreeViewManager treeViewManager = InitializationManager.getBean(TreeViewManager.class);
        treeViewManager.fillAndExpands(this.gallery);
        BrowserManager browserManager = InitializationManager.getBean(BrowserManager.class);
        browserManager.view(this.gallery, ViewMode.PREVIEW);
        try {
            SitePersister.write(siteHolder.getSite());
        } catch (IOException e2) {
            throw new RuntimeException(e2);
        }
    }
}

From source file:com.PrivacyGuard.Application.Network.FakeVPN.MyVpnService.java

private void stop() {
    running = false;/*from   ww w. j a  v  a  2  s . c o  m*/
    if (mInterface == null)
        return;
    Logger.d(TAG, "Stopping");
    try {
        readThread.interrupt();
        writeThread.interrupt();
        localServer.interrupt();
        mInterface.close();
    } catch (IOException e) {
        Logger.e(TAG, e.toString() + "\n" + Arrays.toString(e.getStackTrace()));
    }
    mInterface = null;
}

From source file:java_lang_programming.com.android_media_demo.article94.java.ImageDecoderActivity.java

/**
 * ???????//ww w . j  av a 2 s .  co m
 *
 * @param uri ?Uri
 * @return ?????
 */
private int getOrientation(@NonNull Uri uri) {
    int orientation = ExifInterface.ORIENTATION_UNDEFINED;
    InputStream in = null;
    try {
        in = getContentResolver().openInputStream(uri);
        if (in == null)
            return orientation;
        ExifInterface exifInterface = new ExifInterface(in);
        orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);
    } catch (IOException e) {
        e.getStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {
            }
        }
    }
    return orientation;
}

From source file:org.openhmis.oauth2.OAuth2Utils.java

/**
 * /*  w  w w .  ja  v  a2 s.  c  o  m*/
 * @param oauthDetails
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public String getAccessToken(OAuth2Details oauthDetails) {
    HttpPost post = new HttpPost(oauthDetails.getAuthenticationServerUrl());
    String clientId = oauthDetails.getClientId();
    String clientSecret = oauthDetails.getClientSecret();
    String scope = oauthDetails.getScope();

    List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
    parametersBody.add(new BasicNameValuePair(OAuthConstants.GRANT_TYPE, oauthDetails.getGrantType()));

    parametersBody.add(new BasicNameValuePair(OAuthConstants.USERNAME, oauthDetails.getUsername()));

    parametersBody.add(new BasicNameValuePair(OAuthConstants.PASSWORD, oauthDetails.getPassword()));

    if (isValid(clientId)) {
        parametersBody.add(new BasicNameValuePair(OAuthConstants.CLIENT_ID, oauthDetails.getClientId()));
    }
    if (isValid(clientSecret)) {
        parametersBody
                .add(new BasicNameValuePair(OAuthConstants.CLIENT_SECRET, oauthDetails.getClientSecret()));
    }

    if (isValid(scope)) {
        parametersBody.add(new BasicNameValuePair(OAuthConstants.SCOPE, oauthDetails.getScope()));
    }

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = null;
    String accessToken = null;
    try {
        post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
        response = httpClient.execute(post);
        int code = response.getStatusLine().getStatusCode();
        if (code >= 400) {
            log.debug("Authorization server expects Basic authentication");
            post.addHeader(OAuthConstants.AUTHORIZATION,
                    getBasicAuthorizationHeader(oauthDetails.getUsername(), oauthDetails.getPassword()));
            post.releaseConnection();
            response = httpClient.execute(post);
            code = response.getStatusLine().getStatusCode();
            if (code >= 400) {
                log.debug("Retry with client credentials");
                post.removeHeaders(OAuthConstants.AUTHORIZATION);
                post.addHeader(OAuthConstants.AUTHORIZATION, getBasicAuthorizationHeader(
                        oauthDetails.getClientId(), oauthDetails.getClientSecret()));
                post.releaseConnection();
                response = httpClient.execute(post);
                if (code >= 400) {
                    throw new RuntimeException(
                            "Could not retrieve access token for user: " + oauthDetails.getUsername());
                }
            }
        }
        Map<String, String> map = handleResponse(response);
        accessToken = map.get(OAuthConstants.ACCESS_TOKEN);
    } catch (ClientProtocolException cpe) {
        cpe.getStackTrace(); // will remove after testing
        log.debug(cpe.getMessage());
    } catch (IOException ioe) {
        ioe.getStackTrace(); // will remove after testing
        log.debug(ioe.getMessage());
    }
    return accessToken;
}

From source file:pt.ua.dicoogle.core.index.FileIndexer.java

/**
 * Calculates the md5 hash of a given file
 * @param f the file to be hashed/*from   w  w w.  j a  v a2s .  co m*/
 * @return a string representation of the md5 hash, or null
 */
private String MD5Hash(File f) {
    InputStream is = null;
    String out = null;
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        is = new FileInputStream(f);
        byte[] buffer = new byte[8192];

        int read = 0;
        try {
            while ((read = is.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }
            byte[] md5sum = digest.digest();
            out = new String(org.apache.commons.codec.binary.Hex.encodeHex(md5sum));
        } catch (IOException ex) {
            System.out.println(ex.getStackTrace());
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                System.out.println(ex.getStackTrace());
            }
        }

    } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace(System.out);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.out);
    } finally {
        try {
            is.close();
        } catch (IOException ex) {
            ex.printStackTrace(System.out);
        }
    }
    return out;
}

From source file:business.services.ExcerptListService.java

/**
 * Write the excerpt list as a file./*w w  w.  j  a  v  a 2  s .  co  m*/
 * @param list - the list
 * @param selectedOnly - writes only selected excerpts if true; all excerpts otherwise.
 * @return the resource holding selected excerpts or all (depends on the value of {@value selected}
 * in CSV format.
 */
public HttpEntity<InputStreamResource> writeExcerptList(ExcerptList list, boolean selectedOnly) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out, EXCERPT_LIST_CHARACTER_ENCODING);
        CSVWriter csvwriter = new CSVWriter(writer, ';', '"');
        csvwriter.writeNext(list.getCsvColumnNames());
        for (ExcerptEntry entry : list.getEntries()) {
            if (!selectedOnly || entry.isSelected()) {
                csvwriter.writeNext(entry.getCsvValues());
            }
        }
        csvwriter.flush();
        writer.flush();
        out.flush();
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        csvwriter.close();
        writer.close();
        out.close();
        InputStreamResource resource = new InputStreamResource(in);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("text/csv;charset=" + EXCERPT_LIST_CHARACTER_ENCODING));
        String filename = (selectedOnly ? "selection" : "excerpts") + "_" + list.getProcessInstanceId()
                + ".csv";
        headers.set("Content-Disposition", "attachment; filename=" + filename);
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        log.info("Returning reponse.");
        return response;
    } catch (IOException e) {
        log.error(e.getStackTrace());
        log.error(e.getMessage());
        throw new ExcerptListDownloadError();
    }
}