Example usage for java.util Objects toString

List of usage examples for java.util Objects toString

Introduction

In this page you can find the example usage for java.util Objects toString.

Prototype

public static String toString(Object o) 

Source Link

Document

Returns the result of calling toString for a non- null argument and "null" for a null argument.

Usage

From source file:com.joyent.manta.http.MantaHttpHeaders.java

/**
 * Returns the first {@code "Accept-Encoding"} header or {@code null} for none.
 *
 * @return {@code "Accept-Encoding"} header value as a {@code java.lang.String} value
 *//*ww w .j  a  v  a 2s  .  c o  m*/
public String getAcceptEncoding() {
    return Objects.toString(get(HttpHeaders.ACCEPT_ENCODING));
}

From source file:com.nubits.nubot.tasks.PriceMonitorTriggerTask.java

public void gracefulPause(LastPrice lp) {
    //This is called is an abnormal price is detected for one whole refresh period
    String logMessage;//ww  w  .  java2 s  . com
    String notification;
    String subject;
    MessageColor notificationColor;
    double sleepTime = 0;

    //we need to check the reason that the refresh took a whole period.
    //if it's because of a no connection issue, we need to wait to see if connection restarts
    if (!Global.exchange.getLiveData().isConnected()) {

        currentTime = System.currentTimeMillis();

        logMessage = "There has been a connection issue for " + Settings.CHECK_PRICE_INTERVAL + " seconds\n"
                + "Consider restarting the bot if the connection issue persists";
        notification = "";
        notificationColor = MessageColor.YELLOW;
        subject = Global.exchange.getName() + " Bot is suffering a connection issue";

    } else { //otherwise something bad has happened so we shutdown.
        int p = 3;
        sleepTime = Settings.CHECK_PRICE_INTERVAL * p;

        logMessage = "The Fetched Exchange rate data has remained outside of the required price band for "
                + Settings.CHECK_PRICE_INTERVAL + "seconds.\nThe bot will notify and restart in " + sleepTime
                + "seconds.";
        notification = "A large price difference was detected at " + Global.exchange.getName()
                + ".\nThe Last obtained price of " + Objects.toString(lp.getPrice().getQuantity())
                + " was outside of " + Objects.toString(PRICE_PERCENTAGE) + "% of the moving average figure of "
                + Objects.toString(getMovingAverage())
                + ".\nNuBot will remove the current orders and replace them in " + sleepTime + "seconds.";
        notificationColor = MessageColor.PURPLE;
        subject = Global.exchange.getName() + " Moving Average issue. Bot will replace orders in " + sleepTime
                + "seconds.";
    }

    //we want to send Hip Chat and mail notifications,
    // cancel all orders to avoid arbitrage against the bot and
    // exit execution gracefully
    LOG.error(logMessage);
    LOG.error("Notifying HipChat");
    HipChatNotifications.sendMessage(notification, notificationColor);
    LOG.error("Sending Email");
    MailNotifications.send(Global.options.getMailRecipient(), subject, notification);
    if (sleepTime > 0) {
        LOG.error("Cancelling Orders to avoid Arbitrage against the bot");
        Global.exchange.getTrade().clearOrders(Global.options.getPair());
        //clear the moving average so the restart is fresh
        queueMA.clear();
        LOG.error("Sleeping for " + sleepTime);
        SLEEP_COUNT = 3;
    }
    currentTime = System.currentTimeMillis();
}

From source file:com.nubits.nubot.trading.wrappers.BitcoinCoIDWrapper.java

