Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:br.com.bluesoft.pronto.controller.TicketController.java

@RequestMapping("/ticket/download.action")
public String download(final HttpServletResponse response, final String file, final int ticketKey)
        throws Exception {

    final File arquivo = new File(Config.getImagesFolder() + ticketKey + "/" + file);
    final FileInputStream fis = new FileInputStream(arquivo);
    final int numberBytes = fis.available();
    final byte bytes[] = new byte[numberBytes];
    fis.read(bytes);// ww w  .  j  a  va2 s.  c  o  m
    fis.close();

    String extensao = null;
    if (file.lastIndexOf('.') > 0) {
        extensao = file.substring(file.lastIndexOf('.') + 1, file.length());
    }

    String mime = null;
    if (extensao == null) {
        mime = "text/plain";
    } else if (extensao.equalsIgnoreCase("png")) {
        mime = "images/png";
    } else if (extensao.equalsIgnoreCase("jpg") || extensao.equalsIgnoreCase("jpeg")) {
        mime = "images/jpeg";
    } else if (extensao.equalsIgnoreCase("gif")) {
        mime = "images/gif";
    } else if (extensao.equalsIgnoreCase("pdf")) {
        mime = "application/pdf";
    } else if (extensao.equalsIgnoreCase("xls") || extensao.equalsIgnoreCase("xlsx")) {
        mime = "application/vnd.ms-excel";
    } else if (extensao.equalsIgnoreCase("csv")) {
        mime = "text/csv";
    } else if (extensao.equalsIgnoreCase("txt")) {
        mime = "text/plain";
    } else if (extensao.equalsIgnoreCase("doc") || extensao.equalsIgnoreCase("docx")) {
        mime = "application/ms-word";
    }

    response.addHeader("content-disposition", "attachment; filename=" + file);
    response.setContentType(mime);
    response.setContentLength(bytes.length);
    FileCopyUtils.copy(bytes, response.getOutputStream());

    return null;
}

From source file:org.pentaho.di.job.entries.dostounix.JobEntryDosToUnix.java

private boolean convert(FileObject file, boolean toUnix) {
    boolean retval = false;
    // CR = CR//from   w w w .jav  a 2  s .  c om
    // LF = LF
    try {
        String localfilename = KettleVFS.getFilename(file);
        File source = new File(localfilename);
        if (isDetailed()) {
            if (toUnix) {
                logDetailed(BaseMessages.getString(PKG, "JobDosToUnix.Log.ConvertingFileToUnix",
                        source.getAbsolutePath()));
            } else {
                logDetailed(BaseMessages.getString(PKG, "JobDosToUnix.Log.ConvertingFileToDos",
                        source.getAbsolutePath()));
            }
        }
        File tempFile = new File(tempFolder, source.getName() + ".tmp");

        if (isDebug()) {
            logDebug(BaseMessages.getString(PKG, "JobDosToUnix.Log.CreatingTempFile",
                    tempFile.getAbsolutePath()));
        }
        FileOutputStream out = new FileOutputStream(tempFile);
        FileInputStream in = new FileInputStream(localfilename);

        if (toUnix) {
            // Dos to Unix
            while (in.available() > 0) {
                int b1 = in.read();
                if (b1 == CR) {
                    int b2 = in.read();
                    if (b2 == LF) {
                        out.write(LF);
                    } else {
                        out.write(b1);
                        out.write(b2);
                    }
                } else {
                    out.write(b1);
                }
            }
        } else {
            // Unix to Dos
            while (in.available() > 0) {
                int b1 = in.read();
                if (b1 == LF) {
                    out.write(CR);
                    out.write(LF);
                } else {
                    out.write(b1);
                }
            }
        }

        in.close();
        out.close();

        if (isDebug()) {
            logDebug(BaseMessages.getString(PKG, "JobDosToUnix.Log.DeletingSourceFile", localfilename));
        }
        file.delete();
        if (isDebug()) {
            logDebug(BaseMessages.getString(PKG, "JobDosToUnix.Log.RenamingTempFile",
                    tempFile.getAbsolutePath(), source.getAbsolutePath()));
        }
        tempFile.renameTo(source);

        retval = true;

    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobDosToUnix.Log.ErrorConvertingFile", file.toString(),
                e.getMessage()));
    }

    return retval;
}

From source file:com.qcloud.PicCloud.java

