Example usage for java.io FileInputStream skip

List of usage examples for java.io FileInputStream skip

Introduction

In this page you can find the example usage for java.io FileInputStream skip.

Prototype

public long skip(long n) throws IOException 

Source Link

Document

Skips over and discards n bytes of data from the input stream.

Usage

From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java

public void loadTextData(File file) {
    try {//from w w w.  j av  a 2  s  .com
        RandomAccessFile in = new RandomAccessFile(file, "r");

        // Skip header
        in.readLine();
        in.readLine();
        in.readLine();

        // Skip Subject Information
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String startTimeInput = in.readLine();
        String commentsInput = in.readLine();

        String data = in.readLine();
        while (!data.startsWith("2) System Configuration")) {
            commentsInput += data;
            data = in.readLine();
        }
        // System configuration

        // in.readLine();
        in.readLine();
        String timeCounstantInput = in.readLine();
        String cameraGainInput = in.readLine();
        String exposureTimeInput = in.readLine();
        in.readLine();
        in.readLine();
        in.readLine();
        String resolutionInput = in.readLine();

        // Time Data
        in.readLine();
        String timeDataInput = in.readLine();
        String totalImagesInput = in.readLine();
        in.readLine();
        in.readLine();
        // in.readLine();
        // System.out.println(in.readLine());
        // in.readLine();

        // Parse important Size

        high = (new Scanner(resolutionInput.split(":")[1])).nextInt();
        wide = (new Scanner(resolutionInput.split(",")[1])).nextInt();
        int tot = 1;
        try {
            tot = (new Scanner(totalImagesInput.split(":")[1])).nextInt();
        } catch (Exception e) {

        }
        System.out.println(wide + "," + high);
        // Parse timeInformation
        SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss (dd/MM/yy)");
        Date startTime = null;
        try {
            startTime = format.parse(startTimeInput.split(": ")[1]);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String[] frameTimeData = timeDataInput.split("information:")[1].split(",");

        Date[] timeInfo = new Date[tot];
        for (int i = 0; i < frameTimeData.length - 1; i++) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(startTime);
            String dat = (frameTimeData[i]);
            String[] timeVals = dat.split(":");

            int hour = Integer.parseInt(StringOperations.removeNonNumber(timeVals[0]));
            int min = Integer.parseInt(StringOperations.removeNonNumber(timeVals[1]));
            int sec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[2]));
            int msec = Integer.parseInt(StringOperations.removeNonNumber(timeVals[3]));

            cal.add(Calendar.HOUR_OF_DAY, hour);
            cal.add(Calendar.MINUTE, min);
            cal.add(Calendar.SECOND, sec);
            cal.add(Calendar.MILLISECOND, msec);
            timeInfo[i] = cal.getTime();
        }

        // Parse Image Data
        /*
         * Close Random access file and switch to scanner first store pos
         * then move to correct point.
         */
        long pos = in.getFilePointer();
        in.close();

        FileInputStream fIn = new FileInputStream(file);
        fIn.skip(pos);

        BufferedInputStream bIn = new BufferedInputStream(fIn);
        Scanner sIn = new Scanner(bIn);

        short[][][] holder = new short[tot][wide][high];

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        StatusBarPanel stat = new StatusBarPanel();
        stat.setMaximum(high);
        f.getContentPane().setLayout(new BorderLayout());
        f.getContentPane().add(stat, BorderLayout.CENTER);
        f.setSize(200, 60);
        f.setVisible(true);

        for (int i = 0; i < tot; i++) {
            // Skip over the heading values
            stat.setStatusMessage("Loading " + i + " of " + tot);
            sIn.useDelimiter("\n");
            sIn.next();
            sIn.next();
            sIn.next();
            if (i != 0) {
                sIn.next();
            }
            sIn.reset();
            for (int y = 0; y < high; y++) {
                stat.setValue(y);
                sIn.nextInt();
                for (int x = 0; x < wide; x++) {
                    holder[i][x][y] = sIn.nextShort();
                }

            }
            addData(timeInfo[i], holder[i]);
        }

        // FrameFactroy.getFrame(new DynamicRangeImage(data[0]));
        // Start Image Data

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Ignore("Broken in OpenJDK8 zipfs")
@Test/*from www .j  a  va 2s  .c  o  m*/
public void mimeTypePosition() throws Exception {
    Bundle bundle = Bundles.createBundle();
    String mimetype = "application/x-test";
    Bundles.setMimeType(bundle, mimetype);
    assertEquals(mimetype, Bundles.getMimeType(bundle));
    Path zip = Bundles.closeBundle(bundle);

    assertTrue(Files.exists(zip));
    try (ZipFile zipFile = new ZipFile(zip.toFile())) {
        // Must be first entry
        ZipEntry mimeEntry = zipFile.entries().nextElement();
        assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName());
        assertEquals("mimetype should be uncompressed, but compressed size mismatch",
                mimeEntry.getCompressedSize(), mimeEntry.getSize());
        assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod());
        assertEquals("Wrong mimetype", mimetype, IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII"));
    }

    // Check position 30++ according to
    // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568
    byte[] expected = ("mimetype" + mimetype + "PK").getBytes("ASCII");
    FileInputStream in = new FileInputStream(zip.toFile());
    byte[] actual = new byte[expected.length];

    try {

        assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
        assertEquals(expected.length, in.read(actual));
    } finally {
        in.close();
    }
    assertArrayEquals(expected, actual);
}

