Example usage for java.io FileNotFoundException getStackTrace

List of usage examples for java.io FileNotFoundException getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

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

Usage

From source file:org.dspace.content.crosswalk.XSLTDisseminationCrosswalk.java

/**
 * Simple command-line rig for testing the DIM output of a stylesheet.
 * Usage:  java XSLTDisseminationCrosswalk  <crosswalk-name> <handle> [output-file]
 *///www.  j  av a 2s  . c  o  m
public static void main(String[] argv) throws Exception {
    log.error("started.");
    if (argv.length < 2 || argv.length > 3) {
        System.err.println("Usage:  java XSLTDisseminationCrosswalk <crosswalk-name> <handle> [output-file]");
        log.error("You started Dissemination Crosswalk Test/Export with a wrong number of parameters.");
        System.exit(1);
    }

    String xwalkname = argv[0];
    String handle = argv[1];
    OutputStream out = System.out;
    if (argv.length > 2) {
        try {
            out = new FileOutputStream(argv[2]);
        } catch (FileNotFoundException e) {
            System.err.println("Can't write to the specified file: " + e.getMessage());
            System.err.println("Will write output to stdout.");
        }
    }

    DisseminationCrosswalk xwalk = (DisseminationCrosswalk) PluginManager
            .getNamedPlugin(DisseminationCrosswalk.class, xwalkname);
    if (xwalk == null) {
        System.err.println("Error: Cannot find a DisseminationCrosswalk plugin for: \"" + xwalkname + "\"");
        log.error("Cannot find the Dissemination Crosswalk plugin.");
        System.exit(1);
    }

    context = new Context();
    context.turnOffAuthorisationSystem();

    DSpaceObject dso = null;
    try {
        dso = HandleManager.resolveToObject(context, handle);
    } catch (SQLException e) {
        System.err.println(
                "Error: A problem with the database connection occurred, check logs for further information.");
        System.exit(1);
    }

    if (null == dso) {
        System.err.println("Can't find a DSpaceObject with the handle \"" + handle + "\"");
        System.exit(1);
    }

    if (!xwalk.canDisseminate(dso)) {
        System.err.println("Dissemination Crosswalk can't disseminate this DSpaceObject.");
        log.error("Dissemination Crosswalk can't disseminate this DSpaceObject.");
        System.exit(1);
    }

    Element root = null;
    try {
        root = xwalk.disseminateElement(dso);
    } catch (Exception e) {
        // as this script is for testing dissemination crosswalks, we want
        // verbose information in case of an exception.
        System.err.println("An error occurred while processing the dissemination crosswalk.");
        System.err.println("=== Error Message ===");
        System.err.println(e.getMessage());
        System.err.println("===  Stack Trace  ===");
        e.printStackTrace();
        System.err.println("=====================");
        log.error("Caught: " + e.toString() + ".");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
        System.exit(1);
    }

    try {
        XMLOutputter xmlout = new XMLOutputter(Format.getPrettyFormat());
        xmlout.output(new Document(root), out);
    } catch (Exception e) {
        // as this script is for testing dissemination crosswalks, we want
        // verbose information in case of an exception.
        System.err.println("An error occurred after processing the dissemination crosswalk.");
        System.err.println("The error occurred while trying to print the generated XML.");
        System.err.println("=== Error Message ===");
        System.err.println(e.getMessage());
        System.err.println("===  Stack Trace  ===");
        System.err.println(e.getStackTrace());
        System.err.println("=====================");
        log.error("Caught: " + e.toString() + ".");
        log.error(e.getMessage());
        log.error(e.getStackTrace());
        System.exit(1);
    }

    context.complete();
    if (out instanceof FileOutputStream) {
        out.close();
    }
}

From source file:Main.java

public static Bitmap decodeFile(String path, int desWidth, int desHeight) {
    Bitmap result = null;//  ww  w  .jav a  2 s.com
    File f = null;
    FileInputStream fileInputStream = null;
    try {
        f = new File(path);
        if (!f.exists()) {
            return null;
        }
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        fileInputStream = new FileInputStream(f);
        BitmapFactory.decodeStream(fileInputStream, null, o);

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < desWidth || height_tmp / 2 < desHeight)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        result = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
        logE(TAG, "error:" + e.getStackTrace());
    } finally {
        if (f != null) {
            f = null;
        }
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            fileInputStream = null;
        }
    }
    return result;
}

