Example usage for java.lang Exception getStackTrace

List of usage examples for java.lang Exception getStackTrace

Introduction

In this page you can find the example usage for java.lang Exception getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

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

Usage

From source file:com.actian.services.dataflow.operators.RunJSONPath.java

@Override
protected void execute(ExecutionContext context) {

    Configuration configuration = Configuration.builder().mappingProvider(new JsonSmartMappingProvider())
            .jsonProvider(/* www.  j  a  va2  s.c om*/
                    new JsonSmartJsonProvider(JSONParser.MODE_PERMISSIVE ^ JSONParser.USE_HI_PRECISION_FLOAT))
            .build();

    if (nullMissingLeaf) {
        configuration = configuration.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
    }

    RecordInput recordInput = getInput().getInput(context);
    RecordOutput recordOutput = getOutput().getOutput(context);
    RecordOutput recordReject = getReject().getOutput(context);

    ScalarValued[] allInputs = recordInput.getFields();
    ScalarSettable[] outputs = TokenUtils.selectFields(recordOutput, recordInput.getType().getNames());
    ScalarSettable[] rejects = TokenUtils.selectFields(recordReject, recordInput.getType().getNames());
    StringSettable jsonPathErrorText = (StringSettable) recordReject.getField(recordReject.size() - 1);

    // Quit early if the operator configuration isn't valid
    if (checkConfig() == false) {
        recordOutput.pushEndOfData();
        recordReject.pushEndOfData();
        return;
    }

    int flatcnt = 0;

    int resultOffset = 0;

    if (!excludeSourceFields)
        resultOffset = allInputs.length;

    // Count the number of output fields being flat mapped
    for (Boolean f : flatmap) {
        if (f)
            flatcnt++;
    }

    while (recordInput.stepNext()) {
        List<Object> results = new ArrayList<Object>();

        int largestListSize = 0;
        boolean rejected = false;

        DocumentContext parsedJSON = null;
        StringValued inputField = null;

        // Evaluate each of the JSONPath expressions
        for (int i = 0; i < targetFields.length; i++) {

            try {

                // Use the previously parsed object if a new is not specified.
                if (i < sourceFields.length && sourceFields[i] != null && sourceFields[i].length() > 0) {

                    // Only parse the source if it is different from the previously parsed JSON object.
                    if (inputField != recordInput.getField(sourceFields[i])) {
                        inputField = (StringValued) recordInput.getField(sourceFields[i]);
                        parsedJSON = JsonPath.using(configuration).parse(inputField.asString());
                    }
                }
            } catch (Exception e) {
                // Copy the original input record fields to the corresponding reject record fields
                TokenUtils.transfer(allInputs, rejects);
                jsonPathErrorText.set(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
                recordReject.push();

                rejected = true;
                break;
            }

            String jsonPathExpr = expressions[i];

            Object res = null;

            try {
                res = parsedJSON.read(jsonPathExpr);
            } catch (Exception e) {
                // Copy the original input record fields to the corresponding reject record fields
                TokenUtils.transfer(allInputs, rejects);
                jsonPathErrorText.set(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
                recordReject.push();

                rejected = true;
                break;
            } finally {

                results.add(res);

                if (res != null && res instanceof List) {
                    List list = (List) res;
                    if (list.size() > largestListSize) {
                        largestListSize = list.size();
                    }
                }
            }
        }

        // Continue with the next record if we rejected the current one
        if (rejected)
            continue;

        if (flatcnt == 0) {
            // No flattening to do.

            // Copy the original input record fields to the corresponding output record fields
            if (!excludeSourceFields) {
                TokenUtils.transfer(allInputs, outputs);
            }

            for (int i = 0; i < targetFields.length; i++) {

                // The output record was generated by merging the input record with a list of new fields
                // and new fields might have slightly different names if there were any name conflicts.
                // We need to compute the offset of the current output field rather than look it up by name.
                StringSettable resultField = (StringSettable) recordOutput.getField(i + resultOffset);

                resultField.set(formatResult(configuration, results.get(i)));
            }
            recordOutput.push();
        } else {
            // Generate one output row for each element of the largest result list
            for (int f = 0; f < largestListSize; f++) {

                // Copy the original input record fields to the corresponding output record fields
                if (!excludeSourceFields) {
                    TokenUtils.transfer(allInputs, outputs);
                }

                for (int i = 0; i < targetFields.length; i++) {

                    // The output record was generated by merging the input record with a list of new fields
                    // and new fields might have slightly different names if there were any name conflicts.
                    // We need to compute the offset of the current output field rather than look it up by name.
                    StringSettable resultField = (StringSettable) recordOutput.getField(i + resultOffset);

                    Object o = results.get(i);

                    // See if we are flat mapping this result
                    if (flatmap[i] && o instanceof List) {
                        List l = (List) o;
                        if (f < l.size()) {
                            resultField.set(formatResult(configuration, l.get(f)));
                        } else {
                            resultField.set((String) null);
                        }
                    } else {
                        resultField.set(formatResult(configuration, results.get(i)));
                    }

                }
                recordOutput.push();
            }
        }
    }

    recordOutput.pushEndOfData();
    recordReject.pushEndOfData();
}

From source file:org.ambientdynamix.contextplugins.withingsdataplugin.WithingsDataPluginRuntime.java

/**
  * start the process by loging in, finding the right user and 
  * retreiving the values, then submitting the new values.
  * /*ww  w.  jav  a  2  s . c  o m*/
  * the method is  loop that sleeps a while in between.
  * 
  * a new context is only pushed if a new value is found.
  *
  *@return a array with the values (default 0 if no new value is found)
  */
private float[] getValues() throws Exception {
    Log.i("Withings", "getvalues");
    Date lastupdate = user.getLastUpdate();
    Log.i("Withings", "lastupdate" + lastupdate);
    Date newlastupdate = lastupdate;
    String newlastupdatestring = "";
    String request = "http://wbsapi.withings.net/measure?action=getmeas&userid=" + id + "&publickey="
            + publicKey +
            //"&limit=10"+
            "&devtype=1"; // Only values from the scale
    String response = performRequest(request);
    System.out.println(response);
    // Decode JSon object
    JSONObject json = new JSONObject(response);
    JSONArray JSONvalues = json.getJSONObject("body").getJSONArray("measuregrps");
    JSONObject JSONvalue;
    JSONArray JSONtypes;
    JSONObject JSONtype;
    long timestamp;
    float weight = 0;
    float height = 0;
    float fatFreeMass = 0;
    float fatRatio = 0;
    float fatMassWeight = 0;
    float diastolicBloodPressure = 0;
    float systolicBloodPressure = 0;
    float pulse = 0;
    int size = JSONvalues.length();
    for (int i = 0; i < size; i++) {
        JSONvalue = JSONvalues.getJSONObject(i);
        if (JSONvalue.getInt("category") != 1) {
            continue;
        }
        timestamp = JSONvalue.getLong("date");
        String stamp = "" + timestamp;
        Date newdate = new Date(Long.parseLong(stamp) * 1000);
        System.out.println(timestamp);
        if (newdate.after(newlastupdate)) {
            Log.i("Withings", "newdate " + newdate);
            newlastupdate = newdate;
            newlastupdatestring = stamp;
        }
        if (newdate.after(lastupdate)) {
            //Log.i("Withings", "newdate after lastupdate");
            JSONtypes = JSONvalue.getJSONArray("measures");
            for (int j = 0; j < JSONtypes.length(); j++) {
                JSONtype = JSONtypes.getJSONObject(j);
                //1  Weight (kg)
                //4  Height (meter)
                //5  Fat Free Mass (kg)
                //6  Fat Ratio (%)
                //8  Fat Mass Weight (kg)
                //9  Diastolic Blood Pressure (mmHg)
                //10 Systolic Blood Pressure (mmHg)
                //11 Heart Pulse (bpm)
                if (JSONtype.getInt("type") == 1) {
                    if (weight == 0) {
                        Log.i("Withings", "" + weight);
                        weight = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                        Log.i("Withings", "" + weight);
                    }
                }
                if (JSONtype.getInt("type") == 2) {
                    //not used yet
                }
                if (JSONtype.getInt("type") == 3) {
                    //not used yet
                }
                if (JSONtype.getInt("type") == 4) {
                    if (height == 0) {
                        height = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 5) {
                    if (fatFreeMass == 0) {
                        fatFreeMass = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 6) {
                    if (fatRatio == 0) {
                        fatRatio = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 7) {
                    //not used yet
                }
                if (JSONtype.getInt("type") == 8) {
                    if (fatMassWeight == 0) {
                        fatMassWeight = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 9) {
                    if (diastolicBloodPressure == 0) {
                        diastolicBloodPressure = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 10) {
                    if (systolicBloodPressure == 0) {
                        systolicBloodPressure = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 11) {
                    if (pulse == 0) {
                        pulse = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
            }
        }
    }
    request = "http://wbsapi.withings.net/measure?action=getmeas&userid=" + id + "&publickey=" + publicKey
            + "&limit=10" + "&devtype=0"; // Only values from the scale
    response = performRequest(request);
    System.out.println(response);
    json = new JSONObject(response);
    JSONvalues = json.getJSONObject("body").getJSONArray("measuregrps");
    size = JSONvalues.length();
    for (int i = 0; i < size; i++) {
        JSONvalue = JSONvalues.getJSONObject(i);
        if (JSONvalue.getInt("category") != 1) {
            continue;
        }
        timestamp = JSONvalue.getLong("date");
        String stamp = "" + timestamp;
        Date newdate = new Date();
        System.out.println(timestamp);
        try {
            newdate = new Date(Long.parseLong(stamp) * 1000);
            if (newdate.after(newlastupdate)) {
                Log.i("Withings", "newdate2 " + newdate);
                newlastupdate = newdate;
                newlastupdatestring = stamp;
            }
        } catch (Exception ex) {
            ex.getStackTrace();
        }
        if (newdate.after(lastupdate)) {
            JSONtypes = JSONvalue.getJSONArray("measures");
            for (int j = 0; j < JSONtypes.length(); j++) {
                JSONtype = JSONtypes.getJSONObject(j);
                if (JSONtype.getInt("type") == 1) {
                    if (weight == 0) {
                        weight = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 2) {
                    //not used yet
                }
                if (JSONtype.getInt("type") == 3) {
                    //not used yet
                }
                if (JSONtype.getInt("type") == 4) {
                    if (height == 0) {
                        Log.i("Withings h", "" + height);
                        height = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                        Log.i("Withings h", "" + height);
                    }
                }
                if (JSONtype.getInt("type") == 5) {
                    if (fatFreeMass == 0) {
                        fatFreeMass = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 6) {
                    if (fatRatio == 0) {
                        fatRatio = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 7) {
                    //not used yet
                }
                if (JSONtype.getInt("type") == 8) {
                    if (fatMassWeight == 0) {
                        fatMassWeight = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 9) {
                    if (diastolicBloodPressure == 0) {
                        diastolicBloodPressure = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 10) {
                    if (systolicBloodPressure == 0) {
                        systolicBloodPressure = (float) (JSONtype.getInt("value")
                                * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
                if (JSONtype.getInt("type") == 11) {
                    if (pulse == 0) {
                        pulse = (float) (JSONtype.getInt("value") * Math.pow(10, JSONtype.getInt("unit")));
                    }
                }
            }
        }
    }
    float[] values = new float[8];
    values[0] = weight;
    values[1] = height;
    values[2] = fatFreeMass;
    values[3] = fatRatio;
    values[4] = fatMassWeight;
    values[5] = diastolicBloodPressure;
    values[6] = systolicBloodPressure;
    values[7] = pulse;
    Log.i("Withings", "Als neuer Timestamp wird bergeben:" + newlastupdatestring);
    user.update(newlastupdatestring, values);
    return values;
}

From source file:com.dlshouwen.jspc.zwpc.controller.SelfEvaluateController.java

@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html;charset=utf-8");
    String itemId = request.getParameter("itemId");
    String path = dao.getEvalItemById(itemId).getAttach();
    String fileName = path.substring(path.lastIndexOf("/") + 1);
    File f = new File(path);
    if (f.exists()) {
        FileInputStream filein = new FileInputStream(f);
        byte[] b = new byte[1024];
        try {/*from w w w.j a v  a  2s.co m*/
            int len = filein.read(b);
            if (fileName != null) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
                if (fileName != "") {
                    response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                }
            }
            while (len > 0) {
                response.getOutputStream().write(b, 0, len);
                len = filein.read(b);
            }
        } catch (Exception e) {
            System.out.println(e.getStackTrace() + e.getMessage());
        } finally {
            response.getOutputStream().flush();
            response.getOutputStream().close();
            filein.close();
        }
    } else {
        response.getWriter().print("????");
    }
}

From source file:ru.apertum.qsystem.common.model.QCustomer.java

private void saveToSelfDB() {
    // ? ?  //w w  w  .j a v a 2 s .  co m
    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("SomeTxName");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = Spring.getInstance().getTxManager().getTransaction(def);
    try {
        if (input_data == null) { //     ? ?       ,   ?   
            input_data = "";
        }
        Spring.getInstance().getHt().saveOrUpdate(this);
    } catch (Exception ex) {
        Spring.getInstance().getTxManager().rollback(status);
        throw new ServerException("  ? \n" + ex.toString() + "\n"
                + Arrays.toString(ex.getStackTrace()));
    }
    Spring.getInstance().getTxManager().commit(status);
    QLog.l().logger().debug(".");
}

From source file:org.apache.lucene.gdata.storage.lucenestorage.StorageImplementation.java

/**
 * @see org.apache.lucene.gdata.storage.Storage#getEntry(org.apache.lucene.gdata.data.ServerBaseEntry)
 *//* ww  w . j av  a  2s .  com*/
public BaseEntry getEntry(final ServerBaseEntry entry) throws StorageException {

    if (entry == null)
        throw new StorageException("No entry  specified -- is null");
    if (LOG.isInfoEnabled())
        LOG.info("get entry " + entry.getId() + " -- feed: " + entry.getFeedId());
    ReferenceCounter<StorageQuery> query = null;
    try {
        query = this.controller.getStorageQuery();
        BaseEntry retVal = query.get().singleEntryQuery(entry.getId(), entry.getFeedId(),
                entry.getServiceConfig());
        if (retVal == null)
            throw new ResourceNotFoundException("can not get entry for entry ID " + entry.getId());
        return retVal;
    } catch (Exception e) {
        LOG.error("Can't get entry for feedID: " + entry.getFeedId() + "; entryId: " + entry.getId() + " -- "
                + e.getMessage(), e);
        StorageException ex = new StorageException("Can't create Entry -- " + e.getMessage(), e);
        ex.setStackTrace(e.getStackTrace());
        throw ex;

    } finally {
        if (query != null)
            query.decrementRef();
    }

}

From source file:net.sf.l2j.gameserver.model.entity.L2JOneoRusEvents.CTF.java

public static void spawnFlag(String teamName) {
    int index = _teams.indexOf(teamName);
    L2NpcTemplate tmpl = NpcTable.getInstance().getTemplate(_flagIds.get(index));
    try {//w w  w.  j a  v  a  2s.  c  om
        _flagSpawns.set(index, new L2Spawn(tmpl));
        _flagSpawns.get(index).setLocx(_flagsX.get(index));
        _flagSpawns.get(index).setLocy(_flagsY.get(index));
        _flagSpawns.get(index).setLocz(_flagsZ.get(index));
        _flagSpawns.get(index).setAmount(1);
        _flagSpawns.get(index).setHeading(0);
        _flagSpawns.get(index).setRespawnDelay(1);
        SpawnTable.getInstance().addNewSpawn(_flagSpawns.get(index), false);
        _flagSpawns.get(index).init();
        _flagSpawns.get(index).getLastSpawn().getStatus().setCurrentHp(999999999);
        _flagSpawns.get(index).getLastSpawn().setTitle(teamName + "'s Flag");
        _flagSpawns.get(index).getLastSpawn()._CTF_FlagTeamName = teamName;
        _flagSpawns.get(index).getLastSpawn()._isCTF_Flag = true;
        _flagSpawns.get(index).getLastSpawn().decayMe();
        _flagSpawns.get(index).getLastSpawn().spawnMe(_flagSpawns.get(index).getLastSpawn().getX(),
                _flagSpawns.get(index).getLastSpawn().getY(), _flagSpawns.get(index).getLastSpawn().getZ());
    } catch (Exception e) {
        System.out.println("CTF Engine[spawnFlag(" + teamName + ")]: exception: " + e.getStackTrace());
    }
}

From source file:org.apache.flink.tez.runtime.TezTask.java

protected void run() throws Exception {
    // ---------------------------- Now, the actual processing starts ------------------------
    // check for asynchronous canceling

    boolean stubOpen = false;

    try {//from w ww. j a v a2s  .  c  om
        // run the data preparation
        try {
            this.driver.prepare();
        } catch (Throwable t) {
            // if the preparation caused an error, clean up
            // errors during clean-up are swallowed, because we have already a root exception
            throw new Exception("The data preparation for task '" + this.taskName + "' , caused an error: "
                    + t.getMessage(), t);
        }

        // open stub implementation
        if (this.stub != null) {
            try {
                Configuration stubConfig = this.config.getStubParameters();
                FunctionUtils.openFunction(this.stub, stubConfig);
                stubOpen = true;
            } catch (Throwable t) {
                throw new Exception("The user defined 'open()' method caused an exception: " + t.getMessage(),
                        t);
            }
        }

        // run the user code
        this.driver.run();

        // close. We close here such that a regular close throwing an exception marks a task as failed.
        if (this.stub != null) {
            FunctionUtils.closeFunction(this.stub);
            stubOpen = false;
        }

        this.output.close();

    } catch (Exception ex) {
        // close the input, but do not report any exceptions, since we already have another root cause
        ex.printStackTrace();
        throw new RuntimeException("Exception in TaskContext: " + ex.getMessage() + " " + ex.getStackTrace());
    } finally {
        this.driver.cleanup();
    }
}

From source file:nl.gridline.zieook.exceptions.ZieOokExceptionMapper.java

private ResponseBuilder getResponseBuilder(int status, Exception exception) {
    ResponseBuilder responseBuilder = Response.status(status);
    responseBuilder.type(MediaType.TEXT_HTML);
    StringBuilder b = new StringBuilder();
    b.append("<html><head><title>").append(exception.getClass().getCanonicalName())
            .append("</title></head><body>");
    b.append("<b>CODE</b>\t").append(status).append("<br />\n");
    b.append("<b>CLASS</b>\t").append(exception.getClass().getCanonicalName()).append("<br />\n");
    b.append("<b>MESSAGE</b>:\t<span style='color:red'>").append(exception.getMessage())
            .append("</span><br />\n");
    b.append("<b>STACKTRACE</b><br />\t\n");
    if (LOG.isDebugEnabled()) {
        StackTraceElement[] ste = exception.getStackTrace();
        for (StackTraceElement s : ste) {
            b.append(s.toString()).append("<br />\n");
        }/*from w  ww.ja  v  a2s  .c o m*/
        b.append("end<br />");
    }
    b.append("</body></html>");
    return responseBuilder.entity(b.toString());
}

From source file:org.apache.zeppelin.interpreter.SnappyDataSqlZeppelinInterpreter.java

/**
 * The content of this method are borrowed from JDBC interpreter of apache zeppelin
 *
 * @param snc/* w ww .jav  a  2  s.com*/
 * @param sql
 * @param interpreterContext
 * @return
 */
private InterpreterResult executeSql(SnappyContext snc, String sql, InterpreterContext interpreterContext,
        boolean isApproxQuery) {

    String paragraphId = interpreterContext.getParagraphId();

    try {

        StringBuilder msg = new StringBuilder();

        long startTime = System.currentTimeMillis();
        Dataset ds = snc.sql(sql);
        String data = null;
        if (null != ds) {
            data = ZeppelinContext.showDF(snc.sparkContext(), interpreterContext, ds, maxResult);
        }
        long endTime = System.currentTimeMillis();

        data = data.trim();
        if (null != data && data != EMPTY_STRING && data.split("\n").length > 1) {
            msg.append(data);
            msg.append(NEWLINE);

            if (isApproxQuery) {
                paragraphStateMap.get(paragraphId).setTimeRequiredForApproxQuery(endTime - startTime);
                msg.append("\n<font color=red>Time required to execute query on sample table : "
                        + (endTime - startTime) + " millis.Executing base query ...</font>");

            } else if (paragraphStateMap.containsKey(paragraphId)) {

                paragraphStateMap.get(paragraphId).setTimeRequiredForBaseQuery(endTime - startTime);
                msg.append("\n<font color=red>Time required to execute query on sample table : "
                        + paragraphStateMap.get(paragraphId).getTimeRequiredForApproxQuery()
                        + " millis.</font><br>");
                msg.append("\n<font color=red>Time required to execute query on base table : "
                        + paragraphStateMap.get(paragraphId).getTimeRequiredForBaseQuery() + " millis.</font>");
                paragraphStateMap.remove(paragraphId);
            } else {
                msg.append("\n<br><font color=red>Time required to execute query : " + (endTime - startTime)
                        + " millis.</font>");

            }
        } else {
            // Response contains either an update count or there are no results.
        }

        return new InterpreterResult(InterpreterResult.Code.SUCCESS, msg.toString());

    } catch (Exception e) {
        if (!paragraphStateMap.containsKey(paragraphId) || !paragraphStateMap.get(paragraphId).isCancelCalled) {
            logger.error("Cannot run " + sql, e);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(e.getMessage()).append("\n");
            stringBuilder.append(e.getClass().toString()).append("\n");
            stringBuilder.append(StringUtils.join(e.getStackTrace(), "\n"));
            return new InterpreterResult(InterpreterResult.Code.ERROR, stringBuilder.toString());
        } else {
            paragraphStateMap.remove(paragraphId);
            // Don't show error in case of cancel
            return new InterpreterResult(InterpreterResult.Code.KEEP_PREVIOUS_RESULT, EMPTY_STRING);
        }
    }
}

From source file:de.hybris.platform.marketplaceintegrationbackoffice.renderer.MarketplaceIntegrationOrderInitialRenderer.java

private void initialOrderDownload(final MarketplaceStoreModel model) {
    if (null == model.getOrderStartTime()) {
        NotificationUtils.notifyUserVia(Localization
                .getLocalizedString("type.Marketplacestore." + MarketplaceStoreModel.ORDERSTARTTIME + ".name")
                + " " + Labels.getLabel("backoffice.field.notfilled"), NotificationEvent.Type.WARNING, "");
        LOG.warn("get order start time is not filled!");
        return;/*from  www  .j  a va2 s.c o m*/
    } else if (null == model.getOrderEndTime()) {
        NotificationUtils.notifyUserVia(Localization
                .getLocalizedString("type.Marketplacestore." + MarketplaceStoreModel.ORDERENDTIME + ".name")
                + " " + Labels.getLabel("backoffice.field.notfilled"), NotificationEvent.Type.WARNING, "");
        LOG.warn("get order end time is not filled!");
        return;
    } else if (model.getOrderStartTime().after(model.getOrderEndTime())) {
        NotificationUtils.notifyUserVia(Labels.getLabel("backoffice.field.timerange.error"),
                NotificationEvent.Type.WARNING, "");
        LOG.warn("start time is greate than end time!");
        return;
    } else if (model.getMarketplace().getTmallOrderStatus().isEmpty()
            || null == model.getMarketplace().getTmallOrderStatus()) {
        NotificationUtils.notifyUserVia(
                Localization
                        .getLocalizedString("type.Marketplace." + MarketplaceModel.TMALLORDERSTATUS + ".name")
                        + " " + Labels.getLabel("backoffice.field.notfilled"),
                NotificationEvent.Type.WARNING, "");
        LOG.warn("order status field is not filled!");
        return;
    }
    if (!StringUtils.isBlank(model.getIntegrationId()) && !model.getAuthorized().booleanValue()) {
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.authorization.fail"),
                NotificationEvent.Type.WARNING, "");
        LOG.warn("authorization is expired!");
        return;
    }
    // in order to avoid this value out of date, we only get it from
    // database
    final Boolean isAuth = ((MarketplaceStoreModel) modelService.get(model.getPk())).getAuthorized();
    final String integrationId = ((MarketplaceStoreModel) modelService.get(model.getPk())).getIntegrationId();
    model.setIntegrationId(integrationId);
    model.setAuthorized(isAuth);
    if (null == isAuth || !isAuth.booleanValue()) {
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.initorder.unauthed"),
                NotificationEvent.Type.WARNING, "");
        LOG.warn("marketplace store do not authorized, initial download failed!");
        return;
    }

    String urlStr = "";
    final String logUUID = logUtil.getUUID();
    final MarketplaceSellerModel seller = model.getMarketplaceSeller();
    final MarketplaceModel marketPlace = seller.getMarketplace();
    try {

        // Configure and open a connection to the site you will send the
        urlStr = marketPlace.getAdapterUrl() + Config.getParameter(MARKETPLACE_ORDER_SYCHRONIZE_PATH)
                + Config.getParameter(MARKETPLACE_ORDER_INITIAL_PATH) + integrationId
                + Config.getParameter(MARKETPLACE_ORDER_INITIAL_LOGUUID) + logUUID;
        final JSONObject jsonObj = new JSONObject();
        jsonObj.put("batchSize", BATCH_SIZE);
        jsonObj.put("status", getOrderStatus(model.getMarketplace().getTmallOrderStatus()));
        //jsonObj.put("marketplaceLogId", marketplacelogUUID);
        // set the correct timezone
        final String configTimezone = model.getMarketplace().getTimezone();
        boolean isValidTimezone = false;
        for (final String vaildTimezone : TimeZone.getAvailableIDs()) {
            if (vaildTimezone.equals(configTimezone)) {
                isValidTimezone = true;
                break;
            }
        }

        if (!isValidTimezone) {
            final String[] para = { configTimezone == null ? "" : configTimezone,
                    model.getMarketplace().getName() };
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.initorder.wrongtimezone", para),
                    NotificationEvent.Type.WARNING, "");
            LOG.warn("wrong timezone or missing timezone configed in market:"
                    + model.getMarketplace().getName());
            return;
        }

        final SimpleDateFormat format = new SimpleDateFormat(Config.getParameter(BACKOFFICE_FORMAT_DATEFORMAT));
        format.setTimeZone(TimeZone.getTimeZone(configTimezone));

        final String startTimeWithCorrectZone = format.format(model.getOrderStartTime()).toString();
        final String endTimeWithCorrectZone = format.format(model.getOrderEndTime()).toString();

        jsonObj.put("startCreated", startTimeWithCorrectZone);
        jsonObj.put("endCreated", endTimeWithCorrectZone);
        jsonObj.put("productCatalogVersion",
                model.getCatalogVersion().getCatalog().getId() + ":" + model.getCatalogVersion().getVersion());
        jsonObj.put("currency", model.getCurrency().getIsocode());

        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.initorder.success"),
                NotificationEvent.Type.SUCCESS, "");

        final JSONObject results = marketplaceHttpUtil.post(urlStr, jsonObj.toJSONString());

        final String msg = results.toJSONString();
        final String responseCode = results.get("code").toString();

        if ("401".equals(responseCode)) {
            LOG.error("=========================================================================");
            LOG.error("Order initial download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + responseCode);
            LOG.error("Request path: " + urlStr);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Authentication was failed, please re-authenticate again!");
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.order.authorization.fail"),
                    NotificationEvent.Type.FAILURE, "");
            LOG.warn("Authentication was failed, please re-authenticate again!");
            return;
        } else if (!("0".equals(responseCode))) {
            LOG.error("=========================================================================");
            LOG.error("Order initial download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + responseCode);
            LOG.error("Request path: " + urlStr);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("A known issue occurs in tmall, error details :" + msg);
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(
                    Labels.getLabel("marketplace.tmallapp.known.issues", new Object[] { msg }),
                    NotificationEvent.Type.FAILURE, "");
            LOG.warn("A known issue occurs in tmall, error details :" + msg);
            return;
        }

    } catch (final HttpClientErrorException httpError) {
        if (httpError.getStatusCode().is4xxClientError()) {
            LOG.error("=========================================================================");
            LOG.error("Order initial download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + httpError.getStatusCode().toString());
            LOG.error("Request path: " + urlStr);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Requested Tmall service URL is not correct!");
            LOG.error("Detail error info: " + httpError.getMessage());
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.request.post.error"),
                    NotificationEvent.Type.FAILURE, "");
        }
        if (httpError.getStatusCode().is5xxServerError()) {
            LOG.error("=========================================================================");
            LOG.error("Order initial download request post to Tmall failed!");
            LOG.error("Marketplacestore Code: " + model.getName());
            LOG.error("Error Status Code: " + httpError.getStatusCode().toString());
            LOG.error("Request path: " + urlStr);
            LOG.error("-------------------------------------------------------------------------");
            LOG.error("Failed Reason:");
            LOG.error("Requested Json Ojbect is not correct!");
            LOG.error("Detail error info: " + httpError.getMessage());
            LOG.error("=========================================================================");
            NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.process.error"),
                    NotificationEvent.Type.FAILURE, "");
        }
        LOG.error(httpError.toString());
        return;
    } catch (final ResourceAccessException raError) {
        LOG.error("=========================================================================");
        LOG.error("Order initial download request post to Tmall failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + urlStr);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Failed Reason:");
        LOG.error("Marketplace order download request server access failed!");
        LOG.error("Detail error info: " + raError.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.access.error"),
                NotificationEvent.Type.FAILURE, "");
        return;
    } catch (final HttpServerErrorException serverError) {
        LOG.error("=========================================================================");
        LOG.error("Order initial download request post to Tmall failed!");
        LOG.error("Marketplacestore Code: " + model.getName());
        LOG.error("Request path: " + urlStr);
        LOG.error("-------------------------------------------------------------------------");
        LOG.error("Failed Reason:");
        LOG.error("Marketplace order download request server process failed!");
        LOG.error("Detail error info: " + serverError.getMessage());
        LOG.error("=========================================================================");
        NotificationUtils.notifyUserVia(Labels.getLabel("marketplace.error.server.process.error"),
                NotificationEvent.Type.FAILURE, "");
        return;
    } catch (final Exception e) {
        final String errorMsg = e.getClass().toString() + ":" + e.getMessage();
        NotificationUtils.notifyUserVia(
                Labels.getLabel("marketplace.runtime.issues", new Object[] { errorMsg }),
                NotificationEvent.Type.FAILURE, "");
        LOG.warn(e.getMessage() + e.getStackTrace());
        return;
    }
    LOG.info("=========================================================================");
    LOG.info("Order initial download request post to Tmall suceessfully!");
    LOG.info("-------------------------------------------------------------------------");
    LOG.info("Marketplacestore Code: " + model.getName());
    LOG.info("Request path: " + urlStr);
    LOG.info("=========================================================================");

    //      logUtil.addMarketplaceLog("PENDING", model.getIntegrationId(), Labels.getLabel("marketplace.order.initial.action"),
    //            Labels.getLabel("marketplace.order.initial.object.type"), marketPlace, model, logUUID);
}