private ApiResponse getLastTradesImpl(CurrencyPair pair, long startTime) {
    ApiResponse apiResponse = new ApiResponse();
    String url = API_BASE_URL;
    String method = API_TRADE_HISTORY;
    boolean isGet = false;
    HashMap<String, String> query_args = new HashMap<>();
    ArrayList<Trade> tradeList = new ArrayList<>();

    query_args.put("pair", pair.toStringSep());
    if (startTime > 0) {
        query_args.put("since", Objects.toString(startTime));
    }/*from  w  w  w.  j av  a  2 s  .  com*/

    ApiResponse response = getQuery(url, method, query_args, true, isGet);
    if (response.isPositive()) {
        JSONObject httpAnswerJson = (JSONObject) response.getResponseObject();
        JSONObject data = (JSONObject) httpAnswerJson.get("return");
        JSONArray trades = (JSONArray) data.get("trades");
        for (Iterator<JSONObject> trade = trades.iterator(); trade.hasNext();) {
            JSONObject thisTrade = trade.next();
            tradeList.add(parseTrade(thisTrade, pair));
        }
        apiResponse.setResponseObject(tradeList);
    } else {
        apiResponse = response;
    }

    return apiResponse;
}

From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java

/**
 *  This method encodes the parameter value as specified by Apache CloudStack
 *//*from  w  ww.j  a  va  2  s.c  o  m*/
protected String getUrlEncodedValue(Object paramValue) {
    String value = Objects.toString(paramValue);
    try {
        value = URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new ApacheCloudStackClientRuntimeException(e);
    }
    return value.replaceAll("\\+", "%20");
}

From source file:com.nubits.nubot.tasks.PriceMonitorTriggerTask.java

public void updateLastPrice(LastPrice lp, ArrayList<LastPrice> priceList) {
    if (SessionManager.sessionInterrupted())
        return; //external interruption

    //We need to fill up the moving average queue so that 30 data points exist.
    if (queueMA.size() < MOVING_AVERAGE_SIZE) {
        initMA(lp.getPrice().getQuantity());
    }//from w  w w.  j  ava  2 s  .c  o  m

    if (!Global.options.isMultipleCustodians()) { //
        //we check against the moving average
        double current = lp.getPrice().getQuantity();
        double MA = getMovingAverage();

        //calculate the percentage difference
        double percentageDiff = (((MA - current) / ((MA + current) / 2)) * 100);
        if ((percentageDiff > PRICE_PERCENTAGE) || (percentageDiff < -PRICE_PERCENTAGE)) {
            //The potential price is more than % different to the moving average
            //add it to the MA-Queue to raise the Moving Average and re-request the currency data
            //in this way we can react to a large change in price when we are sure it is not an anomaly
            LOG.warn("Latest price " + Objects.toString(current) + " is " + Objects.toString(percentageDiff)
                    + "% outside of the moving average of " + Objects.toString(MA) + "."
                    + "\nShifting moving average and re-fetching exchange rate data.");
            updateMovingAverageQueue(current);

            try {
                int trials = 1;
                executeUpdatePrice(trials);
            } catch (FeedPriceException ex) {

            }
            return;
        }
        //the potential price is within the % boundary.
        //add it to the MA-Queue to keep the moving average moving
        // Only do this if the standard update interval hasn't passed
        if (((System.currentTimeMillis() - (currentTime + REFRESH_OFFSET))
                / 1000L) < Settings.CHECK_PRICE_INTERVAL) {
            updateMovingAverageQueue(current);
        } else {
            //If we get here, we haven't had a price within % of the average for as long as a standard update period
            //the action is to send notifications, cancel all orders and turn off the bot
            gracefulPause(lp);
            return;
        }
    }
    if (SessionManager.sessionInterrupted())
        return; //external interruption

    //carry on with updating the wall price shift
    this.lastPrice = lp;
    this.lastPrices = priceList;

    LOG.info("Price Updated. " + lp.getSource() + ":1 " + lp.getCurrencyMeasured().getCode() + " = " + ""
            + lp.getPrice().getQuantity() + " " + lp.getPrice().getCurrency().getCode());
    if (isFirstTimeExecution) {
        try {
            initStrategy(lp.getPrice().getQuantity());
        } catch (NuBotConnectionException e) {

        }
        currentWallPEGPrice = lp;
        isFirstTimeExecution = false;
    } else {
        verifyPegPrices();
    }
}

From source file:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get application run info for the specified job
 * <p>/*from   w ww .  java2s . c om*/
 * @param appId
 * @param sc
 * @param req
 * @return url
 */