public SliceUploadInfo simpleUploadSlice(String fileName, String fileId, int sliceSize) {
    int fileSize = 0;
    FileInputStream fs;
    byte[] data = null;
    try {//from   w  ww . j av a 2  s .  com
        fs = new FileInputStream(fileName);
        fileSize = fs.available();
        data = new byte[fileSize];
        fs.read(data);
        fs.close();
    } catch (Exception e) {
        setError(-1, "read file failed");
        return null;
    }

    SliceUploadInfo info = initUploadSlice(fileId, data, fileSize, sliceSize);
    if (null == info) {
        return info;
    }

    while (false == info.finishFlag) {
        SliceUploadInfo newInfo = UploadSlice(data, info);
        if (newInfo == null) {
            setError(-1, "slice upload failed, need retry");
            return null;
        }
        info = newInfo;
    }

    setError(0, "success");
    return info;
}

From source file:com.qcloud.PicCloud.java

public SliceUploadInfo simpleUploadSlice(String fileName, SliceUploadInfo lastInfo) {
    FileInputStream fs;
    byte[] data = null;
    try {/*from  w w w .j a v  a  2  s  . c  o  m*/
        fs = new FileInputStream(fileName);
        data = new byte[fs.available()];
        fs.read(data);
        fs.close();
    } catch (Exception e) {
        setError(-1, "read file failed");
        return null;
    }

    SliceUploadInfo info = initUploadSlice(lastInfo.fileId, data, lastInfo.fileSize, lastInfo.sliceSize,
            lastInfo.session);
    if (null == info) {
        return info;
    }

    int maxRetry = 3;
    while (false == info.finishFlag) {
        int retry = 0;
        while (retry < maxRetry) {
            retry++;
            SliceUploadInfo newInfo = UploadSlice(data, info);
            if (newInfo != null) {
                info = newInfo;
                break;
            }
        }
        if (retry >= maxRetry) {
            setError(-1, "slice upload failed, need retry");
            return null;
        }
    }

    setError(0, "success");
    return info;
}

From source file:net.pflaeging.PortableSigner.SignCommandLine.java