From source file:org.jenkinsci.plugins.os_ci.utils.CompressUtils.java

public static void untarFile(File file) throws IOException {
    FileInputStream fileInputStream = null;
    String currentDir = file.getParent();
    try {//from  www.ja v  a 2  s .  c  o m
        fileInputStream = new FileInputStream(file);
        GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
        TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipInputStream);

        TarArchiveEntry tarArchiveEntry;

        while (null != (tarArchiveEntry = tarArchiveInputStream.getNextTarEntry())) {
            if (tarArchiveEntry.isDirectory()) {
                FileUtils.forceMkdir(new File(currentDir + File.separator + tarArchiveEntry.getName()));
            } else {
                byte[] content = new byte[(int) tarArchiveEntry.getSize()];
                int offset = 0;
                tarArchiveInputStream.read(content, offset, content.length - offset);
                FileOutputStream outputFile = new FileOutputStream(
                        currentDir + File.separator + tarArchiveEntry.getName());
                org.apache.commons.io.IOUtils.write(content, outputFile);
                outputFile.close();
            }
        }
    } catch (FileNotFoundException e) {
        throw new IOException(e.getStackTrace().toString());
    }
}

From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java

/**
 * Copies the File toCopy to the File destFile.
 * /*from  ww  w.ja  v a2s  .  c  o  m*/
 * @param toCopy
 * @param destFile
 * @return true if copy is successful, false otherwise.
 */
public static boolean copyFile(final File toCopy, final File destFile) {
    logger.debug("copyFile()");
    boolean success = false;
    try {
        success = FileInstaller.copyStream(new FileInputStream(toCopy), new FileOutputStream(destFile));
        logger.debug("returning " + success);
        return success;
    } catch (final FileNotFoundException e) {
        logger.debug(e.getStackTrace().toString());
    }
    logger.debug("returning " + success);
    return success;
}

From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java

/**
 * Copies bytes from an InputStream to a File.
 * //from  w  w  w. j  a  va  2s . c om
 * @param is
 * @param os
 * @return true if copy is successful, false otherwise.
 */
private static boolean copyStream(final InputStream is, final File f) {
    logger.debug("copyStream(InputStream is, File f)");
    boolean success = false;
    try {
        success = FileInstaller.copyStream(is, new FileOutputStream(f));
        logger.debug("returning " + success);
        return success;
    } catch (final FileNotFoundException e) {
        logger.debug(e.getStackTrace().toString());
    }
    logger.debug("returning " + success);
    return success;
}

From source file:br.com.verificanf.bo.NotaBO.java