@GET
@Path("/{appId}/appinfo")
@Produces(MediaType.APPLICATION_JSON)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getAppInfo(@PathParam("appId") String appId, @Context SecurityContext sc,
        @Context HttpServletRequest req) {
    Response response = checkAccessRight(appId);
    if (response != null) {
        return response;
    } else {
        Execution execution = exeFacade.findByAppId(appId);
        try {
            long startTime = System.currentTimeMillis() - 60000;
            long endTime = System.currentTimeMillis();
            boolean running = true;
            if (execution != null) {
                startTime = execution.getSubmissionTime().getTime();
                endTime = startTime + execution.getExecutionDuration();
                running = false;
                if (!execution.getState().isFinalState()) {
                    running = true;
                }
            }

            InfluxDB influxDB = InfluxDBFactory.connect(settings.getInfluxDBAddress(),
                    settings.getInfluxDBUser(), settings.getInfluxDBPW());

            // Transform application_1493112123688_0001 to 1493112123688_0001
            // application_ = 12 chars
            String timestamp_attempt = appId.substring(12);

            Query query = new Query("show tag values from nodemanager with key=\"source\" "
                    + "where source =~ /^.*" + timestamp_attempt + ".*$/", "graphite");
            QueryResult queryResult = influxDB.query(query, TimeUnit.MILLISECONDS);

            int nbExecutors = 0;
            HashMap<Integer, List<String>> executorInfo = new HashMap<>();
            int index = 0;
            if (queryResult != null && queryResult.getResults() != null) {
                for (QueryResult.Result res : queryResult.getResults()) {
                    if (res.getSeries() != null) {
                        for (QueryResult.Series series : res.getSeries()) {
                            List<List<Object>> values = series.getValues();
                            if (values != null) {
                                nbExecutors += values.size();
                                for (List<Object> l : values) {
                                    executorInfo.put(index,
                                            Stream.of(Objects.toString(l.get(1))).collect(Collectors.toList()));
                                    index++;
                                }
                            }
                        }
                    }
                }
            }

            /*
             * At this point executor info contains the keys and a list with a single value, the YARN container id
             */
            String vCoreTemp = null;
            HashMap<String, String> hostnameVCoreCache = new HashMap<>();

            for (Map.Entry<Integer, List<String>> entry : executorInfo.entrySet()) {
                query = new Query(
                        "select MilliVcoreUsageAvgMilliVcores, hostname from nodemanager where source = \'"
                                + entry.getValue().get(0) + "\' limit 1",
                        "graphite");
                queryResult = influxDB.query(query, TimeUnit.MILLISECONDS);

                if (queryResult != null && queryResult.getResults() != null
                        && queryResult.getResults().get(0) != null
                        && queryResult.getResults().get(0).getSeries() != null) {
                    List<List<Object>> values = queryResult.getResults().get(0).getSeries().get(0).getValues();
                    String hostname = Objects.toString(values.get(0).get(2)).split("=")[1];
                    entry.getValue().add(hostname);

                    if (!hostnameVCoreCache.containsKey(hostname)) {
                        // Not in cache, get the vcores of the host machine
                        query = new Query("select AllocatedVCores+AvailableVCores from nodemanager "
                                + "where hostname =~ /.*" + hostname + ".*/ limit 1", "graphite");
                        queryResult = influxDB.query(query, TimeUnit.MILLISECONDS);

                        if (queryResult != null && queryResult.getResults() != null
                                && queryResult.getResults().get(0) != null
                                && queryResult.getResults().get(0).getSeries() != null) {
                            values = queryResult.getResults().get(0).getSeries().get(0).getValues();
                            vCoreTemp = Objects.toString(values.get(0).get(1));
                            entry.getValue().add(vCoreTemp);
                            hostnameVCoreCache.put(hostname, vCoreTemp); // cache it
                        }
                    } else {
                        // It's a hit, skip the database query
                        entry.getValue().add(hostnameVCoreCache.get(hostname));
                    }
                }
            }

            influxDB.close();

            AppInfoDTO appInfo = new AppInfoDTO(appId, startTime, running, endTime, nbExecutors, executorInfo);

            return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(appInfo).build();

        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "exception while geting job ui " + e.getLocalizedMessage(), e);
        }
        return noCacheResponse.getNoCacheResponseBuilder(Response.Status.NOT_FOUND).build();
    }
}