/** Creates a new instance of CommandLine */
public SignCommandLine(String args[]) {
    langcodes = "";
    java.util.Enumeration<String> langCodes = ResourceBundle
            .getBundle("net/pflaeging/PortableSigner/SignatureblockLanguages").getKeys();

    while (langCodes.hasMoreElements()) {
        langcodes = langcodes + langCodes.nextElement() + "|";
    }// w  w w. ja  v a  2s  .c  o  m
    langcodes = langcodes.substring(0, langcodes.length() - 1);
    //        System.out.println("Langcodes: " + langcodes);

    CommandLine cmd;
    Options options = new Options();
    options.addOption("t", true, rbi18n.getString("CLI-InputFile"));
    options.addOption("o", true, rbi18n.getString("CLI-OutputFile"));
    options.addOption("s", true, rbi18n.getString("CLI-SignatureFile"));
    options.addOption("p", true, rbi18n.getString("CLI-Password"));
    options.addOption("n", false, rbi18n.getString("CLI-WithoutGUI"));
    options.addOption("f", false, rbi18n.getString("CLI-Finalize"));
    options.addOption("h", false, rbi18n.getString("CLI-Help"));
    options.addOption("b", true, rbi18n.getString("CLI-SigBlock") + langcodes);
    options.addOption("i", true, rbi18n.getString("CLI-SigImage"));
    options.addOption("c", true, rbi18n.getString("CLI-SigComment"));
    options.addOption("r", true, rbi18n.getString("CLI-SigReason"));
    options.addOption("l", true, rbi18n.getString("CLI-SigLocation"));
    options.addOption("e", true, rbi18n.getString("CLI-EmbedSignature"));
    options.addOption("pwdfile", true, rbi18n.getString("CLI-PasswdFile"));
    options.addOption("ownerpwd", true, rbi18n.getString("CLI-OwnerPasswd"));
    options.addOption("ownerpwdfile", true, rbi18n.getString("CLI-OwnerPasswdFile"));
    options.addOption("z", false, rbi18n.getString("CLI-LastPage"));

    CommandLineParser parser = new PosixParser();
    HelpFormatter usage = new HelpFormatter();
    try {
        cmd = parser.parse(options, args);
        input = cmd.getOptionValue("t", "");
        output = cmd.getOptionValue("o", "");
        signature = cmd.getOptionValue("s", "");
        password = cmd.getOptionValue("p", "");
        nogui = cmd.hasOption("n");
        help = cmd.hasOption("h");
        finalize = !cmd.hasOption("f");
        sigblock = cmd.getOptionValue("b", "");
        sigimage = cmd.getOptionValue("i", "");
        comment = cmd.getOptionValue("c", "");
        reason = cmd.getOptionValue("r", "");
        location = cmd.getOptionValue("l", "");
        embedParams = cmd.getOptionValue("e", "");
        pwdFile = cmd.getOptionValue("pwdfile", "");
        ownerPwdString = cmd.getOptionValue("ownerpwd", "");
        ownerPwdFile = cmd.getOptionValue("ownerpwdfile", "");
        lastPage = !cmd.hasOption("z");

        if (cmd.getArgs().length != 0) {
            throw new ParseException(rbi18n.getString("CLI-UnknownArguments"));
        }
    } catch (ParseException e) {
        System.err.println(rbi18n.getString("CLI-WrongArguments"));
        usage.printHelp("PortableSigner", options);
        System.exit(3);
    }
    if (nogui) {
        if (input.equals("") || output.equals("") || signature.equals("")) {
            System.err.println(rbi18n.getString("CLI-MissingArguments"));
            usage.printHelp("PortableSigner", options);
            System.exit(2);
        }
        if (!help) {
            if (password.equals("")) {
                // password missing
                if (!pwdFile.equals("")) {
                    // read the password from the given file
                    try {
                        FileInputStream pwdfis = new FileInputStream(pwdFile);
                        byte[] pwd = new byte[1024];
                        password = "";
                        try {
                            do {
                                int r = pwdfis.read(pwd);
                                if (r < 0) {
                                    break;
                                }
                                password += new String(pwd);
                                password = password.trim();
                            } while (pwdfis.available() > 0);
                            pwdfis.close();
                        } catch (IOException ex) {
                        }
                    } catch (FileNotFoundException fnfex) {
                    }
                } else {
                    // no password file given, read from standard input
                    System.out.print(rbi18n.getString("CLI-MissingPassword"));
                    Console con = System.console();
                    if (con == null) {
                        byte[] pwd = new byte[1024];
                        password = "";
                        try {
                            do {
                                int r = System.in.read(pwd);
                                if (r < 0) {
                                    break;
                                }
                                password += new String(pwd);
                                password = password.trim();
                            } while (System.in.available() > 0);
                        } catch (IOException ex) {
                        }
                    } else {
                        // Console not null. Use it to read the password without echo
                        char[] pwd = con.readPassword();
                        if (pwd != null) {
                            password = new String(pwd);
                        }
                    }
                }
            }
            if (ownerPwdString.equals("") && ownerPwdFile.equals("")) {
                // no owner password or owner password file given, read from standard input
                System.out.print(rbi18n.getString("CLI-MissingOwnerPassword") + " ");
                Console con = System.console();
                if (con == null) {
                    byte[] pwd = new byte[1024];
                    String tmppassword = "";
                    try {
                        do {
                            int r = System.in.read(pwd);
                            if (r < 0) {
                                break;
                            }
                            tmppassword += new String(pwd, 0, r);
                            tmppassword = tmppassword.trim();
                        } while (System.in.available() > 0);
                    } catch (java.io.IOException ex) {
                        // TODO: perhaps notify the user
                    }
                    ownerPwd = tmppassword.getBytes();
                } else {
                    // Console not null. Use it to read the password without echo
                    char[] pwd = con.readPassword();
                    if (pwd != null) {
                        ownerPwd = new byte[pwd.length];
                        for (int i = 0; i < pwd.length; i++) {
                            ownerPwd[i] = (byte) pwd[i];
                        }
                    }
                }
            } else if (!ownerPwdString.equals("")) {
                ownerPwd = ownerPwdString.getBytes();
            } else if (!ownerPwdFile.equals("")) {
                try {
                    FileInputStream pwdfis = new FileInputStream(ownerPwdFile);
                    ownerPwd = new byte[0];
                    byte[] tmp = new byte[1024];
                    byte[] full;
                    try {
                        do {
                            int r = pwdfis.read(tmp);
                            if (r < 0) {
                                break;
                            }
                            // trim the length:
                            tmp = Arrays.copyOfRange(tmp, 0, r);
                            //System.arraycopy(tmp, 0, tmp, 0, r);
                            full = new byte[ownerPwd.length + tmp.length];
                            System.arraycopy(ownerPwd, 0, full, 0, ownerPwd.length);
                            System.arraycopy(tmp, 0, full, ownerPwd.length, tmp.length);
                            ownerPwd = full;
                        } while (pwdfis.available() > 0);
                        pwdfis.close();
                    } catch (IOException ex) {
                    }
                } catch (FileNotFoundException fnfex) {
                }
            }
        }

    }
    if (!embedParams.equals("")) {
        String[] parameter = null;
        parameter = embedParams.split(",");
        try {
            Float vPosF = new Float(parameter[0]), lMarginF = new Float(parameter[1]),
                    rMarginF = new Float(parameter[2]);
            vPos = vPosF.floatValue();
            lMargin = lMarginF.floatValue();
            rMargin = rMarginF.floatValue();
            noSigPage = true;
        } catch (NumberFormatException nfe) {
            System.err.println(rbi18n.getString("CLI-embedParameter-Error"));
            usage.printHelp("PortableSigner", options);
            System.exit(5);
        }
    }
    if (!(langcodes.contains(sigblock) || sigblock.equals(""))) {
        System.err.println(rbi18n.getString("CLI-Only-german-english") + langcodes);
        usage.printHelp("PortableSigner", options);
        System.exit(4);
    }
    if (help) {
        usage.printHelp("PortableSigner", options);
        System.exit(1);
    }
    //        System.err.println("CMDline: input: " + input);
    //        System.err.println("CMDline: output: " + output);
    //        System.err.println("CMDline: signature: " + signature);
    //        System.err.println("CMDline: password: " + password);
    //        System.err.println("CMDline: sigblock: " + sigblock);
    //        System.err.println("CMDline: sigimage: " + sigimage);
    //        System.err.println("CMDline: comment: " + comment);
    //        System.err.println("CMDline: reason: " + reason);
    //        System.err.println("CMDline: location: " + location);
    //        System.err.println("CMDline: pwdFile: " + pwdFile);
    //        System.err.println("CMDline: ownerPwdFile: " + ownerPwdFile);
    //        System.err.println("CMDline: ownerPwdString: " + ownerPwdString);
    //        System.err.println("CMDline: ownerPwd: " + ownerPwd.toString());
}