From source file:fi.iki.elonen.SimpleWebServer.java

/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 *//*from  ww w . ja v  a 2 s . c om*/
Response serveFile(String uri, Map<String, String> header, File file, String mime) {
    Response res;
    try {
        // Calculate etag
        String etag = Integer
                .toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;
        String range = header.get("range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');
                try {
                    if (minus > 0) {
                        startFrom = Long.parseLong(range.substring(0, minus));
                        endAt = Long.parseLong(range.substring(minus + 1));
                    }
                } catch (NumberFormatException ignored) {
                }
            }
        }

        // get if-range header. If present, it must match etag or else we
        // should ignore the range request
        String ifRange = header.get("if-range");
        boolean headerIfRangeMissingOrMatching = (ifRange == null || etag.equals(ifRange));

        String ifNoneMatch = header.get("if-none-match");
        boolean headerIfNoneMatchPresentAndMatching = ifNoneMatch != null
                && ("*".equals(ifNoneMatch) || ifNoneMatch.equals(etag));

        // Change return code and add Content-Range header when skipping is
        // requested
        long fileLen = file.length();

        if (headerIfRangeMissingOrMatching && range != null && startFrom >= 0 && startFrom < fileLen) {
            // range request that matches current etag
            // and the startFrom of the range is satisfiable
            if (headerIfNoneMatchPresentAndMatching) {
                // range request that matches current etag
                // and the startFrom of the range is satisfiable
                // would return range from file
                // respond with not-modified
                res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
                res.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }
                long newLen = endAt - startFrom + 1;
                if (newLen < 0) {
                    newLen = 0;
                }

                FileInputStream fis = new FileInputStream(file);
                fis.skip(startFrom);

                res = newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mime, fis, newLen);
                res.addHeader("Accept-Ranges", "bytes");
                res.addHeader("Content-Length", "" + newLen);
                res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
                res.addHeader("ETag", etag);
            }
        } else {

            if (headerIfRangeMissingOrMatching && range != null && startFrom >= fileLen) {
                // return the size of the file
                // 4xx responses are not trumped by if-none-match
                res = newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT,
                        "");
                res.addHeader("Content-Range", "bytes */" + fileLen);
                res.addHeader("ETag", etag);
            } else if (range == null && headerIfNoneMatchPresentAndMatching) {
                // full-file-fetch request
                // would return entire file
                // respond with not-modified
                res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
                res.addHeader("ETag", etag);
            } else if (!headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching) {
                // range request that doesn't match current etag
                // would return entire (different) file
                // respond with not-modified

                res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
                res.addHeader("ETag", etag);
            } else {
                // supply the file
                res = newFixedFileResponse(file, mime);
                res.addHeader("Content-Length", "" + fileLen);
                res.addHeader("ETag", etag);
            }
        }
    } catch (IOException ioe) {
        res = getForbiddenResponse("Reading file failed.");
    }

    return res;
}

From source file:ru.org.linux.util.ImageInfo.java