From source file:org.opencb.opencga.storage.core.variant.VariantStoragePipeline.java

/**
 * PreLoad step for modify the StudyConfiguration.
 * This step is executed inside a study lock.
 *
 * @see StudyConfigurationManager#lockStudy(int)
 * @param studyConfiguration    StudyConfiguration
 * @param source                VariantSource
 * @throws StorageEngineException  If any condition is wrong
 *//*from  www.  ja  v a 2s. c om*/
protected void securePreLoad(StudyConfiguration studyConfiguration, VariantSource source)
        throws StorageEngineException {

    /*
     * Before load file, check and add fileName to the StudyConfiguration.
     * FileID and FileName is read from the VariantSource
     * If fileId is -1, read fileId from Options
     * Will fail if:
     *     fileId is not an integer
     *     fileId was already in the studyConfiguration.indexedFiles
     *     fileId was already in the studyConfiguration.fileIds with a different fileName
     *     fileName was already in the studyConfiguration.fileIds with a different fileId
     */

    int fileId;
    String fileName = source.getFileName();
    try {
        fileId = Integer.parseInt(source.getFileId());
    } catch (NumberFormatException e) {
        throw new StorageEngineException("FileId '" + source.getFileId() + "' is not an integer", e);
    }

    if (fileId < 0) {
        fileId = options.getInt(Options.FILE_ID.key(), Options.FILE_ID.defaultValue());
    } else {
        int fileIdFromParams = options.getInt(Options.FILE_ID.key(), Options.FILE_ID.defaultValue());
        if (fileIdFromParams >= 0 && fileIdFromParams != fileId) {
            if (!options.getBoolean(Options.OVERRIDE_FILE_ID.key(), Options.OVERRIDE_FILE_ID.defaultValue())) {
                throw new StorageEngineException("Wrong fileId! Unable to load using fileId: "
                        + fileIdFromParams + ". " + "The input file has fileId: " + fileId + ". Use "
                        + Options.OVERRIDE_FILE_ID.key() + " to ignore original fileId.");
            } else {
                //Override the fileId
                fileId = fileIdFromParams;
            }
        }
    }

    if (studyConfiguration.getIndexedFiles().isEmpty()) {
        // First indexed file
        // Use the EXCLUDE_GENOTYPES value from CLI. Write in StudyConfiguration.attributes
        boolean excludeGenotypes = options.getBoolean(Options.EXCLUDE_GENOTYPES.key(),
                Options.EXCLUDE_GENOTYPES.defaultValue());
        studyConfiguration.setAggregation(options.get(Options.AGGREGATED_TYPE.key(),
                VariantSource.Aggregation.class, Options.AGGREGATED_TYPE.defaultValue()));
        studyConfiguration.getAttributes().put(Options.EXCLUDE_GENOTYPES.key(), excludeGenotypes);
    } else {
        // Not first indexed file
        // Use the EXCLUDE_GENOTYPES value from StudyConfiguration. Ignore CLI value
        boolean excludeGenotypes = studyConfiguration.getAttributes()
                .getBoolean(Options.EXCLUDE_GENOTYPES.key(), Options.EXCLUDE_GENOTYPES.defaultValue());
        options.put(Options.EXCLUDE_GENOTYPES.key(), excludeGenotypes);
    }

    fileId = checkNewFile(studyConfiguration, fileId, fileName);
    options.put(Options.FILE_ID.key(), fileId);
    studyConfiguration.getFileIds().put(source.getFileName(), fileId);
    //        studyConfiguration.getHeaders().put(fileId, source.getMetadata().get(VariantFileUtils.VARIANT_FILE_HEADER).toString());

    checkAndUpdateStudyConfiguration(studyConfiguration, fileId, source, options);

    // Check Extra genotype fields
    if (options.containsKey(Options.EXTRA_GENOTYPE_FIELDS.key())
            && StringUtils.isNotEmpty(options.getString(Options.EXTRA_GENOTYPE_FIELDS.key()))) {
        List<String> extraFields = options.getAsStringList(Options.EXTRA_GENOTYPE_FIELDS.key());
        if (studyConfiguration.getIndexedFiles().isEmpty()) {
            studyConfiguration.getAttributes().put(Options.EXTRA_GENOTYPE_FIELDS.key(), extraFields);
        } else {
            if (!extraFields.equals(
                    studyConfiguration.getAttributes().getAsStringList(Options.EXTRA_GENOTYPE_FIELDS.key()))) {
                throw new StorageEngineException(
                        "Unable to change Stored Extra Fields if there are already indexed files.");
            }
        }
        if (!studyConfiguration.getAttributes().containsKey(Options.EXTRA_GENOTYPE_FIELDS_TYPE.key())) {
            List<String> extraFieldsType = new ArrayList<>(extraFields.size());
            for (String extraField : extraFields) {
                List<Map<String, Object>> formats = (List) source.getHeader().getMeta().get("FORMAT");
                VCFHeaderLineType type = VCFHeaderLineType.String;
                for (Map<String, Object> format : formats) {
                    if (format.get("ID").toString().equals(extraField)) {
                        if ("1".equals(format.get("Number"))) {
                            try {
                                type = VCFHeaderLineType.valueOf(Objects.toString(format.get("Type")));
                            } catch (IllegalArgumentException ignore) {
                                type = VCFHeaderLineType.String;
                            }
                        } else {
                            //Fields with arity != 1 are loaded as String
                            type = VCFHeaderLineType.String;
                        }
                        break;
                    }
                }
                switch (type) {
                case String:
                case Float:
                case Integer:
                    break;
                case Character:
                default:
                    type = VCFHeaderLineType.String;
                    break;

                }
                extraFieldsType.add(type.toString());
                logger.debug(extraField + " : " + type);
            }
            studyConfiguration.getAttributes().put(Options.EXTRA_GENOTYPE_FIELDS_TYPE.key(), extraFieldsType);
        }
    }
}

