Example usage for java.io IOException getStackTrace

List of usage examples for java.io IOException getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

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

Usage

From source file:com.chinamobile.bcbsp.partition.HashWithBalancerWritePartition.java

/**
 * This method is used to partition graph vertexes. Writing Each vertex to the
 * corresponding partition. In this method calls recordParse method to create
 * an HeadNode object. The last call partitioner's getPartitionId method to
 * calculate the HeadNode belongs to partition's id. If the HeadNode belongs
 * local partition then written to the local partition or send it to the
 * appropriate partition.//from   w w w.j a v  a2s .co m
 * @param recordReader The recordreader of the split.
 * @throws IOException The io exception
 * @throws InterruptedException The Interrupted Exception
 */
@Override
public void write(RecordReader recordReader) throws IOException, InterruptedException {
    int headNodeNum = 0;
    int local = 0;
    int send = 0;
    int lost = 0;
    ThreadPool tpool = new ThreadPool(this.sendThreadNum);
    int staffNum = this.staff.getStaffNum();
    BytesWritable kbytes = new BytesWritable();
    int ksize = 0;
    BytesWritable vbytes = new BytesWritable();
    int vsize = 0;
    DataOutputBuffer bb = new DataOutputBuffer();
    int bufferSize = (int) ((this.TotalCacheSize * CONTAINERNUMBER * CONTAINERNUMBER) * PART);
    int dataBufferSize = (this.TotalCacheSize * CONTAINERNUMBER * CONTAINERNUMBER)
            / (this.staff.getStaffNum() + this.sendThreadNum);
    byte[] buffer = new byte[bufferSize];
    int bufindex = 0;
    SerializationFactory sFactory = new SerializationFactory(new Configuration());
    Serializer<IntWritable> psserializer = sFactory.getSerializer(IntWritable.class);
    byte[] pidandsize = new byte[TIME * CONTAINERNUMBER * CONTAINERNUMBER];
    int psindex = 0;
    BytesWritable pidbytes = new BytesWritable();
    int psize = 0;
    BytesWritable sizebytes = new BytesWritable();
    int ssize = 0;
    try {
        this.keyserializer.open(bb);
        this.valueserializer.open(bb);
        psserializer.open(bb);
    } catch (IOException e) {
        throw e;
    }
    String path = "/tmp/bcbsp/" + this.staff.getJobID() + "/" + this.staff.getStaffID();
    File dir = new File("/tmp/bcbsp/" + this.staff.getJobID());
    dir.mkdir();
    dir = new File("/tmp/bcbsp/" + this.staff.getJobID() + "/" + this.staff.getStaffID());
    dir.mkdir();
    ArrayList<File> files = new ArrayList<File>();
    try {
        File file = new File(path + "/" + "data" + ".txt");
        files.add(file);
        DataOutputStream dataWriter = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(path + "/" + "data" + ".txt", true)));
        DataInputStream dataReader = new DataInputStream(
                new BufferedInputStream(new FileInputStream(path + "/" + "data" + ".txt")));
        File filet = new File(path + "/" + "pidandsize" + ".txt");
        files.add(filet);
        DataOutputStream psWriter = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(path + "/" + "pidandsize" + ".txt", true)));
        DataInputStream psReader = new DataInputStream(
                new BufferedInputStream(new FileInputStream(path + "/" + "pidandsize" + ".txt")));
        while (recordReader != null && recordReader.nextKeyValue()) {
            headNodeNum++;
            Text key = new Text(recordReader.getCurrentKey().toString());
            Text value = new Text(recordReader.getCurrentValue().toString());
            int pid = -1;
            Text vertexID = this.recordParse.getVertexID(key);
            if (vertexID != null) {
                pid = this.partitioner.getPartitionID(vertexID);
            } else {
                lost++;
                continue;
            }
            if (this.counter.containsKey(pid)) {
                this.counter.put(pid, (this.counter.get(pid) + 1));
            } else {
                this.counter.put(pid, 1);
            }
            bb.reset();
            this.keyserializer.serialize(key);
            kbytes.set(bb.getData(), 0, bb.getLength());
            ksize = kbytes.getLength();
            bb.reset();
            this.valueserializer.serialize(value);
            vbytes.set(bb.getData(), 0, bb.getLength());
            vsize = vbytes.getLength();
            bb.reset();
            psserializer.serialize(new IntWritable(ksize + vsize));
            sizebytes.set(bb.getData(), 0, bb.getLength());
            ssize = sizebytes.getLength();
            bb.reset();
            psserializer.serialize(new IntWritable(pid));
            pidbytes.set(bb.getData(), 0, bb.getLength());
            psize = pidbytes.getLength();
            if ((pidandsize.length - psindex) > (ssize + psize)) {
                System.arraycopy(sizebytes.getBytes(), 0, pidandsize, psindex, ssize);
                psindex += ssize;
                System.arraycopy(pidbytes.getBytes(), 0, pidandsize, psindex, psize);
                psindex += psize;
            } else {
                psWriter.write(pidandsize, 0, psindex);
                psindex = 0;
                System.arraycopy(sizebytes.getBytes(), 0, pidandsize, psindex, ssize);
                psindex += ssize;
                System.arraycopy(pidbytes.getBytes(), 0, pidandsize, psindex, psize);
                psindex += psize;
            }
            if ((buffer.length - bufindex) > (ksize + vsize)) {
                System.arraycopy(kbytes.getBytes(), 0, buffer, bufindex, ksize);
                bufindex += ksize;
                System.arraycopy(vbytes.getBytes(), 0, buffer, bufindex, vsize);
                bufindex += vsize;
            } else if (buffer.length < (ksize + vsize)) {
                dataWriter.write(buffer, 0, bufindex);
                bufindex = 0;
                LOG.info("This is a super record");
                dataWriter.write(kbytes.getBytes(), 0, ksize);
                dataWriter.write(vbytes.getBytes(), 0, vsize);
            } else {
                dataWriter.write(buffer, 0, bufindex);
                bufindex = 0;
                System.arraycopy(kbytes.getBytes(), 0, buffer, bufindex, ksize);
                bufindex += ksize;
                System.arraycopy(vbytes.getBytes(), 0, buffer, bufindex, vsize);
                bufindex += vsize;
            }
        }
        if (psindex != 0) {
            psWriter.write(pidandsize, 0, psindex);
        }
        if (bufindex != 0) {
            dataWriter.write(buffer, 0, bufindex);
            bufindex = 0;
        }
        dataWriter.close();
        dataWriter = null;
        psWriter.close();
        psWriter = null;
        buffer = null;
        pidandsize = null;
        this.ssrc.setDirFlag(new String[] { "3" });
        this.ssrc.setCounter(this.counter);
        HashMap<Integer, Integer> hashBucketToPartition = this.sssc.loadDataInBalancerBarrier(ssrc,
                Constants.PARTITION_TYPE.HASH);
        this.staff.setHashBucketToPartition(hashBucketToPartition);
        byte[][] databuf = new byte[staffNum][dataBufferSize];
        int[] databufindex = new int[staffNum];
        try {
            IntWritable pid = new IntWritable();
            IntWritable size = new IntWritable();
            int belongPid = 0;
            while (true) {
                size.readFields(psReader);
                pid.readFields(psReader);
                belongPid = hashBucketToPartition.get(pid.get());
                if (belongPid != this.staff.getPartition()) {
                    send++;
                } else {
                    local++;
                }
                if ((databuf[belongPid].length - databufindex[belongPid]) > size.get()) {
                    dataReader.read(databuf[belongPid], databufindex[belongPid], size.get());
                    databufindex[belongPid] += size.get();
                } else if (databuf[belongPid].length < size.get()) {
                    LOG.info("This is a super record");
                    byte[] tmp = new byte[size.get()];
                    dataReader.read(tmp, 0, size.get());
                    if (belongPid == this.staff.getPartition()) {
                        DataInputStream reader = new DataInputStream(
                                new BufferedInputStream(new ByteArrayInputStream(tmp)));
                        try {
                            boolean stop = true;
                            while (stop) {
                                Text key = new Text();
                                key.readFields(reader);
                                Text value = new Text();
                                value.readFields(reader);
                                if (key.getLength() > 0 && value.getLength() > 0) {
                                    Vertex vertex = this.recordParse.recordParse(key.toString(),
                                            value.toString());
                                    if (vertex == null) {
                                        lost++;
                                        continue;
                                    }
                                    this.staff.getGraphData().addForAll(vertex);
                                } else {
                                    stop = false;
                                }
                            }
                        } catch (IOException e) {
                            LOG.info("IO exception: " + e.getStackTrace());
                        }
                    } else {
                        ThreadSignle t = tpool.getThread();
                        while (t == null) {
                            t = tpool.getThread();
                        }
                        t.setWorker(
                                this.workerAgent.getWorker(staff.getJobID(), staff.getStaffID(), belongPid));
                        t.setJobId(staff.getJobID());
                        t.setTaskId(staff.getStaffID());
                        t.setBelongPartition(belongPid);
                        BytesWritable data = new BytesWritable();
                        data.set(tmp, 0, size.get());
                        t.setData(data);
                        LOG.info("Using Thread is: " + t.getThreadNumber());
                        t.setStatus(true);
                    }
                    tmp = null;
                } else {
                    if (belongPid == this.staff.getPartition()) {
                        DataInputStream reader = new DataInputStream(new BufferedInputStream(
                                new ByteArrayInputStream(databuf[belongPid], 0, databufindex[belongPid])));
                        try {
                            boolean stop = true;
                            while (stop) {
                                Text key = new Text();
                                key.readFields(reader);
                                Text value = new Text();
                                value.readFields(reader);
                                if (key.getLength() > 0 && value.getLength() > 0) {
                                    Vertex vertex = this.recordParse.recordParse(key.toString(),
                                            value.toString());
                                    if (vertex == null) {
                                        lost++;
                                        continue;
                                    }
                                    this.staff.getGraphData().addForAll(vertex);
                                } else {
                                    stop = false;
                                }
                            }
                        } catch (IOException e) {
                            LOG.info("IO exception: " + e.getStackTrace());
                        }
                    } else {
                        ThreadSignle t = tpool.getThread();
                        while (t == null) {
                            t = tpool.getThread();
                        }
                        t.setWorker(
                                this.workerAgent.getWorker(staff.getJobID(), staff.getStaffID(), belongPid));
                        t.setJobId(staff.getJobID());
                        t.setTaskId(staff.getStaffID());
                        t.setBelongPartition(belongPid);
                        BytesWritable data = new BytesWritable();
                        data.set(databuf[belongPid], 0, databufindex[belongPid]);
                        t.setData(data);
                        LOG.info("Using Thread is: " + t.getThreadNumber());
                        t.setStatus(true);
                    }
                    databufindex[belongPid] = 0;
                    dataReader.read(databuf[belongPid], databufindex[belongPid], size.get());
                    databufindex[belongPid] += size.get();
                }
            }
        } catch (EOFException ex) {
            LOG.error("[write]", ex);
        }
        for (int i = 0; i < staffNum; i++) {
            if (databufindex[i] != 0) {
                if (i == this.staff.getPartition()) {
                    DataInputStream reader = new DataInputStream(
                            new BufferedInputStream(new ByteArrayInputStream(databuf[i], 0, databufindex[i])));
                    try {
                        boolean stop = true;
                        while (stop) {
                            Text key = new Text();
                            key.readFields(reader);
                            Text value = new Text();
                            value.readFields(reader);
                            if (key.getLength() > 0 && value.getLength() > 0) {
                                Vertex vertex = this.recordParse.recordParse(key.toString(), value.toString());
                                if (vertex == null) {
                                    lost++;
                                    continue;
                                }
                                this.staff.getGraphData().addForAll(vertex);
                            } else {
                                stop = false;
                            }
                        }
                    } catch (IOException e) {
                        LOG.info("IO exception: " + e.getStackTrace());
                    }
                } else {
                    ThreadSignle t = tpool.getThread();
                    while (t == null) {
                        t = tpool.getThread();
                    }
                    t.setWorker(this.workerAgent.getWorker(staff.getJobID(), staff.getStaffID(), i));
                    t.setJobId(staff.getJobID());
                    t.setTaskId(staff.getStaffID());
                    t.setBelongPartition(i);
                    BytesWritable data = new BytesWritable();
                    data.set(databuf[i], 0, databufindex[i]);
                    t.setData(data);
                    LOG.info("Using Thread is: " + t.getThreadNumber());
                    t.setStatus(true);
                }
            }
        }
        dataReader.close();
        dataReader = null;
        psReader.close();
        psReader = null;
        for (File f : files) {
            f.delete();
        }
        dir.delete();
        dir = new File(path.substring(0, path.lastIndexOf('/')));
        dir.delete();
        tpool.cleanup();
        tpool = null;
        databuf = null;
        databufindex = null;
        this.counter = null;
        LOG.info("The number of vertices that were read from the input file: " + headNodeNum);
        LOG.info("The number of vertices that were put into the partition: " + local);
        LOG.info("The number of vertices that were sent to other partitions: " + send);
        LOG.info("The number of verteices in the partition that cound not be " + "parsed:" + lost);
    } catch (IOException e) {
        throw e;
    } catch (InterruptedException e) {
        throw e;
    } finally {
        for (File f : files) {
            f.delete();
        }
        dir.delete();
        dir = new File(path.substring(0, path.lastIndexOf('/')));
        dir.delete();
    }
}