private void getJpgInfo(FileInputStream fileStream) throws IOException, BadImageException {
    if (fileStream.read() == 0xFF && fileStream.read() == 0xD8) {
        while (true) {
            int marker;
            do {/*from www .  j a  v  a2  s.  c om*/
                marker = fileStream.read();
            } while (marker != 0xFF);
            do {
                marker = fileStream.read();
            } while (marker == 0xFF);

            if (((marker >= 0xC0) && (marker <= 0xC3)) || ((marker >= 0xC5) && (marker <= 0xCB))
                    || ((marker >= 0xCD) && (marker <= 0xCF))) {
                fileStream.skip(3);
                height = shortBigEndian((byte) fileStream.read(), (byte) fileStream.read());
                width = shortBigEndian((byte) fileStream.read(), (byte) fileStream.read());
                break;
            } else {
                fileStream.skip(shortBigEndian((byte) fileStream.read(), (byte) fileStream.read()) - 2);
            }
        }
    } else {
        throw new BadImageException("Bad JPG image: " + filename);
    }
}

From source file:com.irccloud.android.activity.BaseActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_logout:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Logout");
        builder.setMessage("Would you like to logout of IRCCloud?");

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override/* ww  w  .j a va 2 s  .c  o  m*/
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("Logout", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                conn.logout();
                if (mGoogleApiClient.isConnected()) {
                    Auth.CredentialsApi.disableAutoSignIn(mGoogleApiClient)
                            .setResultCallback(new ResultCallback<Status>() {
                                @Override
                                public void onResult(Status status) {
                                    Intent i = new Intent(BaseActivity.this, LoginActivity.class);
                                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(i);
                                    finish();
                                }
                            });
                } else {
                    Intent i = new Intent(BaseActivity.this, LoginActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i);
                    finish();
                }
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setOwnerActivity(this);
        dialog.show();
        break;
    case R.id.menu_settings:
        Intent i = new Intent(this, PreferencesActivity.class);
        startActivity(i);
        break;
    case R.id.menu_feedback:
        try {
            String bugReport = "Briefly describe the issue below:\n\n\n\n\n" + "===========\n"
                    + ((NetworkConnection.getInstance().getUserInfo() != null)
                            ? ("UID: " + NetworkConnection.getInstance().getUserInfo().id + "\n")
                            : "")
                    + "App version: " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName
                    + " (" + getPackageManager().getPackageInfo(getPackageName(), 0).versionCode + ")\n"
                    + "Device: " + Build.MODEL + "\n" + "Android version: " + Build.VERSION.RELEASE + "\n"
                    + "Firmware fingerprint: " + Build.FINGERPRINT + "\n";

            File logsDir = new File(getFilesDir(),
                    ".Fabric/com.crashlytics.sdk.android.crashlytics-core/log-files/");
            File log = null;
            File output = null;
            if (logsDir.exists()) {
                long max = Long.MIN_VALUE;
                for (File f : logsDir.listFiles()) {
                    if (f.lastModified() > max) {
                        max = f.lastModified();
                        log = f;
                    }
                }

                if (log != null) {
                    File f = new File(getFilesDir(), "logs");
                    f.mkdirs();
                    output = new File(f, LOG_FILENAME);
                    byte[] b = new byte[1];

                    FileOutputStream out = new FileOutputStream(output);
                    FileInputStream is = new FileInputStream(log);
                    is.skip(5);

                    while (is.available() > 0 && is.read(b, 0, 1) > 0) {
                        if (b[0] == ' ') {
                            while (is.available() > 0 && is.read(b, 0, 1) > 0) {
                                out.write(b);
                                if (b[0] == '\n')
                                    break;
                            }
                        }
                    }
                    is.close();
                    out.close();
                }
            }

            Intent email = new Intent(Intent.ACTION_SEND);
            email.setData(Uri.parse("mailto:"));
            email.setType("message/rfc822");
            email.putExtra(Intent.EXTRA_EMAIL, new String[] { "IRCCloud Team <team@irccloud.com>" });
            email.putExtra(Intent.EXTRA_TEXT, bugReport);
            email.putExtra(Intent.EXTRA_SUBJECT, "IRCCloud for Android");
            if (log != null) {
                email.putExtra(Intent.EXTRA_STREAM,
                        FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", output));
            }
            startActivityForResult(Intent.createChooser(email, "Send Feedback:"), 0);
        } catch (Exception e) {
            Toast.makeText(this, "Unable to generate email report: " + e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
            Crashlytics.logException(e);
            NetworkConnection.printStackTraceToCrashlytics(e);
        }
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.ms.commons.standalone.service.StandaloneServiceImpl.java

private String getHeadLogFile(String logFilePath, boolean isTail, int lenth) {
    String content = null;//from   ww  w  .j  a  v  a 2 s.c  o m
    File logFile = new File(logFilePath);
    FileInputStream fiStream = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        fiStream = new FileInputStream(logFile);
        if (isTail && logFile.length() > lenth) {
            fiStream.skip(logFile.length() - lenth);
        }
        byte[] buffer = new byte[lenth];
        long count = 0;
        int n = 0;
        while (-1 != (n = fiStream.read(buffer))) {
            baos.write(buffer, 0, n);
            count += n;
            if (count >= lenth) {
                break;
            }
        }
        byte[] result = ArrayUtils.subarray(baos.toByteArray(), 0, lenth);
        content = new String(result, "utf-8");
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return "" + e.getMessage();
    } finally {
        IOUtils.closeQuietly(fiStream);
        IOUtils.closeQuietly(baos);
    }
    return content;
}

From source file:com.alecgorge.minecraft.jsonapi.NanoHTTPD.java

/**
 * Serves file from homeDir and its' subdirectories (only). Uses only URI,
 * ignores all headers and HTTP parameters.
 *//*from  w  w w.ja  va 2 s .co m*/
public Response serveFile(String uri, Properties header, File homeDir, boolean allowDirectoryListing) {
    // Make sure we won't die of an exception later
    if (!homeDir.isDirectory())
        return new Response(HTTP_INTERNALERROR, MIME_PLAINTEXT,
                "INTERNAL ERRROR: serveFile(): given homeDir is not a directory.");

    // Remove URL arguments
    uri = uri.trim().replace(File.separatorChar, '/');
    if (uri.indexOf('?') >= 0)
        uri = uri.substring(0, uri.indexOf('?'));

    // Prohibit getting out of current directory
    if (uri.startsWith("..") || uri.endsWith("..") || uri.indexOf("../") >= 0)
        return new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons.");

    File f = new File(homeDir, uri);
    if (!f.exists())
        return new Response(HTTP_NOTFOUND, MIME_PLAINTEXT, "Error 404, file not found.");

    // List the directory, if necessary
    if (f.isDirectory()) {
        // Browsers get confused without '/' after the
        // directory, send a redirect.
        if (!uri.endsWith("/")) {
            uri += "/";
            Response r = new Response(HTTP_REDIRECT, MIME_HTML,
                    "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>");
            r.addHeader("Location", uri);
            return r;
        }

        // First try index.html and index.htm
        if (new File(f, "index.html").exists())
            f = new File(homeDir, uri + "/index.html");
        else if (new File(f, "index.htm").exists())
            f = new File(homeDir, uri + "/index.htm");

        // No index file, list the directory
        else if (allowDirectoryListing) {
            String[] files = f.list();
            String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";

            if (uri.length() > 1) {
                String u = uri.substring(0, uri.length() - 1);
                int slash = u.lastIndexOf('/');
                if (slash >= 0 && slash < u.length())
                    msg += "<b><a href=\"" + uri.substring(0, slash + 1) + "\">..</a></b><br/>";
            }

            for (int i = 0; i < files.length; ++i) {
                File curFile = new File(f, files[i]);
                boolean dir = curFile.isDirectory();
                if (dir) {
                    msg += "<b>";
                    files[i] += "/";
                }

                msg += "<a href=\"" + encodeUri(uri + files[i]) + "\">" + files[i] + "</a>";

                // Show file size
                if (curFile.isFile()) {
                    long len = curFile.length();
                    msg += " &nbsp;<font size=2>(";
                    if (len < 1024)
                        msg += curFile.length() + " bytes";
                    else if (len < 1024 * 1024)
                        msg += curFile.length() / 1024 + "." + (curFile.length() % 1024 / 10 % 100) + " KB";
                    else
                        msg += curFile.length() / (1024 * 1024) + "."
                                + curFile.length() % (1024 * 1024) / 10 % 100 + " MB";

                    msg += ")</font>";
                }
                msg += "<br/>";
                if (dir)
                    msg += "</b>";
            }
            return new Response(HTTP_OK, MIME_HTML, msg);
        } else {
            return new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: No directory listing.");
        }
    }

    try {
        // Get MIME type from file name extension, if possible
        String mime = null;
        int dot = f.getCanonicalPath().lastIndexOf('.');
        if (dot >= 0)
            mime = (String) theMimeTypes.get(f.getCanonicalPath().substring(dot + 1).toLowerCase());
        if (mime == null)
            mime = MIME_DEFAULT_BINARY;

        // Support (simple) skipping:
        long startFrom = 0;
        String range = header.getProperty("range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');
                if (minus > 0)
                    range = range.substring(0, minus);
                try {
                    startFrom = Long.parseLong(range);
                } catch (NumberFormatException nfe) {
                }
            }
        }

        FileInputStream fis = new FileInputStream(f);
        fis.skip(startFrom);
        Response r = new Response(HTTP_OK, mime, fis);
        r.addHeader("Content-length", "" + (f.length() - startFrom));
        r.addHeader("Content-range", "" + startFrom + "-" + (f.length() - 1) + "/" + f.length());
        return r;
    } catch (IOException ioe) {
        return new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed.");
    }
}

From source file:com.warfrog.bitmapallthethings.BattEngine.java

private void decodeBitmap(String filename) throws IOException {
    System.out.println("Decoding " + filename);

    File inputFile = new File(filename);
    File outputFile = new File(
            outputDirectory + File.separator + FilenameUtils.removeExtension(inputFile.getName()));

    FileInputStream fis = new FileInputStream(filename);
    //skip 6 bytes
    fis.skip(6);
    //read the length we encoded
    int fileSize = EndianUtils.readSwappedInteger(fis);
    //skip the rest of the header
    fis.skip(44);//from  w  ww  . j  a v  a  2 s  . c o  m
    Files.copy(fis, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    //truncate the file
    FileChannel outChan = new FileOutputStream(outputFile, true).getChannel();
    outChan.truncate(fileSize);
    outChan.close();

    //clean up
    if (isCleanUp()) {
        //delete the bitmap
        System.out.println("Deleting: " + inputFile);
        FileUtils.deleteQuietly(inputFile);
    }
}

From source file:de.tarent.maven.plugins.pkg.packager.DebPackager.java

/**
 * Puts a pgp signature in the package based on the maintainer name
 * <p>//  w w w. java 2 s . c o m
 * The signature for the maintainer name must have been importend in the gpg
 * keyring and the name of the maintainer must match with the one set in the
 * POM
 * </p>
 * <p>
 * These are the steps followed by this method:<br/>
 * <ul>
 * <li>Take an existing .deb and unpack it:<br/>
 * $ ar x my_package_1_0_0.deb</li>
 * <li>Concatenate its contents (the order is important), and output to a
 * temp file:<br/>
 * $ cat debian-binary control.tar.gz data.tar.gz > /tmp/combined-contents<br/>
 * </li>
 * <li>Create a GPG signature of the concatenated file, calling it
 * _gpgorigin:<br/>
 * $ gpg -abs -o _gpgorigin /tmp/combined-contents</li>
 * <li>Finally, archive the _gpgorigin file and append it to the original
 * deb file<br/>
 * $ ar rc _gpgorigin.ar _gpgorigin<br/>
 * </li>
 * </ul>
 * </p>
 * 
 * @param workspaceSession
 * @throws MojoExecutionException
 */
private void bundleSignatureWithPackage(WorkspaceSession workspaceSession) throws MojoExecutionException {

    File tempRoot = workspaceSession.getMojo().getTempRoot();
    String packageFilename = workspaceSession.getHelper().getPackageFileName();
    String maintainer = workspaceSession.getTargetConfiguration().getMaintainer();
    AbstractPackagingMojo apm = workspaceSession.getMojo();
    Utils.exec(new String[] { "ar", "x", packageFilename }, tempRoot.getParentFile(),
            "Error extracting package", "Error extracting package");
    try {
        File combinedContents = new File(tempRoot.getParentFile(), COMBINEDCONTENTSFILENAME);
        FileWriter fw = new FileWriter(combinedContents);

        InputStream stream = Utils.exec(
                new String[] { "cat", "debian-binary", "control.tar.gz", "data.tar.gz" },
                tempRoot.getParentFile(), "Error creating concatenated content",
                "Error creating concatenated content");
        IOUtils.copy(stream, fw);
        fw.close();
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    // If signPassPhrase has been set we don't expect any interaction with
    // the user
    // therefore we call gpg with --tty
    if (apm.getSignPassPhrase() != null) {
        Utils.exec(
                new String[] { "gpg", "--no-tty", "--passphrase", apm.getSignPassPhrase(), "--default-key",
                        maintainer, "--no-use-agent", "-abs", "-o", GPGORIGIN, COMBINEDCONTENTSFILENAME },
                tempRoot.getParentFile(), "Error signing concatenated file", "Error writing concatenated file");

    } else {
        Utils.exec(
                new String[] { "gpg", "--default-key", maintainer, "-abs", "-o", GPGORIGIN,
                        COMBINEDCONTENTSFILENAME },
                tempRoot.getParentFile(), "Error signing concatenated file", "Error writing concatenated file");
    }

    Utils.exec(new String[] { "ar", "rc", GPGORIGIN_AR, GPGORIGIN }, tempRoot.getParentFile(),
            "Error putting package back together", "Error writing package parts into package");

    // We will create a FileInputStream in order to read the ar containing
    // the signature
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(new File(tempRoot.getParentFile(), GPGORIGIN_AR));
    } catch (FileNotFoundException e1) {
        throw new MojoExecutionException("Ar containing signature not found");
    }

    // We will avoid copying the header of the ar file
    try {
        fis.skip(8);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    /*
     * We will create a FileOutputStream in order to write in the debian
     * package
     */
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(new File(tempRoot.getParentFile(), packageFilename), true);
    } catch (FileNotFoundException e) {
        IOUtils.closeQuietly(fis);
        throw new MojoExecutionException("Package file to be signed could not be found");
    }

    // We copy one stream into the other
    try {
        int unit;
        while ((unit = fis.read()) != -1) {
            fos.write(unit);
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Error appending _gpgorigin to archive");
    } finally {
        try {
            fis.close();
        } catch (IOException e) {
            throw new MojoExecutionException("Error closing input stream from _gpgorigin archive");
        }
        try {
            fos.close();
        } catch (IOException e) {
            throw new MojoExecutionException("Error closing output stream to debian package");
        }
    }

    // Here we clean the artifacts created while signing
    File f = new File(tempRoot.getParentFile(), "debian-binary");
    f.delete();
    f = new File(tempRoot.getParentFile(), "control.tar.gz");
    f.delete();
    f = new File(tempRoot.getParentFile(), "data.tar.gz");
    f.delete();
    f = new File(tempRoot.getParentFile(), GPGORIGIN);
    f.delete();
    f = new File(tempRoot.getParentFile(), GPGORIGIN_AR);
    f.delete();
    f = new File(tempRoot.getParentFile(), COMBINEDCONTENTSFILENAME);
    f.delete();
}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void mimeTypePosition() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_EPUB);
    assertEquals(UCFPackage.MIME_EPUB, container.getPackageMediaType());
    container.save(tmpFile);//from   www.  j  a  v a2 s.c  om
    assertTrue(tmpFile.exists());
    ZipFile zipFile = new ZipFile(tmpFile);
    // Must be first entry
    ZipEntry mimeEntry = zipFile.entries().nextElement();
    assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName());
    assertEquals("mimetype should be uncompressed, but compressed size mismatch", mimeEntry.getCompressedSize(),
            mimeEntry.getSize());
    assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod());
    assertEquals("Wrong mimetype", UCFPackage.MIME_EPUB,
            IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII"));

    // Check position 30++ according to
    // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568
    byte[] expected = ("mimetype" + UCFPackage.MIME_EPUB + "PK").getBytes("ASCII");
    FileInputStream in = new FileInputStream(tmpFile);
    byte[] actual = new byte[expected.length];
    try {
        assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
        assertEquals(expected.length, in.read(actual));
    } finally {
        in.close();
    }
    assertArrayEquals(expected, actual);
}