From source file:org.apache.hadoop.hbase.backup.impl.BackupSystemTable.java

/**
 * Add tables to global incremental backup set
 * @param tables set of tables//from  w  w  w .  j  a v a 2 s.c o m
 * @param backupRoot root directory path to backup
 * @throws IOException exception
 */
public void addIncrementalBackupTableSet(Set<TableName> tables, String backupRoot) throws IOException {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Add incremental backup table set to backup system table. ROOT=" + backupRoot + " tables ["
                + StringUtils.join(tables, " ") + "]");
    }
    if (LOG.isDebugEnabled()) {
        tables.forEach(table -> LOG.debug(Objects.toString(table)));
    }
    try (Table table = connection.getTable(tableName)) {
        Put put = createPutForIncrBackupTableSet(tables, backupRoot);
        table.put(put);
    }
}

From source file:com.emc.storageos.api.service.impl.resource.DisasterRecoveryService.java

private void precheckForResumeLocalStandby() {
    Site localSite = drUtil.getLocalSite();
    if (!isClusterStable()) {
        throw APIException.serviceUnavailable.siteClusterStateNotStable(localSite.getName(),
                Objects.toString(coordinator.getControlNodesState()));
    }//from  w  w w  .  j a  v  a  2 s  .  co m

    if (SiteState.STANDBY_PAUSED != localSite.getState()) {
        throw APIException.internalServerErrors.resumeStandbyPrecheckFailed(localSite.getName(),
                "Standby site is not in paused state");
    }
}

From source file:com.yinghua.translation.rest.PhoneResourceRESTService.java

/**
 * /*from  w w w  .  j av a  2 s .  c  om*/
 * 
 * @param params
 * @return
 */