public void buscar() {
    /*Inicio - Pegar Configuraes de email do arquivo*/
    try {/*from   www. j  a v  a  2 s . c om*/
        String local = new File("./email.txt").getCanonicalFile().toString();
        File arq = new File(local);
        boolean existe = arq.exists();
        if (existe) {
            FileReader fr = new FileReader(arq);
            BufferedReader br = new BufferedReader(fr);
            while (br.ready()) {
                String linha = br.readLine();
                if (linha.contains("host:")) {
                    hostEmail = linha.replace("host:", "").replace(" ", "");
                }
                if (linha.contains("port:")) {
                    portEmail = linha.replace("port:", "").replace(" ", "");
                }
                if (linha.contains("user:")) {
                    userEmail = linha.replace("user:", "").replace(" ", "");
                }
                if (linha.contains("pass:")) {
                    passEmail = linha.replace("pass:", "").replace(" ", "");
                }
                if (linha.contains("from:")) {
                    fromEmail = linha.replace("from:", "").replace(" ", "");
                }
                if (linha.contains("to:")) {
                    toEmail = linha.replace("to:", "").replace(" ", "");
                }
            }

        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex);
        StackTraceElement st[] = ex.getStackTrace();
        String erro = "";
        for (int i = 0; i < st.length; i++) {
            erro += st[i].toString() + "\n";
        }

    } catch (IOException ex) {
        Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex);
        StackTraceElement st[] = ex.getStackTrace();
        String erro2 = "";
        for (int i = 0; i < st.length; i++) {
            erro2 += st[i].toString() + "\n";
        }

    }
    /*FIM - Pegar Configuraes de email do arquivo*/

    NotaDAO notaDAO = new NotaDAO();
    try {
        ultimasAtual = notaDAO.getUltimaNotaMesAtual();
        ultimasAnterior = notaDAO.getUltimaNotaMesAnterior();
        naoEncontradas = new ArrayList<>();
        for (Nota notaAnterior : ultimasAnterior) {

            for (Nota notaAtual : ultimasAtual) {

                if (notaAnterior.getLoja() == notaAtual.getLoja()) {
                    //System.out.println("Anterior Loja: "+notaAnterior.getLoja()+" Nota: "+notaAnterior.getNumero());
                    //System.out.println("Atual Loja: "+notaAtual.getLoja()+" Nota: "+notaAtual.getNumero());
                    Integer numero = 0;
                    for (Integer i = notaAnterior.getNumero(); i <= notaAtual.getNumero(); i++) {
                        numero = i;
                        Nota notacorrente = new Nota();
                        notacorrente.setLoja(notaAnterior.getLoja());
                        notacorrente.setNumero(numero);
                        notacorrente.setSerie(notaAnterior.getSerie());

                        //System.out.println("Corrente Loja: "+notacorrente.getLoja()+" Nota: "+notacorrente.getNumero());
                        if (!notaDAO.notaIsValida(notacorrente)) {
                            System.out.println("Loja " + notaAnterior.getLoja() + " Numero: " + numero);
                            naoEncontradas.add(notacorrente);
                            msg = msg.concat("      Loja: " + notacorrente.getLoja() + " Nota: "
                                    + notacorrente.getNumero() + " Serie: " + notacorrente.getSerie() + " \n");
                        }

                    }
                }
            }
        }
        if (naoEncontradas.size() > 0) {
            Email email = new SimpleEmail();
            email.setHostName(hostEmail);
            email.setSmtpPort(Integer.parseInt(portEmail));
            email.setAuthentication(userEmail, passEmail);
            email.setFrom(fromEmail);
            email.setSubject("Alerta Nerus!!");
            email.setMsg(msg);

            email.addTo(toEmail);
            email.send();
        }
    } catch (Exception ex) {
        Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

/**
 * Bitmap??//from  w w w. j ava  2s .  co  m
 *
 * @param context 
 * @param uri     ?Uri
 * @return Bitmap
 */
private @Nullable Bitmap getBitmap(@NonNull Context context, @NonNull Uri uri) {
    final ParcelFileDescriptor parcelFileDescriptor;
    try {
        parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
    } catch (FileNotFoundException e) {
        e.getStackTrace();
        return null;
    }

    final FileDescriptor fileDescriptor;
    if (parcelFileDescriptor != null) {
        fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    } else {
        // ParcelFileDescriptor was null for given Uri: [" + mInputUri + "]"
        return null;
    }

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
    if (options.outWidth == -1 || options.outHeight == -1) {
        // "Bounds for bitmap could not be retrieved from the Uri: [" + mInputUri + "]"
        return null;
    }

    int orientation = getOrientation(uri);
    int rotation = getRotation(orientation);

    Matrix transformMatrix = new Matrix();
    transformMatrix.setRotate(rotation);

    // ???
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();

    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    int reqWidth = Math.min(width, options.outWidth);
    int reqHeight = Math.min(height, options.outHeight);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    Bitmap decodeSampledBitmap = null;

    boolean decodeAttemptSuccess = false;
    while (!decodeAttemptSuccess) {
        try {
            decodeSampledBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
            decodeAttemptSuccess = true;
        } catch (OutOfMemoryError error) {
            Log.e("", "doInBackground: BitmapFactory.decodeFileDescriptor: ", error);
            options.inSampleSize *= 2;
        }
    }

    // ??
    decodeSampledBitmap = transformBitmap(decodeSampledBitmap, transformMatrix);

    return decodeSampledBitmap;
}

From source file:com.bah.applefox.main.plugins.fulltextindex.FTLoader.java

/**
 * Gets the words that are supposed to be removed from the article file
 * (Words such as the, a, an, etc. that are unimportant to the search
 * engine)//from w w w  .j  av  a  2  s.co  m
 * 
 * 
 * @return articles - All the words that shouldn't be included in the data
 * @throws IOException
 */
private HashSet<String> getStopWords() {
    HashSet<String> articles = new HashSet<String>();
    System.out.println("getting stop words");
    try {
        // Read the file
        BufferedReader reader = new BufferedReader(new FileReader(new File(articleFile)));

        // String to temporarily store each word
        String temp;

        // Add each word to temp
        while ((temp = reader.readLine()) != null) {
            // Add temp to articles
            articles.add(temp);
        }
        reader.close();
    } catch (FileNotFoundException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
    } catch (IOException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
    }
    return articles;
}

From source file:com.bah.applefox.main.plugins.fulltextindex.FTLoader.java

/**
 * Gets the ids of the div tags that should be excluded from the data on the
 * page. This is useful for pages with repetitive generic headers and
 * footers, allowing for more accurate results
 * //ww  w  .  j  a  v  a 2  s . c  o m
 * @return - HashSet of ids
 */
private HashSet<String> getExDivs() {
    HashSet<String> divs = new HashSet<String>();
    System.out.println("Getting stop divs");
    try {
        // Read in the file
        BufferedReader reader = new BufferedReader(new FileReader(new File(divsFile)));

        // Temporary variable for the ids
        String temp;

        // Set temp to the ids
        while ((temp = reader.readLine()) != null) {
            // Add temp to divs
            divs.add(temp);
        }
        reader.close();
    } catch (FileNotFoundException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
    } catch (IOException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
    }
    return divs;
}

From source file:be.ppareit.swiftp.server.CmdAbstractStore.java

public void doStorOrAppe(String param, boolean append) {
    Log.d(TAG, "STOR/APPE executing with append=" + append);
    File storeFile = inputPathToChrootedFile(sessionThread.getWorkingDir(), param);

    String errString = null;/* ww w  .j  a v a2 s.  com*/
    //OutputStream out = null;
    FileOutputStream out = null;
    // DedicatedWriter dedicatedWriter = null;
    // int origPriority = Thread.currentThread().getPriority();
    // myLog.l(Log.DEBUG, "STOR original priority: " + origPriority);
    storing: {
        // Get a normalized absolute path for the desired file
        if (violatesChroot(storeFile)) {
            errString = "550 Invalid name or chroot violation\r\n";
            break storing;
        }
        if (storeFile.isDirectory()) {
            errString = "451 Can't overwrite a directory\r\n";
            break storing;
        }
        if ((sessionThread.offset >= 0) && (append)) {
            errString = "555 Append can not be used after a REST command\r\n";
            break storing;
        }
        try {
            if (storeFile.exists()) {
                if (!append) {
                    if (!FileUtil.deleteFile(storeFile, App.getAppContext())) {
                        errString = "451 Couldn't truncate file\r\n";
                        break storing;
                    }
                    // Notify other apps that we just deleted a file
                    MediaUpdater.notifyFileDeleted(storeFile.getPath());
                }
            }
            if (!storeFile.exists()) {
                FileUtil.mkfile(storeFile, App.getAppContext());
            }
            out = FileUtil.getOutputStream(storeFile, App.getAppContext());

            //file
            if (sessionThread.offset <= 0) {
                out.getChannel().position(storeFile.length());
                //out = new FileOutputStream(storeFile, append);
            } else if (sessionThread.offset == storeFile.length()) {
                out.getChannel().position(storeFile.length());
                //out = new FileOutputStream(storeFile, true);
            } else {
                out.getChannel().position(sessionThread.offset);
                //                    final RandomAccessFile raf = new RandomAccessFile(storeFile, "rw");
                //                    raf.seek(sessionThread.offset);
                //                    out = new OutputStream() {
                //                        @Override
                //                        public void write(int oneByte) throws IOException {
                //                            raf.write(oneByte);
                //                        }
                //
                //                        @Override
                //                        public void close() throws IOException {
                //                            raf.close();
                //                        }
                //                    };
            }

        } catch (FileNotFoundException e) {
            Log.e(TAG, "error : ", e);
            try {
                errString = "451 Couldn't open file \"" + param + "\" aka \"" + storeFile.getCanonicalPath()
                        + "\" for writing\r\n";
            } catch (IOException io_e) {
                errString = "451 Couldn't open file, nested exception\r\n";
            }
            break storing;
        } catch (IOException e) {
            errString = "451 Unable to seek in file to append\r\n";
            break storing;
        }
        if (!sessionThread.openDataSocket()) {
            errString = "425 Couldn't open data socket\r\n";
            break storing;
        }
        Log.d(TAG, "Data socket ready");
        sessionThread.writeString("150 Data socket ready\r\n");
        byte[] buffer = new byte[SessionThread.DATA_CHUNK_SIZE];
        // dedicatedWriter = new DedicatedWriter(out);
        // dedicatedWriter.start(); // start the writer thread executing
        // myLog.l(Log.DEBUG, "Started DedicatedWriter");
        int numRead;
        // Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        // int newPriority = Thread.currentThread().getPriority();
        // myLog.l(Log.DEBUG, "New STOR prio: " + newPriority);
        if (sessionThread.isBinaryMode()) {
            Log.d(TAG, "Mode is binary");
        } else {
            Log.d(TAG, "Mode is ascii");
        }
        while (true) {
            /*
             * if(dedicatedWriter.checkErrorFlag()) { errString =
             * "451 File IO problem\r\n"; break storing; }
             */
            switch (numRead = sessionThread.receiveFromDataSocket(buffer)) {
            case -1:
                Log.d(TAG, "Returned from final read");
                // We're finished reading
                break storing;
            case 0:
                errString = "426 Couldn't receive data\r\n";
                break storing;
            case -2:
                errString = "425 Could not connect data socket\r\n";
                break storing;
            default:
                try {
                    // Log.d(TAG, "Enqueueing buffer of " + numRead);
                    // dedicatedWriter.enqueueBuffer(buffer, numRead);
                    if (sessionThread.isBinaryMode()) {
                        out.write(buffer, 0, numRead);

                    } else {
                        // ASCII mode, substitute \r\n to \n
                        int startPos = 0, endPos;
                        for (endPos = 0; endPos < numRead; endPos++) {
                            if (buffer[endPos] == '\r') {
                                out.write(buffer, startPos, endPos - startPos);
                                // Our hacky method is to drop all \r
                                startPos = endPos + 1;
                            }
                        }
                        // Write last part of buffer as long as there was something
                        // left after handling the last \r
                        if (startPos < numRead) {
                            out.write(buffer, startPos, endPos - startPos);
                        }
                    }

                    // Attempted bugfix for transfer stalls. Reopen file periodically.
                    // bytesSinceReopen += numRead;
                    // if(bytesSinceReopen >= Defaults.bytes_between_reopen &&
                    // Defaults.do_reopen_hack) {
                    // Log.d(TAG, "Closing and reopening file: " + storeFile);
                    // out.close();
                    // out = new FileOutputStream(storeFile, true/*append*/);
                    // bytesSinceReopen = 0;
                    // }

                    // Attempted bugfix for transfer stalls. Flush file periodically.
                    // bytesSinceFlush += numRead;
                    // if(bytesSinceFlush >= Defaults.bytes_between_flush &&
                    // Defaults.do_flush_hack) {
                    // Log.d(TAG, "Flushing: " + storeFile);
                    // out.flush();
                    // bytesSinceFlush = 0;
                    // }

                    // If this transfer fails, a later APPEND operation might be
                    // received. In that case, we will need to have flushed the
                    // previous writes in order for the append to work. The
                    // filesystem on my G1 doesn't seem to recognized unflushed
                    // data when appending.

                    //out.flush();

                } catch (IOException e) {
                    errString = "451 File IO problem. Device might be full.\r\n";
                    Log.d(TAG, "Exception while storing: " + e);
                    Log.d(TAG, "Message: " + e.getMessage());
                    Log.d(TAG, "Stack trace: ");
                    StackTraceElement[] traceElems = e.getStackTrace();
                    for (StackTraceElement elem : traceElems) {
                        Log.d(TAG, elem.toString());
                    }
                    break storing;
                }
                break;
            }
        }
    }
    // // Clean up the dedicated writer thread
    // if(dedicatedWriter != null) {
    // dedicatedWriter.exit(); // set its exit flag
    // dedicatedWriter.interrupt(); // make sure it wakes up to process the flag
    // }
    // Thread.currentThread().setPriority(origPriority);
    try {
        // if(dedicatedWriter != null) {
        // dedicatedWriter.exit();
        // }
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
    }

    if (errString != null) {
        Log.i(TAG, "STOR error: " + errString.trim());
        sessionThread.writeString(errString);
    } else {
        sessionThread.writeString("226 Transmission complete\r\n");
        // Notify the music player (and possibly others) that a few file has
        // been uploaded.
        MediaUpdater.notifyFileCreated(storeFile.getPath());
    }
    sessionThread.closeDataSocket();
    Log.d(TAG, "STOR finished");
}