From source file:base.BasePlayer.FileRead.java

static String getVCFLine(String chrom, int start, int end, Sample sample) {
    if (Draw.variantcalculator) {
        return "";
    }/*from w ww .j av  a2s .  c om*/
    if (sample.calledvariants) {
        StringBuffer altbases = new StringBuffer("");
        int alts = 0, refs = 0;

        for (int i = 0; i < Main.drawCanvas.varOverLap.vars.size() - 1; i++) {
            altbases.append(Main.drawCanvas.varOverLap.vars.get(i).getKey());

        }
        alts = Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls();
        refs = (Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCoverage()
                - Main.drawCanvas.varOverLap.vars.get(0).getValue().get(0).getCalls());
        String genotype = "";
        if (alts / (double) refs > 0.95) {
            genotype = "1/1";
        } else {
            genotype = "0/1";
        }
        altbases.append(
                Main.drawCanvas.varOverLap.vars.get(Main.drawCanvas.varOverLap.vars.size() - 1).getKey());
        return Main.drawCanvas.splits.get(0).chrom + "\t" + (Main.drawCanvas.varOverLap.getPosition() + 1)
                + "\t.\t" + Main.getBase.get(Main.drawCanvas.varOverLap.getRefBase()) + "\t" + altbases
                + "\t99\tPASS\tINFO\tGT:AD:DP\t" + genotype + ":" + refs + "," + alts + ":" + (refs + alts);
    }
    String line = "";

    cancelfileread = false;
    cancelvarcount = false;

    try {
        if (!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) {
            if (sample.multipart) {
                for (int i = sample.getIndex(); i >= 0; i--) {
                    if (!Main.drawCanvas.sampleList.get(i).multipart) {
                        sample = Main.drawCanvas.sampleList.get(i);
                        break;
                    }
                }
            }
            if (sample.getTabixFile() != null) {

                setVCFFileStart(chrom, start, end + 3, sample);
                boolean vcf = sample.getVCFReader() != null;
                while (line != null) {
                    if (vcf) {
                        try {
                            sample.getVCFReader().ready();
                        } catch (IOException ex) {

                        }
                    }
                    try {
                        if (vcf) {

                            line = sample.getVCFReader().readLine();
                        } else {

                            line = sample.getVCFInput().readLine();
                        }
                        if (line == null || line.split("\t").length < 3 || line.startsWith("#")) {
                            continue;
                        }
                        if (line != null && Integer.parseInt(line.split("\t")[1]) == start + 1) {
                            if (sample.getVCFReader() != null) {
                                sample.getVCFReader().close();
                            }
                            return line;
                        }

                    } catch (Exception ex) {
                        Main.showError(ex.getMessage(), "Error");

                        ErrorLog.addError(ex.getStackTrace());
                        ex.printStackTrace();
                        Main.cancel();
                        changing = false;

                    }

                }

                if (sample.getVCFReader() != null) {
                    sample.getVCFReader().close();
                }

                return line;
            }
        }
    } catch (Exception exc) {
        Main.showError(exc.getMessage(), "Error");

        System.out.println(sample.getName());
        exc.printStackTrace();
        ErrorLog.addError(exc.getStackTrace());
        changing = false;
    }
    return "";
}