From source file:com.grass.caishi.cc.activity.AdAddActivity.java

public void addToListImage(final String path) {
    if (path != null) {
        dialog.setMessage("...");
        dialog.show();//w  ww.j  ava  2s  .com
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                File file = new File(path);
                imageUrl = path;
                FileInputStream fis = null;
                try {
                    int quality = 90;
                    fis = new FileInputStream(file);
                    int size = fis.available() / 1024;
                    if (size > 150) {
                        BitmapFactory.Options opts = new BitmapFactory.Options();
                        opts.inJustDecodeBounds = true;
                        resizeBmp = BitmapFactory.decodeFile(path, opts);

                        int pic_width = opts.outWidth;
                        int pic_height = opts.outHeight;
                        int be = 1;
                        if (pic_height > pic_width && pic_width > 1500) {
                            be = (int) Math.rint(pic_width / 1440.0);
                        } else if (pic_height < pic_width && pic_height > 2600) {
                            be = (int) Math.rint(pic_height / 2560.0);
                        }
                        if (be <= 0)
                            be = 1;
                        opts.inSampleSize = be;// 
                        opts.inJustDecodeBounds = false;
                        resizeBmp = BitmapFactory.decodeFile(path, opts);
                        pic_width = opts.outWidth;
                        pic_height = opts.outHeight;
                        File dirFile = new File(Environment.getExternalStorageDirectory(),
                                Constant.CACHE_DIR_IMAGE);
                        if (!dirFile.exists()) {
                            dirFile.mkdirs();
                        }
                        int drive_width = MetricsUnit.getWidth(AdAddActivity.this);
                        int drive_height = MetricsUnit.getHeight(AdAddActivity.this);

                        float my_width = (float) drive_width;
                        float my_height = (float) drive_height;

                        double doo = 0.0;
                        if (pic_width > my_width) {
                            doo = (double) my_width / (double) pic_width;
                            my_height = (int) (pic_height * doo);
                        }

                        int c_h = 0;

                        if (my_height > drive_height) {
                            c_h = (int) ((pic_height - my_height) / 2);
                            if (c_h < 0) {
                                c_h = 0;
                            }
                        }
                        Matrix matrix = new Matrix();
                        matrix.postScale(my_width / pic_width, my_height / pic_height);

                        resizeBmp = Bitmap.createBitmap(resizeBmp, 0, c_h, pic_width, pic_height, matrix, true);
                        File jpegTrueFile = new File(dirFile, "img_" + System.currentTimeMillis() + ".jpg");
                        FileOutputStream fileOutputStream = new FileOutputStream(jpegTrueFile);

                        resizeBmp.compress(CompressFormat.JPEG, quality, fileOutputStream);
                        imageUrl = jpegTrueFile.getAbsolutePath();
                        // MyApplication.getInstance().setMatchImages(jpegTrueFile.getAbsolutePath());

                        //bit.recycle();

                    } else {
                        resizeBmp = BitmapFactory.decodeStream(fis);
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (select_type == 1) {
                                path_logo = imageUrl;
                                img_logo.setImageBitmap(resizeBmp);
                            } else if (select_type == 2) {
                                path_price = imageUrl;
                                img_price.setImageBitmap(resizeBmp);
                            } else if (select_type == 3) {
                                MyApplication.getInstance().setMatchImages(imageUrl);
                                adapter.notifyDataSetChanged();
                            }
                            if (dialog.isShowing()) {
                                dialog.dismiss();
                            }
                        }
                    });

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

From source file:org.signserver.client.cli.validationservice.ValidateCertificateCommand.java

private int run() throws Exception {

    // read certificate
    X509Certificate cert = null;/*w ww. j av a  2s .co m*/
    FileInputStream fis = new FileInputStream(certPath);
    try {
        if (pemFlag) {
            Collection<?> certs = CertTools.getCertsFromPEM(fis);
            if (certs.iterator().hasNext()) {
                cert = (X509Certificate) certs.iterator().next();
            }
        } else {
            byte[] data = new byte[fis.available()];
            fis.read(data, 0, fis.available());
            cert = (X509Certificate) CertTools.getCertfromByteArray(data);
        }
    } finally {
        fis.close();
    }

    if (cert == null) {
        println("Error, Certificate in file " + certPath + " not read succesfully.");
    }

    println("\n\nValidating certificate with: ");
    println("  Subject    : " + cert.getSubjectDN().toString());
    println("  Issuer     : " + cert.getIssuerDN().toString());
    println("  Valid From : " + cert.getNotBefore());
    println("  Valid To   : " + cert.getNotAfter());

    println("\n");

    // validate
    final ValidateResponse vresp;
    switch (protocol) {
    case WEBSERVICES:
        // set up trust
        SSLSocketFactory sslf = null;
        if (trustStorePath != null) {
            sslf = WSClientUtil.genCustomSSLSocketFactory(null, null, trustStorePath, trustStorePwd);
        }

        vresp = runWS(sslf, cert);
        break;
    case HTTP:
        vresp = runHTTP(cert);
        break;
    default:
        throw new IllegalArgumentException("Unknown protocol: " + protocol.toString());
    }
    ;

    // output result
    String certificatePurposes = vresp.getValidCertificatePurposes();
    println("Valid Certificate Purposes:\n  " + (certificatePurposes == null ? "" : certificatePurposes));
    Validation validation = vresp.getValidation();
    println("Certificate Status:\n  " + validation.getStatus());

    return getReturnValue(validation.getStatus());
}

From source file:cn.com.teamlink.workbench.ExplorerActivity.java

public void onCreate(Bundle savedInstanceState) {
    // /*from ww  w  .  j  a  va2 s  .c  om*/
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // ?
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_explorer);

    try {
        gridview = (GridView) findViewById(R.id.explorer_grid_view);

        gridViewListItems = new ArrayList<HashMap<String, String>>();
        /*
        gridViewListItemAdapter = new SimpleAdapter(
            this,
            // ???
            gridViewListItems,
            R.layout.explorer_item,
            new String[]{"item_text"},
            new int[]{R.id.item_text_view}
        );
        */

        gridViewListItemAdapter = new BaseAdapter() {

            @Override
            public int getCount() {
                return gridViewListItems.size();
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public int getItemViewType(int position) {
                // TODO Auto-generated method stub
                Map<String, String> item = gridViewListItems.get(position);
                if (item.get("type").equals("GRID_HEADER")) {
                    return 1;
                }
                return 0;
            }

            @Override
            public int getViewTypeCount() {
                return 2;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                if (getItemViewType(position) == 0) {
                    GridViewHeaderHolder gridViewHeaderHolder = null;

                    if (convertView != null) {
                        gridViewHeaderHolder = (GridViewHeaderHolder) convertView.getTag();
                    } else {
                        gridViewHeaderHolder = new GridViewHeaderHolder();

                        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
                        convertView = inflater.inflate(R.layout.explorer_item, parent, false);

                        gridViewHeaderHolder.itemTextView = (TextView) convertView
                                .findViewById(R.id.item_text_view);
                        convertView.setTag(gridViewHeaderHolder);
                    }

                    gridViewHeaderHolder.itemTextView
                            .setText(gridViewListItems.get(position).get("item_text").toString());

                } else {

                    GridViewItemHolder gridViewItemHolder = null;

                    if (convertView != null) {
                        gridViewItemHolder = (GridViewItemHolder) convertView.getTag();
                    } else {
                        gridViewItemHolder = new GridViewItemHolder();

                        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
                        convertView = inflater.inflate(R.layout.explorer_item, parent, false);
                        convertView.setBackgroundResource(R.color.deepGray);

                        gridViewItemHolder.itemTextView = (TextView) convertView
                                .findViewById(R.id.item_text_view);
                        convertView.setTag(gridViewItemHolder);
                    }

                    gridViewItemHolder.itemTextView
                            .setText(gridViewListItems.get(position).get("item_text").toString());

                }

                return convertView;
            }
        };

        // 
        gridview.setAdapter(gridViewListItemAdapter);
        // ??
        gridview.setOnItemClickListener(new ItemClickListener());

        // 
        addHeader();

        // ?
        addData();
    } catch (Exception e) {
        Dialog alertDialog = new AlertDialog.Builder(this).setTitle("??").setMessage(e.getMessage())
                .setIcon(R.mipmap.ic_launcher).create();
        alertDialog.show();
    }

    try {
        // ??
        String fileName = "fileDemo.txt";
        // ??
        FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
        String text = "Some data";
        // ?
        fos.write(text.getBytes());
        // ?
        fos.flush();
        // FileOutputStream
        fos.close();

        // String fileName = "fileDemo.txt";
        FileInputStream fis = openFileInput(fileName);
        byte[] readBytes = new byte[fis.available()];
        while (fis.read(readBytes) != -1) {

        }

        Dialog alertDialog = new AlertDialog.Builder(this).setTitle("??").setMessage(new String(readBytes))
                .setIcon(R.mipmap.ic_launcher).create();
        alertDialog.show();
    } catch (Exception e) {

        Dialog alertDialog = new AlertDialog.Builder(this).setTitle("??")
                .setMessage(e.getLocalizedMessage()).setIcon(R.mipmap.ic_launcher).create();
        alertDialog.show();

        /*
        Dialog alertDialog = new AlertDialog.Builder(this).
            setTitle("").
            setMessage("???").
            setIcon(R.mipmap.ic_launcher).
            setPositiveButton(
                    "",
                    new DialogInterface.OnClickListener() {
                
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }
            ).
            setNegativeButton("?", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            }).
            setNeutralButton("", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            }).
            create();
        alertDialog.show();
        */

        /*
        final String[] arrayFruit = new String[]{"", "?", "?", ""};
        Dialog alertDialog = new AlertDialog
            .Builder(this).
            setTitle("??").
            setIcon(R.mipmap.ic_launcher)
            .setItems(
                    arrayFruit,
                    new DialogInterface.OnClickListener() {
                
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(ExplorerActivity.this, arrayFruit[which], Toast.LENGTH_SHORT).show();
                        }
                    }
            )
            .setNegativeButton(
                    "?",
                    new DialogInterface.OnClickListener() {
                
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    }
            ).create();
        alertDialog.show();
        */

        /*
        // int selectedFruitIndex = 0;
        final String[] arrayFruit = new String[]{"", "?", "?", ""};
                
        Dialog alertDialog = new AlertDialog.Builder(this)
            .setTitle("??")
            .setIcon(R.mipmap.ic_launcher)
            .setSingleChoiceItems(arrayFruit, 0, new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    selectedFruitIndex = which;
                }
            })
            .setPositiveButton("", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(Dialog_AlertDialogDemoActivity.this, arrayFruit[selectedFruitIndex], Toast.LENGTH_SHORT).show();
                }
            }).setNegativeButton("?", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            }).create();
        alertDialog.show();
        */

        /*
        final String[] arrayFruit = new String[]{"", "?", "?", ""};
        final boolean[] arrayFruitSelected = new boolean[]{true, true, false, false};
                
        Dialog alertDialog = new AlertDialog.Builder(this)
            .setTitle("??")
            .setIcon(R.mipmap.ic_launcher)
            .setMultiChoiceItems(arrayFruit, arrayFruitSelected, new DialogInterface.OnMultiChoiceClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    arrayFruitSelected[which] = isChecked;
                }
            })
            .setPositiveButton("", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < arrayFruitSelected.length; i++) {
                        if (arrayFruitSelected[i] == true) {
                            stringBuilder.append(arrayFruit[i] + "?");
                        }
                    }
                    Toast.makeText(ExplorerActivity.this, stringBuilder.toString(), Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton("?", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            }).create();
        alertDialog.show();
        */

        /*
        // ?View
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View myLoginView = layoutInflater.inflate(R.layout.login, null);
                
        Dialog alertDialog = new AlertDialog.Builder(this)
            .setTitle("")
            .setIcon(R.mipmap.ic_launcher)
            .setView(myLoginView)
            .setPositiveButton("", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            })
            .setNegativeButton("?", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                }
            }).create();
        alertDialog.show();
        */
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.DataSourcePublishACLTest.java

@Test
public void testDSW_ACL() throws Exception {
    repositoryBase.login(singleTenantAdminUserName, defaultTenant,
            new String[] { repositoryBase.getTenantAdminRoleName(), AUTHENTICATED_ROLE_NAME });

    final String domainID = "test.xmi";
    final FileInputStream metadataFile = new FileInputStream("test-res/test.xmi");
    final boolean overwrite = true;

    MultiPart part = new FormDataMultiPart().field("domainId", domainID)
            .field("overwrite", String.valueOf(overwrite)).bodyPart(
                    new FormDataBodyPart(
                            FormDataContentDisposition.name("metadataFile").fileName("test.xmi")
                                    .size(metadataFile.available()).build(),
                            metadataFile, MediaType.TEXT_XML_TYPE));

    WebResource webResource = resource();

    final ClientResponse noDSW = webResource.path(DATA_ACCESS_API_DATASOURCE_DSW + domainID + "/acl")
            .get(ClientResponse.class);
    assertEquals(Response.Status.CONFLICT.getStatusCode(), noDSW.getStatus());

    ClientResponse postAnalysis = webResource.path(DATA_ACCESS_API_DATASOURCE_DSW + "import")
            .type(MediaType.MULTIPART_FORM_DATA_TYPE).put(ClientResponse.class, part);
    assertEquals(Response.Status.OK.getStatusCode(), postAnalysis.getStatus());

    final ClientResponse noACL = webResource.path(DATA_ACCESS_API_DATASOURCE_DSW + domainID + "/acl")
            .get(ClientResponse.class);
    assertEquals(Response.Status.NOT_FOUND.getStatusCode(), noACL.getStatus());

    repositoryBase.login(USERNAME_SUZY, defaultTenant, new String[] { AUTHENTICATED_ROLE_NAME });
    checkDSW(webResource, domainID, true);

    repositoryBase.login(singleTenantAdminUserName, defaultTenant,
            new String[] { repositoryBase.getTenantAdminRoleName(), AUTHENTICATED_ROLE_NAME });
    final ClientResponse setSuzyACL = webResource.path(DATA_ACCESS_API_DATASOURCE_DSW + domainID + "/acl")
            .put(ClientResponse.class, generateACL(USERNAME_SUZY, RepositoryFileSid.Type.USER));
    assertEquals(Response.Status.OK.getStatusCode(), setSuzyACL.getStatus());

    repositoryBase.login(USERNAME_SUZY, defaultTenant, new String[] { AUTHENTICATED_ROLE_NAME });
    checkDSW(webResource, domainID, true);

    final ClientResponse noAccessACL = webResource.path(DATA_ACCESS_API_DATASOURCE_DSW + domainID + "/acl")
            .get(ClientResponse.class);
    assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), noAccessACL.getStatus());

    final ClientResponse noAccessACLNoDS = webResource
            .path(DATA_ACCESS_API_DATASOURCE_DSW + domainID + "_not_exist/acl").get(ClientResponse.class);
    assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), noAccessACLNoDS.getStatus());
}