@POST
@GET
@Path("/billNotify")
//   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
@Encoded
public String billNotify(@QueryParam("v_count") int count, @QueryParam("v_oid") String oids,
        @QueryParam("v_pmode") String pmodes, @QueryParam("v_pstatus") String pstatus,
        @QueryParam("v_pstring") String pstrings, @QueryParam("v_amount") String amounts,
        @QueryParam("v_moneytype") String moneytype, @QueryParam("v_mac") String mac,
        @QueryParam("v_md5money") String md5money, @QueryParam("v_sign") String sign) {
    String result = "error";
    if (count > 0) {
        String regex = "\\|_\\|";
        if (oids != null && pstatus != null && pmodes != null && pstrings != null && amounts != null
                && moneytype != null) {
            String[] oid = oids.split(regex);
            String[] status = pstatus.split(regex);
            String[] pmode = pmodes.split(regex);
            String[] pstring = pstrings.split(regex);
            String[] amount = amounts.split(regex);
            String[] mtype = moneytype.split(regex);
            for (int i = 0; i < count; i++) {
                if (oid[i] != null) {
                    try {
                        String orderNo = Objects.toString(oid[i]);
                        MemberOrder order = memberOrderBean.findByPayNo(orderNo);
                        if (order != null && "1".equals(status[i])) {
                            if (order.getState() != OrderStatus.FINISHED) {//????
                                order.setState(OrderStatus.FINISHED);
                                List<PackageProductContent> ppcs = packageProductContentBean
                                        .findByPackageNo(order.getPackageNo());
                                switch (order.getPackageType()) {
                                case "1":
                                    //
                                    for (PackageProductContent packageProductContent : ppcs) {
                                        MemberOrderUse mou = new MemberOrderUse();
                                        mou.setOrderNo(order.getOrderNo());
                                        mou.setProductNo(packageProductContent.getProductNo());
                                        mou.setTimes(packageProductContent.getTimes());
                                        memberOrderUseBean.createMemberOrderUse(mou);
                                    }
                                    break;
                                case "2":
                                    //
                                    for (PackageProductContent packageProductContent : ppcs) {
                                        MemberOrderUse mou = new MemberOrderUse();
                                        mou.setOrderNo(order.getOrderNo());
                                        mou.setProductNo(packageProductContent.getProductNo());
                                        mou.setTimes(packageProductContent.getTimes());
                                        memberOrderUseBean.createMemberOrderUse(mou);
                                    }
                                    break;
                                case "3":
                                    //?
                                    JSONObject obj = JSONObject.parseObject(order.getRemark());
                                    for (String key : obj.keySet()) {
                                        MemberOrderUse mou = new MemberOrderUse();
                                        mou.setOrderNo(order.getOrderNo());
                                        mou.setProductNo(key);
                                        mou.setTimes(obj.getIntValue(key));
                                        memberOrderUseBean.createMemberOrderUse(mou);
                                    }
                                    break;
                                }
                                if (System.currentTimeMillis() >= order.getServiceTime().getTime()) {
                                    //                                  Account account = accountBean.findByMemberNo(order.getMemberNumber());
                                    //                                  int addCall = order.getSurplusCallDuration()+account.getSurplusCallDuration();
                                    //                                  account.setSurplusCallDuration(addCall);
                                    //                                  accountBean.updateAccount(account);
                                    order.setUseState(OrderUseStatus.USING);
                                }
                                memberOrderBean.updateOrder(order);
                                System.out.println("orderNo:" + order.getOrderNo() + "|orderState:"
                                        + order.getState() + "|orderUseState:" + order.getUseState());
                            }
                        } else {
                            System.out.println("??");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        PayEasyLog payel = new PayEasyLog();
                        payel.setOid(oid[i]);
                        payel.setPstatus(status[i]);
                        payel.setPmode(URLDecoder.decode(pmode[i], "gbk"));
                        payel.setPstring(URLDecoder.decode(pstring[i], "gbk"));
                        payel.setAmount(amount[i]);
                        payel.setMoneytype(mtype[i]);
                        payel.setMac(mac);
                        payel.setMd5money(md5money);
                        payel.setSign(sign);
                        payEasyLogBean.create(payel);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            result = "send";
        }
    }
    return result;
}