From source file:base.BasePlayer.FileRead.java

void getVariants(String chrom, int start, int end, Sample sample) {
    if (sample.calledvariants) {
        Main.drawCanvas.variantsStart = start;
        Main.drawCanvas.variantsEnd = end;
        return;/*from  w w w .  j a  v  a  2 s  . c  om*/
    }
    String line;
    String[] split;
    cancelfileread = false;
    cancelvarcount = false;

    try {
        if (!(VariantHandler.hideIndels.isSelected() && VariantHandler.hideSNVs.isSelected())) {
            readFiles = true;
            Main.drawCanvas.splits.get(0).transStart = 0;
            Main.drawCanvas.variantsStart = start;
            Main.drawCanvas.variantsEnd = end;
            Main.drawCanvas.loadbarAll = (int) ((sample.getIndex() / (double) (Main.samples)) * 100);

            linecounter = 0;
            if (cancelfileread) {
                cancelFileRead();
                return;
            }
            if (sample.multipart) {
                return;
            }

            if (sample.getTabixFile() != null) {

                String searchChrom = setVCFFileStart(chrom, start, end, sample);

                boolean vcf = sample.getVCFReader() != null;

                if (vcf) {
                    try {
                        sample.getVCFReader().ready();
                    } catch (IOException ex) {
                        return;
                    }
                }

                sample.setMaxCoverage(0F);
                current = head;
                line = "";
                first = true;
                stop = false;

                while (true) {
                    if (stop) {

                        break;
                    }
                    if (cancelfileread || cancelvarcount || !Main.drawCanvas.loading) {
                        cancelFileRead();

                        break;
                    }

                    try {

                        if (vcf) {

                            line = sample.getVCFReader().readLine();

                            if (line != null && line.startsWith("#")) {
                                continue;
                            }
                        } else {
                            try {
                                line = sample.getVCFInput().readLine();
                            } catch (htsjdk.samtools.FileTruncatedException e) {
                                e.printStackTrace();

                            }

                        }
                        if (line == null) {
                            break;
                        }
                    } catch (Exception ex) {
                        Main.showError(ex.getMessage(), "Error");
                        ErrorLog.addError(ex.getStackTrace());
                        ex.printStackTrace();
                        Main.cancel();
                        changing = false;
                        break;
                    }
                    if (sample.oddchar != null) {
                        line = line.replaceAll(sample.oddchar, "");
                    }

                    split = line.split("\\t+");
                    try {
                        if (split[0].startsWith("#")) {
                            continue;
                        }

                        if (vcf && split.length > 2
                                && (Integer.parseInt(split[1]) > end || !split[0].equals(searchChrom))) {

                            break;
                        }

                    } catch (Exception e) {
                        String string = "";
                        for (int i = 0; i < split.length; i++) {
                            string += split[i] + "\t";
                        }

                        ErrorLog.addError(string);
                    }
                    if (sample.getVCFInput() != null) {
                        if (sample.getVCFInput().getFilePointer() > sample.vcfEndPos) {

                            break;
                        }
                    }
                    if (sample.multiVCF) {

                        readLineMulti(split, sample);
                    } else {

                        readLine(split, sample);

                    }
                    if (first) {
                        first = false;
                    }

                }
                if (sample.getVCFReader() != null) {
                    sample.getVCFReader().close();
                }
                Draw.updatevars = true;
                if (sample.getIndex()
                        * Main.drawCanvas.drawVariables.sampleHeight < Main.drawScroll.getViewport().getHeight()
                                + Main.drawCanvas.drawVariables.sampleHeight) {
                    if (Main.drawCanvas.splits.get(0).viewLength < 2000000) {
                        Main.chromDraw.updateExons = true;
                        Main.chromDraw.repaint();
                    }
                }
            }
        }
    } catch (Exception exc) {
        Main.showError(exc.getMessage(), "Error");

        System.out.println(sample.getName());
        exc.printStackTrace();
        ErrorLog.addError(exc.getStackTrace());
        changing = false;
    }

}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