From source file:org.sakaiproject.tool.assessment.contentpackaging.ImportService.java

public String unzipImportFile(String filename) {
    FileInputStream fileInputStream = null;
    FileOutputStream ofile = null;
    ZipInputStream zipStream = null;
    ZipEntry entry = null;//  w w w .  ja v a2s.  c  om

    ExternalContext external = FacesContext.getCurrentInstance().getExternalContext();
    StringBuilder unzipLocation = new StringBuilder(
            (String) ((ServletContext) external.getContext()).getAttribute("FILEUPLOAD_REPOSITORY_PATH"));
    log.debug("****" + unzipLocation);
    unzipLocation.append("/jsf/upload_tmp/qti_imports/");
    unzipLocation.append(AgentFacade.getAgentString());
    unzipLocation.append("/unzip_files/");
    unzipLocation.append(Long.toString(new java.util.Date().getTime()));

    try {
        fileInputStream = new FileInputStream(new File(filename));
        byte[] data = new byte[fileInputStream.available()];
        fileInputStream.read(data, 0, fileInputStream.available());

        File dir = new File(unzipLocation.toString()); // directory where file would be saved
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                log.error("unable to mkdir " + dir.getPath());
            }
        }

        Set dirsMade = new TreeSet();
        zipStream = new ZipInputStream(new ByteArrayInputStream(data));
        entry = (ZipEntry) zipStream.getNextEntry();
        // Get the name of the imported zip file name. The value of "filename" has timestamp append to it.
        String tmpName = filename.substring(filename.lastIndexOf("/") + 1);
        qtiFilename = "exportAssessment.xml";
        ArrayList xmlFilenames = new ArrayList();
        while (entry != null) {
            String zipName = entry.getName();
            int ix = zipName.lastIndexOf('/');
            if (ix > 0) {
                String dirName = zipName.substring(0, ix);
                if (!dirsMade.contains(dirName)) {
                    File d = new File(dir.getPath() + "/" + dirName);
                    // If it already exists as a dir, don't do anything
                    if (!(d.exists() && d.isDirectory())) {
                        // Try to create the directory, warn if it fails
                        if (!d.mkdirs()) {
                            log.error("unable to mkdir " + dir.getPath() + "/" + dirName);
                        }
                        dirsMade.add(dirName);
                    }
                }
            }

            File zipEntryFile = new File(dir.getPath() + "/" + entry.getName());
            if (!zipEntryFile.isDirectory()) {
                ofile = new FileOutputStream(zipEntryFile);
                byte[] buffer = new byte[1024 * 10];
                int bytesRead;
                while ((bytesRead = zipStream.read(buffer)) != -1) {
                    ofile.write(buffer, 0, bytesRead);
                }
            }

            // Now try to get the QTI xml file name from the imsmanifest.xml
            if ("imsmanifest.xml".equals(entry.getName())) {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.parse(zipEntryFile);
                    doc.getDocumentElement().normalize();
                    NodeList nodeLst = doc.getElementsByTagName("resource");
                    Node fstNode = nodeLst.item(0);
                    NamedNodeMap namedNodeMap = fstNode.getAttributes();
                    qtiFilename = namedNodeMap.getNamedItem("href").getNodeValue();
                } catch (Exception e) {
                    log.error("error parsing imsmanifest.xml");
                }
            } else if (entry.getName() != null && entry.getName().trim().endsWith(".xml")) {
                xmlFilenames.add(entry.getName().trim());
            }

            zipStream.closeEntry();
            entry = zipStream.getNextEntry();
        }
        // If the QTI file doesn't exist in the zip, 
        // we guess the name might be either exportAssessment.xml or the same as the zip file name
        if (!xmlFilenames.contains(qtiFilename.trim())) {
            if (xmlFilenames.contains("exportAssessment.xml")) {
                qtiFilename = "exportAssessment.xml";
            } else {
                qtiFilename = tmpName.substring(0, tmpName.lastIndexOf("_")) + ".xml";
            }
        }
    } catch (FileNotFoundException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        if (ofile != null) {
            try {
                ofile.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (zipStream != null) {
            try {
                zipStream.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
    return unzipLocation.toString();
}