Example usage for java.lang IllegalStateException printStackTrace

List of usage examples for java.lang IllegalStateException printStackTrace

Introduction

In this page you can find the example usage for java.lang IllegalStateException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.opendatakit.common.persistence.engine.gae.TaskLockImpl.java

/**
 * Update the entity with the given values.
 * //from   ww  w  . j ava2  s  . co  m
 * @param transaction
 * @param lockId
 * @param formId
 * @param taskType
 * @param gaeEntity
 * @throws ODKTaskLockException
 */
private void updateValuesNpersist(Transaction transaction, String lockId, String formId, ITaskLockType taskType,
        Entity gaeEntity) throws ODKTaskLockException {
    Long timestamp = System.currentTimeMillis() + taskType.getLockExpirationTimeout();

    dam.recordPutUsage(KIND);
    try {
        gaeEntity.setProperty(TIMESTAMP_PROPERTY, timestamp);
        gaeEntity.setProperty(LOCK_ID_PROPERTY, lockId);
        gaeEntity.setProperty(FORM_ID_PROPERTY, formId);
        gaeEntity.setProperty(TASK_TYPE_PROPERTY, taskType.getName());
        try {
            updateLockIdTimestampMemCache(lockId, formId, taskType, timestamp);
        } finally {
            ds.put(transaction, gaeEntity);
            log.info("Persisting lock : " + lockId + " " + formId + " " + taskType.getName() + " timestamp: "
                    + timestamp);
        }
    } catch (IllegalStateException e) {
        throw new ODKTaskLockException(NO_TRANSACTION_ACTIVE, e);
    } catch (ODKTaskLockException e) {
        throw e;
    } catch (Exception e) { // catches datastore issues...
        e.printStackTrace();
        throw new ODKTaskLockException(OTHER_ERROR, e);
    }
}

From source file:immf.ImodeNetClient.java

/**
 * POST????????/*from   ww  w .  j  a v  a  2  s . c  o m*/
 * @param req
 * @return
 * @throws IOException
 */