/**
 * Called when the camera view exits.//  w  ww  . j a  v  a2  s. com
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    Log.d(LOG_TAG, "-z");

    // If retrieving photo from library
    if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        Log.d(LOG_TAG, "-y");
        if (resultCode == Activity.RESULT_OK) {
            Log.d(LOG_TAG, "-x");
            Uri uri = intent.getData();
            Log.d(LOG_TAG, "-w");
            // If you ask for video or all media type you will automatically
            // get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                Log.d(LOG_TAG, "mediaType not PICTURE, so must be Video");

                String metadataDateTime = "";
                ExifInterface exif;
                try {
                    exif = new ExifInterface(this.getRealPathFromURI(uri, this.cordova));
                    if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) {
                        Log.d(LOG_TAG, "z4a");
                        metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString();
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                    }
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }

                Log.d(LOG_TAG, "before create thumbnail");
                Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(
                        (new File(this.getRealPathFromURI(uri, this.cordova))).getAbsolutePath(),
                        MediaStore.Images.Thumbnails.MINI_KIND);
                Log.d(LOG_TAG, "after create thumbnail");
                String mid = generateRandomMid();

                try {
                    String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_"
                            + mid + ".jpg";
                    FileOutputStream foMedium = new FileOutputStream(filePathMedium);
                    bitmap.compress(CompressFormat.JPEG, 100, foMedium);
                    foMedium.flush();
                    foMedium.close();

                    bitmap.recycle();
                    System.gc();

                    JSONObject mediaFile = new JSONObject();
                    try {
                        mediaFile.put("mid", mid);
                        mediaFile.put("mediaType", "video");
                        mediaFile.put("filePath", filePathMedium);
                        mediaFile.put("filePathMedium", filePathMedium);
                        mediaFile.put("filePathThumb", filePathMedium);
                        mediaFile.put("typeOfPluginResult", "initialRecordInformer");
                        String absolutePath = (new File(this.getRealPathFromURI(uri, this.cordova)))
                                .getAbsolutePath();
                        mediaFile.put("fileExt", absolutePath.substring(absolutePath.lastIndexOf(".") + 1));
                        if (metadataDateTime != "") {
                            mediaFile.put("metadataDateTime", metadataDateTime);
                        }
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "error: " + e.getStackTrace().toString());
                    }
                    Log.d(LOG_TAG, "mediafile at 638" + mediaFile.toString());
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                            (new JSONArray()).put(mediaFile));
                    pluginResult.setKeepCallback(true);
                    this.callbackContext.sendPluginResult(pluginResult);
                    new UploadVideoToS3Task().execute(new File(this.getRealPathFromURI(uri, this.cordova)),
                            this.callbackContext, mid, mediaFile);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                String imagePath = this.getRealPathFromURI(uri, this.cordova);
                String mimeType = FileUtils.getMimeType(imagePath);
                // If we don't have a valid image so quit.
                if (imagePath == null || mimeType == null || !(mimeType.equalsIgnoreCase("image/jpeg")
                        || mimeType.equalsIgnoreCase("image/png"))) {
                    Log.d(LOG_TAG, "I either have a null image path or bitmap");
                    this.failPicture("Unable to retrieve path to picture!");
                    return;
                }

                String mid = generateRandomMid();

                Log.d(LOG_TAG, "a");

                JSONObject mediaFile = new JSONObject();

                Log.d(LOG_TAG, "b");

                try {
                    FileInputStream fi = new FileInputStream(imagePath);
                    Bitmap bitmap = BitmapFactory.decodeStream(fi);
                    fi.close();

                    Log.d(LOG_TAG, "z1");

                    // try to get exif data
                    ExifInterface exif = new ExifInterface(imagePath);

                    Log.d(LOG_TAG, "z2");

                    JSONObject metadataJson = new JSONObject();

                    Log.d(LOG_TAG, "z3");

                    /*
                    JSONObject latlng = new JSONObject();
                    String lat = "0";
                    String lng = "0";
                    if (exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) != null) {
                       lat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
                    }
                    if (exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) != null) {
                       lng = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
                    }
                    latlng.put("lat", lat);
                    latlng.put("lng", lng);
                    Log.d(LOG_TAG, "z4");
                    metadataJson.put("locationData", latlng);
                    */

                    String metadataDateTime = "";

                    if (exif.getAttribute(ExifInterface.TAG_DATETIME) != null) {
                        Log.d(LOG_TAG, "z4a");
                        JSONObject exifWrapper = new JSONObject();
                        exifWrapper.put("DateTimeOriginal",
                                exif.getAttribute(ExifInterface.TAG_DATETIME).toString());
                        exifWrapper.put("DateTimeDigitized",
                                exif.getAttribute(ExifInterface.TAG_DATETIME).toString());
                        metadataDateTime = exif.getAttribute(ExifInterface.TAG_DATETIME).toString();
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        metadataDateTime = metadataDateTime.replaceFirst(":", "-");
                        Log.d(LOG_TAG, "z5");
                        metadataJson.put("Exif", exifWrapper);
                    }
                    Log.d(LOG_TAG, "z6");

                    Log.d(LOG_TAG, "metadataJson: " + metadataJson.toString());
                    Log.d(LOG_TAG, "metadataDateTime: " + metadataDateTime.toString());

                    if (exif.getAttribute(ExifInterface.TAG_ORIENTATION) != null) {
                        int o = Integer.parseInt(exif.getAttribute(ExifInterface.TAG_ORIENTATION));

                        Log.d(LOG_TAG, "z7");

                        if (o == ExifInterface.ORIENTATION_NORMAL) {
                            rotate = 0;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_90) {
                            rotate = 90;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_180) {
                            rotate = 180;
                        } else if (o == ExifInterface.ORIENTATION_ROTATE_270) {
                            rotate = 270;
                        } else {
                            rotate = 0;
                        }

                        Log.d(LOG_TAG, "z8");

                        Log.d(LOG_TAG, "rotate: " + rotate);

                        // try to correct orientation
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            Log.d(LOG_TAG, "z9");
                            matrix.setRotate(rotate);
                            Log.d(LOG_TAG, "z10");
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                            Log.d(LOG_TAG, "z11");
                        }
                    }

                    Log.d(LOG_TAG, "c");

                    String filePath = this.getTempDirectoryPath(this.cordova.getActivity()) + "/econ_" + mid
                            + ".jpg";
                    FileOutputStream foEcon = new FileOutputStream(filePath);
                    fitInsideSquare(bitmap, 850).compress(CompressFormat.JPEG, 45, foEcon);
                    foEcon.flush();
                    foEcon.close();

                    Log.d(LOG_TAG, "d");

                    String filePathMedium = this.getTempDirectoryPath(this.cordova.getActivity()) + "/medium_"
                            + mid + ".jpg";
                    FileOutputStream foMedium = new FileOutputStream(filePathMedium);
                    makeInsideSquare(bitmap, 320).compress(CompressFormat.JPEG, 55, foMedium);
                    foMedium.flush();
                    foMedium.close();

                    Log.d(LOG_TAG, "e");

                    String filePathThumb = this.getTempDirectoryPath(this.cordova.getActivity()) + "/thumb_"
                            + mid + ".jpg";
                    FileOutputStream foThumb = new FileOutputStream(filePathThumb);
                    makeInsideSquare(bitmap, 175).compress(CompressFormat.JPEG, 55, foThumb);
                    foThumb.flush();
                    foThumb.close();

                    bitmap.recycle();
                    System.gc();

                    Log.d(LOG_TAG, "f");

                    mediaFile.put("mid", mid);
                    mediaFile.put("mediaType", "photo");
                    mediaFile.put("filePath", filePath);
                    mediaFile.put("filePathMedium", filePath);
                    mediaFile.put("filePathThumb", filePath);
                    mediaFile.put("typeOfPluginResult", "initialRecordInformer");
                    //mediaFile.put("metadataJson", metadataJson);
                    if (metadataDateTime != "") {
                        mediaFile.put("metadataDateTime", metadataDateTime);
                    }

                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                            (new JSONArray()).put(mediaFile));
                    pluginResult.setKeepCallback(true);
                    this.callbackContext.sendPluginResult(pluginResult);
                    Log.d(LOG_TAG, "g");
                    Log.d(LOG_TAG, "mediaFile " + mediaFile.toString());
                    new UploadFilesToS3Task().execute(new File(filePath), new File(filePathMedium),
                            new File(filePathThumb), this.callbackContext, mid, mediaFile);
                    Log.d(LOG_TAG, "h");
                } catch (FileNotFoundException e) {
                    Log.d(LOG_TAG, "error: " + e.getStackTrace().toString());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    Log.d(LOG_TAG, "error: " + e1.getStackTrace().toString());
                } catch (JSONException e2) {
                    // TODO Auto-generated catch block
                    Log.d(LOG_TAG, "error: " + e2.getStackTrace().toString());
                }

                /*
                if (this.correctOrientation) {
                   String[] cols = { MediaStore.Images.Media.ORIENTATION };
                   Cursor cursor = this.cordova
                .getActivity()
                .getContentResolver()
                .query(intent.getData(), cols, null, null,
                      null);
                   if (cursor != null) {
                      cursor.moveToPosition(0);
                      rotate = cursor.getInt(0);
                      cursor.close();
                   }
                   if (rotate != 0) {
                      Matrix matrix = new Matrix();
                      matrix.setRotate(rotate);
                      bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                   bitmap.getWidth(), bitmap.getHeight(),
                   matrix, true);
                   }
                }
                        
                // Create an ExifHelper to save the exif
                // data that is lost during compression
                String resizePath = this
                      .getTempDirectoryPath(this.cordova
                   .getActivity())
                      + "/resize.jpg";
                ExifHelper exif = new ExifHelper();
                try {
                   if (this.encodingType == JPEG) {
                      exif.createInFile(resizePath);
                      exif.readExifData();
                      rotate = exif.getOrientation();
                   }
                } catch (IOException e) {
                   e.printStackTrace();
                }
                        
                OutputStream os = new FileOutputStream(
                      resizePath);
                bitmap.compress(Bitmap.CompressFormat.JPEG,
                      this.mQuality, os);
                os.close();
                        
                // Restore exif data to file
                if (this.encodingType == JPEG) {
                   exif.createOutFile(this
                .getRealPathFromURI(uri,
                      this.cordova));
                   exif.writeExifData();
                }
                        
                if (bitmap != null) {
                   bitmap.recycle();
                   bitmap = null;
                }
                System.gc();
                        
                // The resized image is cached by the app in
                // order to get around this and not have to
                // delete your
                // application cache I'm adding the current
                // system time to the end of the file url.
                this.callbackContext.success("file://" + resizePath + "?" + System.currentTimeMillis());
                */
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}