private HttpResponse executeHttp(HttpRequestBase req) throws IOException {
    try {
        for (int i = 0; i < 4; i++) {
            HttpResponse res = this.httpClient.execute(req);
            int status = res.getStatusLine().getStatusCode();
            if (300 <= status && status <= 399) {
                req.abort();

                URI location = httpClient.getRedirectHandler().getLocationURI(res, new BasicHttpContext());

                //System.out.println("Redirect "+location);
                req = new HttpGet(location);
                req.setHeader("User-Agent", "Mozilla/4.0 (compatible;MSIE 7.0; Windows NT 6.0;)");
            } else {
                return res;
            }
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        log.info("HttpClient Fatal Error. Restarting HttpCient");
        HttpParams params = this.httpClient.getParams();
        this.httpClient.getConnectionManager().shutdown();
        this.httpClient = new DefaultHttpClient();
        this.httpClient.setParams(params);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        req.abort();
    }
    return null;
}

From source file:zsk.YTDownloadThread.java

boolean downloadone(String sURL) {
    boolean rc = false;
    boolean rc204 = false;
    boolean rc302 = false;

    this.iRecursionCount++;

    // stop recursion
    try {//from  ww  w  . j a v  a  2 s  .c  om
        if (sURL.equals(""))
            return (false);
    } catch (NullPointerException npe) {
        return (false);
    }
    if (JFCMainClient.getbQuitrequested())
        return (false); // try to get information about application shutdown

    debugoutput("start.");

    // TODO GUI option for proxy?
    // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube
    // using local squid to save download time for tests

    try {
        // determine http_proxy environment variable
        if (!this.getProxy().equals("")) {

            String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", "");
            this.proxy = new HttpHost(sproxy.replaceFirst(":(.*)", ""),
                    Integer.parseInt(sproxy.replaceFirst("(.*):", "")), "http");

            SchemeRegistry supportedSchemes = new SchemeRegistry();
            supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
            supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUseExpectContinue(params, true);

            ClientConnectionManager ccm = new PoolingClientConnectionManager(supportedSchemes);

            // with proxy
            this.httpclient = new DefaultHttpClient(ccm, params);
            this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy);
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        } else {
            // without proxy
            this.httpclient = new DefaultHttpClient();
            this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
        }
        this.httpget = new HttpGet(getURI(sURL));
        if (sURL.toLowerCase().startsWith("https"))
            this.target = new HttpHost(getHost(sURL), 443, "https");
        else
            this.target = new HttpHost(getHost(sURL), 80, "http");
    } catch (Exception e) {
        debugoutput(e.getMessage());
    }

    debugoutput("executing request: ".concat(this.httpget.getRequestLine().toString()));
    debugoutput("uri: ".concat(this.httpget.getURI().toString()));
    debugoutput("host: ".concat(this.target.getHostName()));
    debugoutput("using proxy: ".concat(this.getProxy()));

    // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work)
    /*
    this.localContext = new BasicHttpContext();
    if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context)
    ((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient
    */

    // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again?

    try {
        this.response = this.httpclient.execute(this.target, this.httpget, this.localContext);
    } catch (ClientProtocolException cpe) {
        debugoutput(cpe.getMessage());
    } catch (UnknownHostException uhe) {
        output((JFCMainClient.isgerman() ? "Fehler bei der Verbindung zu: " : "error connecting to: ")
                .concat(uhe.getMessage()));
        debugoutput(uhe.getMessage());
    } catch (IOException ioe) {
        debugoutput(ioe.getMessage());
    } catch (IllegalStateException ise) {
        debugoutput(ise.getMessage());
    }

    /*
    CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN);
    CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC);
    CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ;
    try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( )));
    } catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute
    try {
       debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString()));
       debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString()));
       debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString()));
    } catch (NullPointerException npe) {
    }
    */

    try {
        debugoutput("HTTP response status line:".concat(this.response.getStatusLine().toString()));
        //for (int i = 0; i < response.getAllHeaders().length; i++) {
        //   debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue()));
        //}

        // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL?
        if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)"))
                & !(rc204 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)204(.*)"))
                & !(rc302 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)302(.*)"))) {
            debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL));
            output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\""));
            return (rc & rc204 & rc302);
        }
        if (rc204) {
            debugoutput("last response code==204 - download: ".concat(this.vNextVideoURL.get(0).getsYTID()));
            rc = downloadone(this.vNextVideoURL.get(0).getsURL());
            return (rc);
        }
        if (rc302)
            debugoutput(
                    "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString()));

    } catch (NullPointerException npe) {
        // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because
        // response.getStatusLine() == null
        this.sVideoURL = null;
    }

    HttpEntity entity = null;
    try {
        entity = this.response.getEntity();
    } catch (NullPointerException npe) {
    }

    // try to read HTTP response body
    if (entity != null) {
        try {
            if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)"))
                this.textreader = new BufferedReader(new InputStreamReader(entity.getContent()));
            else
                this.binaryreader = new BufferedInputStream(entity.getContent());
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            // test if we got a webpage
            this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase();
            if (this.sContentType.matches("^text/html(.*)")) {
                rc = savetextdata();
                // test if we got the binary content
            } else if (this.sContentType.matches("video/(.)*")) {
                if (JFCMainClient.getbNODOWNLOAD())
                    reportheaderinfo();
                else
                    savebinarydata();
            } else { // content-type is not video/
                rc = false;
                this.sVideoURL = null;
            }
        } catch (IOException ex) {
            try {
                throw ex;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (RuntimeException ex) {
            try {
                throw ex;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } //if (entity != null)

    this.httpclient.getConnectionManager().shutdown();

    debugoutput("done: ".concat(sURL));
    if (this.sVideoURL == null)
        this.sVideoURL = ""; // to prevent NPE

    if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) {
        // no more recursion - html source hase been read
        // test !rc than video could not downloaded because of some error (like wrong protocol or restriction)
        if (!rc) {
            debugoutput("cannot download video - URL does not seem to be valid or could not be found: "
                    .concat(this.sURL));
            output(JFCMainClient.isgerman()
                    ? "es gab ein Problem die Video URL zu finden! evt. wegen Landesinschrnkung?!"
                    : "there was a problem getting the video URL! perhaps not allowed in your country?!");
            output((JFCMainClient.isgerman() ? "erwge die URL dem Autor mitzuteilen!"
                    : "consider reporting the URL to author! - ").concat(this.sURL));
            this.sVideoURL = null;
        }
    } else {
        // enter recursion - download video resource
        debugoutput("try to download video from URL: ".concat(this.sVideoURL));
        rc = downloadone(this.sVideoURL);
    }
    this.sVideoURL = null;

    return (rc);

}

From source file:org.deviceconnect.android.deviceplugin.theta.fragment.ThetaGalleryFragment.java

/** Import data of Theta to storage of App. */
private void exeImportData(final int position) {
    Activity activity = getActivity();//from ww  w .j  a v  a2  s. c  om
    if (activity != null) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (mProgress == null) {
                        mProgress = ThetaDialogFragment.newInstance(getString(R.string.theta_ssid_prefix),
                                getString(R.string.saving));
                        mProgress.show(getActivity().getFragmentManager(), "fragment_dialog");
                    }
                } catch (IllegalStateException e) { //background
                    if (BuildConfig.DEBUG) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    new Thread(new Runnable() {
        @Override
        public void run() {
            ThetaObject importObj = mUpdateThetaList.get(position);
            mStorage.addThetaObjectCache(importObj);
        }
    }).start();
}

From source file:com.moonpi.tapunlock.MainActivity.java

public void killForegroundDispatch() {
    if (dialogCancelled) {
        try {//w  w w.  j av a2s.  c  om
            if (nfcAdapter != null)
                nfcAdapter.disableForegroundDispatch(this);

        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

        dialogCancelled = false;
    }
}

From source file:com.inkubator.hrm.web.flow.JobJabatanFormController.java

public String doEditJabatanSpesification(RequestContext context) {
    String message = "success";
    try {//from   w  w w .j a va  2s.  c om
        JabatanSpesifikasiModel jabatanSpesifikasiModel = (JabatanSpesifikasiModel) context.getFlowScope()
                .get("jabatanSpesifikasiModel");
        JobJabatanModel jobJabatanModel = (JobJabatanModel) context.getFlowScope().get("jobJabatanModel");

        List<JabatanSpesifikasi> listJabatanSpesifikasi = jobJabatanModel.getListJabatanSpesifikasi();
        SpecificationAbility specificationAbility = specificationAbilityService
                .getEntiyByPK(jabatanSpesifikasiModel.getSpecId());

        listJabatanSpesifikasi.get(selectedIndexJabatanSpesifikasi)
                .setSpecificationAbility(specificationAbility);
        listJabatanSpesifikasi.get(selectedIndexJabatanSpesifikasi)
                .setValue(jabatanSpesifikasiModel.getValue());
        listJabatanSpesifikasi.get(selectedIndexJabatanSpesifikasi)
                .setOptionAbility(jabatanSpesifikasiModel.getOptionAbility());

        jobJabatanModel.setListJabatanSpesifikasi(listJabatanSpesifikasi);
        context.getFlowScope().put("jobJabatanModel", jobJabatanModel);

    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return message;
}

From source file:edu.cmu.tetrad.search.Ling.java

private void maxMappings(final DoubleMatrix2D matrix, final double min, final double max, final double[][] W,
        final List<Mapping> allMappings) {

    final int numNodes = W.length;

    for (int i = 0; i < numNodes; i++) {
        double maxScore = Double.NEGATIVE_INFINITY;
        double[] maxRow = new double[numNodes];

        for (Mapping mapping : mappingsForRow(i, allMappings)) {
            W[mapping.getI()][mapping.getJ()] = 0;
        }//from   w  w  w .  j a va  2 s.  c o  m

        try {
            optimizeNonGaussianity(i, matrix, W, allMappings);
            //                optimizeOrthogonality(i, min, max, W, allMappings, W.length);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            continue;
        }

        double v = ngFullData(i, matrix, W);

        if (Double.isNaN(v))
            continue;
        if (v >= 9999)
            continue;

        double[] row = new double[numNodes];
        for (int k = 0; k < numNodes; k++)
            row[k] = W[i][k];

        if (v > maxScore) {
            maxRow = row;
        }

        for (int k = 0; k < numNodes; k++)
            W[i][k] = maxRow[k];
    }
}

From source file:Default.YTDownloadThread.java

public boolean downloadOne(String url) throws IOException {

    boolean rc = false;
    boolean rc204 = false;
    boolean rc302 = false;

    this.recursionCount++;

    // stop recursion
    try {/*from  www  .j a v a2  s. c  o  m*/
        if (url.equals("")) {
            return (false);
        }
    } catch (NullPointerException npe) {
        return (false);
    }
    //      if (JFCMainClient.getQuitRequested()) {
    //         return(false); // try to get information about application shutdown
    //      }

    outputDebugMessage("start.");

    // TODO GUI option for proxy?
    // http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube
    // using local squid to save download time for tests

    try {

        this.request = new HttpGet(url);
        this.request.setConfig(this.config);
        this.httpClient = HttpClients.createDefault();

    } catch (Exception e) {
        outputDebugMessage(e.getMessage());
    }
    outputDebugMessage("executing request: ".concat(this.request.getRequestLine().toString()));
    outputDebugMessage("uri: ".concat(this.request.getURI().toString()));
    outputDebugMessage("using proxy: ".concat(this.getProxy()));

    try {
        this.response = this.httpClient.execute(this.request);
    } catch (ClientProtocolException cpe) {
        outputDebugMessage(cpe.getMessage());
    } catch (UnknownHostException uhe) {
        output(("error connecting to: ").concat(uhe.getMessage()));
        outputDebugMessage(uhe.getMessage());
    } catch (IOException ioe) {
        outputDebugMessage(ioe.getMessage());
    } catch (IllegalStateException ise) {
        outputDebugMessage(ise.getMessage());
    }

    try {
        outputDebugMessage("HTTP response status line:".concat(this.response.getStatusLine().toString()));

        // abort if HTTP response code is != 200, != 302 and !=204 - wrong URL?
        if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)"))
                & !(rc204 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)204(.*)"))
                & !(rc302 = this.response.getStatusLine().toString().toLowerCase()
                        .matches("^(http)(.*)302(.*)"))) {
            outputDebugMessage(this.response.getStatusLine().toString().concat(" ").concat(url));
            output(this.response.getStatusLine().toString().concat(" \"").concat(this.title).concat("\""));
            return (rc & rc204 & rc302);
        }
        if (rc204) {
            rc = downloadOne(this.nextVideoUrl.get(0).getUrl());
            return (rc);
        }
        if (rc302) {
            outputDebugMessage(
                    "location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString()));
        }

    } catch (NullPointerException npe) {
        // if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because
        // response.getStatusLine() == null
        this.videoUrl = null;
    }

    HttpEntity entity = null;
    try {
        entity = this.response.getEntity();
    } catch (NullPointerException npe) {
        //TODO catch must not be empty
    }

    // try to read HTTP response body
    if (entity != null) {
        try {
            if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase()
                    .matches("^text/html(.*)")) {
                this.textReader = new BufferedReader(new InputStreamReader(entity.getContent()));
            } else {
                this.binaryReader = new BufferedInputStream(entity.getContent());
            }
        } catch (IllegalStateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            // test if we got a webpage
            this.contentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase();
            if (this.contentType.matches("^text/html(.*)")) {
                rc = saveTextData();
                // test if we got the binary content
            } else if (this.contentType.matches("(audio|video)/(.*)|application/octet-stream")) {

                // add audio stream URL if necessary
                if (this.recursionCount == 1) {
                    outputDebugMessage(("last response code==true - download: ")
                            .concat(this.nextVideoUrl.get(0).getYoutubeId()));
                    if (this.nextVideoUrl.get(0).getAudioStreamUrl().equals("")) {
                        outputDebugMessage("download audio stream? no");
                    } else {
                        // FIXME audio stream has no filename if we add the direct URL to the GUI url list - we should add YTURL objects, not Strings!
                        outputDebugMessage("download audio stream? yes - "
                                .concat(this.nextVideoUrl.get(0).getAudioStreamUrl()));
                        this.youtubeUrl.setTitle(this.getTitle());
                        //JFCMainClient.addYoutubeUrlToList(this.nextVideoUrl.get(0).getAudioStreamUrl(),this.getTitle(),"AUDIO");
                    }
                }
                //                  if (JFCMainClient.getNoDownload())
                //                    reportHeaderInfo();
                //                  else
                saveBinaryData();
            } else { // content-type is not video/
                rc = false;
                this.videoUrl = null;
            }
        } catch (IOException ex) {
            try {
                throw ex;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (RuntimeException ex) {
            try {
                throw ex;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } //if (entity != null)

    this.httpClient.close();

    outputDebugMessage("done: ".concat(url));
    if (this.videoUrl == null) {
        this.videoUrl = ""; // to prevent NPE
    }
    if (this.videoUrl.matches(URL_REGEX)) {
        // enter recursion - download video resource
        outputDebugMessage("try to download video from URL: ".concat(this.videoUrl));
        rc = downloadOne(this.videoUrl);
    } else {
        // no more recursion - html source hase been read
        // rc==false if video could not downloaded because of some error (like wrong protocol or country restriction)
        if (!rc) {
            outputDebugMessage("cannot download video - URL does not seem to be valid or could not be found: "
                    .concat(this.url));
            output("there was a problem getting the video URL! perhaps not allowed in your country?!");
            output(("consider reporting the URL to author! - ").concat(this.url));
            this.videoUrl = null;
        }
    }

    this.videoUrl = null;

    return (rc);
}

From source file:it.drwolf.ridire.session.async.Mapper.java

public void run() {
    Random random = new Random();
    int waitSec = random.nextInt(100);
    this.setRunning(true);
    Lifecycle.beginCall();/*ww w .  j  a  v a2 s.com*/
    this.mapperUserTx = (UserTransaction) org.jboss.seam.Component
            .getInstance("org.jboss.seam.transaction.transaction", ScopeType.CONVERSATION);
    this.em = (EntityManager) Component.getInstance("eventEntityManager");
    this.tempDir = this.em.find(Parameter.class, Parameter.TEMP_DIR.getKey()).getValue();
    try {
        this.mapperUserTx.setTransactionTimeout(60 * 20);
        Thread.sleep(waitSec);
        if (this.mapperUserTx != null && !this.mapperUserTx.isActive()) {
            if (this.mapperUserTx.getStatus() != javax.transaction.Status.STATUS_ACTIVE) {
                this.mapperUserTx.begin();
            }
        }
        this.em.joinTransaction();
        String dir = this.em.find(Parameter.class, Parameter.JOBS_DIR.getKey()).getValue();
        File filename = null;
        boolean childJobMapping = false;
        Job persistedJob = this.em.find(Job.class, this.jobId);
        if (persistedJob.getChildJobName() != null && !persistedJob.isMappedResources()) {
            childJobMapping = true;
            filename = new File(dir + JobMapperMonitor.FILE_SEPARATOR + persistedJob.getChildJobName()
                    + JobMapperMonitor.FILE_SEPARATOR + "arcs" + JobMapperMonitor.FILE_SEPARATOR);
        } else {
            filename = new File(dir + JobMapperMonitor.FILE_SEPARATOR + persistedJob.getName()
                    + JobMapperMonitor.FILE_SEPARATOR + "arcs" + JobMapperMonitor.FILE_SEPARATOR);
        }
        this.em.flush();
        this.mapperUserTx.commit();
        File[] arcFiles = filename.listFiles();
        if (arcFiles == null) {
            // try also 'completed-' for back compatibility
            filename = new File(dir + JobMapperMonitor.FILE_SEPARATOR + "completed-" + persistedJob.getName()
                    + JobMapperMonitor.FILE_SEPARATOR + "arcs" + JobMapperMonitor.FILE_SEPARATOR);
            arcFiles = filename.listFiles();
        } else {
            for (File f : arcFiles) {
                if (f.getName().equals("resources")) {
                    continue;
                }
                boolean uncompressed = false;
                if (f.getName().endsWith(".gz")) {
                    f = this.uncompressGzippedArcFile(f);
                    uncompressed = true;
                }
                ArchiveReader archiveReader;
                try {
                    archiveReader = ArchiveReaderFactory.get(f);
                } catch (IOException e) {
                    System.err.println("Errore nella lettura del file: " + f.getAbsolutePath());
                    e.printStackTrace();
                    continue;
                }
                Iterator<ArchiveRecord> itOnArchiveRecord = archiveReader.iterator();
                Set<CrawledResource> childResources = new HashSet<CrawledResource>();
                while (itOnArchiveRecord.hasNext()) {
                    ARCRecord archiveRecord = (ARCRecord) itOnArchiveRecord.next();
                    ARCRecordMetaData metadata = archiveRecord.getMetaData();
                    Date now = new Date();
                    // store only succeeded requests
                    if (metadata.getStatusCode() != null && metadata.getStatusCode().equals("200")) {
                        String url = metadata.getUrl();
                        long length = metadata.getLength();
                        System.out.println(
                                "Mapping URL: " + url + "\n" + "Size: " + length + "\t" + this.mapperUserTx);
                        try {
                            archiveRecord.skipHttpHeader();
                            archiveRecord.close();
                            String digest = archiveRecord.getDigestStr();
                            if (!childJobMapping) {
                                // do not store equal resources
                                if (this.mapperUserTx != null && !this.mapperUserTx.isActive()) {
                                    if (this.mapperUserTx
                                            .getStatus() != javax.transaction.Status.STATUS_ACTIVE) {
                                        this.mapperUserTx.begin();
                                    }
                                }
                                this.em.joinTransaction();
                                if (!this.isResourceAlreadyMapped(digest, url, this.em)) {
                                    CrawledResource cr = new CrawledResource();
                                    cr.setDigest(digest);
                                    cr.setOffset(metadata.getOffset());
                                    cr.setArcFile(f.getCanonicalPath());
                                    cr.setArchiveDate(now);
                                    cr.setLastModified(now);
                                    cr.setLength(length);
                                    cr.setContentType(metadata.getMimetype());
                                    cr.setIp(metadata.getIp());
                                    cr.setUrl(url);
                                    cr.setJob(persistedJob);
                                    persistedJob = this.em.find(Job.class, this.jobId);
                                    persistedJob.getCrawledResources().add(cr);
                                    this.em.persist(cr);
                                    this.em.persist(persistedJob);
                                    this.createArchivedResource(f, cr, this.em);
                                    this.em.persist(cr);
                                    if (this.existsResourceWithSameExtractedText(cr)) {
                                        persistedJob.getCrawledResources().remove(cr);
                                        this.em.persist(persistedJob);
                                        this.em.remove(cr);
                                    }
                                }
                                this.em.flush();
                                this.mapperUserTx.commit();
                            } else {
                                CrawledResource cr = new CrawledResource();
                                cr.setUrl(url);
                                if (this.mapperUserTx != null && !this.mapperUserTx.isActive()) {
                                    if (this.mapperUserTx
                                            .getStatus() != javax.transaction.Status.STATUS_ACTIVE) {
                                        this.mapperUserTx.begin();
                                    }
                                }
                                this.em.joinTransaction();
                                // do not store equal resources
                                if (!this.isResourceAlreadyMapped(digest, url, this.em)) {
                                    // check urls
                                    CrawledResource sameUrlResource = this.sameURLExists(url, persistedJob,
                                            this.em);
                                    boolean modifiedResource = false;
                                    String oldDigest = null;
                                    if (sameUrlResource != null) {
                                        // modified resource
                                        modifiedResource = true;
                                        oldDigest = sameUrlResource.getDigest();
                                        cr = sameUrlResource;
                                    } else {
                                        // new resource
                                        cr.setArchiveDate(now);
                                    }
                                    cr.setDigest(digest);
                                    cr.setNoMoreAvailable(false);
                                    cr.setOffset(metadata.getOffset());
                                    cr.setLastModified(now);
                                    cr.setArcFile(f.getCanonicalPath());
                                    cr.setLength(length);
                                    cr.setContentType(metadata.getMimetype());
                                    cr.setIp(metadata.getIp());
                                    cr.setJob(persistedJob);
                                    persistedJob = this.em.find(Job.class, this.jobId);
                                    persistedJob.getCrawledResources().add(cr);
                                    this.em.persist(cr);
                                    this.em.persist(persistedJob);
                                    if (modifiedResource) {
                                        this.updateArchivedResource(f, cr, oldDigest, this.em);
                                        this.em.persist(cr);
                                    } else {
                                        this.createArchivedResource(f, cr, this.em);
                                        if (this.existsResourceWithSameExtractedText(cr)) {
                                            persistedJob.getCrawledResources().remove(cr);
                                            this.em.persist(persistedJob);
                                            this.em.remove(cr);
                                        }
                                    }
                                } else {
                                    // this is an url that was
                                    // marked as
                                    // noMoreAvailable and now it is
                                    // available
                                    // again
                                }
                                CrawledResource sameUrlResource = this.sameURLExists(url, persistedJob,
                                        this.em);
                                if (sameUrlResource != null && sameUrlResource.isNoMoreAvailable()) {
                                    String oldDigest = sameUrlResource.getDigest();
                                    cr = sameUrlResource;
                                    cr.setDigest(digest);
                                    cr.setNoMoreAvailable(false);
                                    cr.setOffset(metadata.getOffset());
                                    cr.setLastModified(now);
                                    cr.setArcFile(f.getCanonicalPath());
                                    cr.setLength(length);
                                    cr.setContentType(metadata.getMimetype());
                                    cr.setIp(metadata.getIp());
                                    cr.setJob(persistedJob);
                                    persistedJob = this.em.find(Job.class, this.jobId);
                                    persistedJob.getCrawledResources().add(cr);
                                    this.em.persist(cr);
                                    this.em.persist(persistedJob);
                                    this.createArchivedResourceAndDeleteFromAttic(f, oldDigest, cr, this.em);
                                    this.em.persist(cr);
                                }
                                childResources.add(cr);
                                this.em.flush();
                                this.mapperUserTx.commit();
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } finally {
                            try {
                                if (this.mapperUserTx != null && this.mapperUserTx.isActive()) {
                                    this.mapperUserTx.rollback();
                                }
                            } catch (IllegalStateException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            } catch (SecurityException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            } catch (SystemException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                            }
                            this.setRunning(false);
                        }
                    }
                }
                archiveReader.close();
                if (uncompressed) {
                    FileUtils.deleteQuietly(f);
                }
                if (childJobMapping) {
                    if (this.mapperUserTx != null && !this.mapperUserTx.isActive()) {
                        if (this.mapperUserTx.getStatus() != javax.transaction.Status.STATUS_ACTIVE) {
                            this.mapperUserTx.begin();
                        }
                    }

                    this.em.joinTransaction();
                    this.lookForNoMoreAvailableResources(persistedJob, childResources, f, this.em);
                    this.em.flush();
                    this.mapperUserTx.commit();
                }
            }
        }
        if (this.mapperUserTx != null && !this.mapperUserTx.isActive()) {
            if (this.mapperUserTx.getStatus() != javax.transaction.Status.STATUS_ACTIVE) {
                this.mapperUserTx.begin();
            }
        }
        this.em.joinTransaction();
        this.em.refresh(persistedJob);
        persistedJob.setMappedResources(true);
        this.em.persist(persistedJob);
        this.em.flush();
        this.mapperUserTx.commit();
        this.flagBearer.setOwnerName(persistedJob.getCrawlerUser().getName());
        this.flagBearer.setOwnerSurname(persistedJob.getCrawlerUser().getSurname());
        this.flagBearer.setJobName(persistedJob.getName());
        this.flagBearer.setEmailAddress(persistedJob.getCrawlerUser().getEmail());
        if (this.flagBearer.getEmailAddress() != null
                && this.flagBearer.getEmailAddress().trim().length() > 0) {
            this.renderer.render("/mail/mappedJob.xhtml");
        }

        this.setRunning(false);
        System.out.println("Job " + this.getJobName() + " mapping terminated.");
    } catch (Exception e) {
        if (this.mapperUserTx != null) {
            try {
                System.err.println("STATUS: " + this.mapperUserTx.getStatus());
            } catch (SystemException e1) {
                System.err.println("SSTACKTRACE mapperUserTx");
                e1.printStackTrace();
            }
        }
        e.printStackTrace();
    } finally {
        try {
            if (this.mapperUserTx != null && this.mapperUserTx.isActive()) {
                this.mapperUserTx.rollback();
            }
        } catch (Exception e) {
            System.err.println("FINALLY");
            e.printStackTrace();
        }
        Lifecycle.endCall();
        this.setRunning(false);
    }
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public String uploadDHIS2APIBackup(MultipartFile dhis2APIBackup) {
    String msg = "";
    String outputFolder = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER;
    File temp = new File(outputFolder);
    File dhis2APIBackupRootDir = new File(
            OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_DHIS2BACKUP_FOLDER);

    if (!temp.exists()) {
        temp.mkdirs();/*from   w w  w  .  j a  va2 s  . c  o m*/
    }

    File dest = new File(outputFolder + File.separator + dhis2APIBackup.getOriginalFilename());

    if (!dhis2APIBackup.isEmpty() && dhis2APIBackup.getOriginalFilename().endsWith(".zip")) {
        try {
            dhis2APIBackup.transferTo(dest);

            if (dest.exists() && dest.isFile()) {
                File unzippedAt = new File(outputFolder + File.separator + "api");
                File api = new File(dhis2APIBackupRootDir.getPath() + File.separator + "api");

                unZipDHIS2APIBackupToTemp(dest.getCanonicalPath());
                if ((new File(outputFolder)).list().length > 0 && unzippedAt.exists()) {
                    if (!dhis2APIBackupRootDir.exists()) {
                        dhis2APIBackupRootDir.mkdirs();
                    }

                    if (FileUtils.sizeOfDirectory(dhis2APIBackupRootDir) > 0 && unzippedAt.exists()
                            && unzippedAt.isDirectory()) {
                        if (checkIfDirContainsFile(dhis2APIBackupRootDir, "api")) {

                            FileUtils.deleteDirectory(api);
                            api.mkdir();
                            msg = Context.getMessageSourceService()
                                    .getMessage("dhisconnector.dhis2backup.replaceSuccess");
                        } else {
                            msg = Context.getMessageSourceService()
                                    .getMessage("dhisconnector.dhis2backup.import.success");
                        }
                        FileUtils.copyDirectory(unzippedAt, api);
                        FileUtils.deleteDirectory(temp);
                    }
                }
            }
        } catch (IllegalStateException e) {
            msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
            e.printStackTrace();
        } catch (IOException e) {
            msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
            e.printStackTrace();
        }
    } else {
        msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
    }

    return msg;
}