Example usage for java.lang InternalError InternalError

List of usage examples for java.lang InternalError InternalError

Introduction

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

Prototype

public InternalError(Throwable cause) 

Source Link

Document

Constructs an InternalError with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.swordlord.jalapeno.datacontainer.DataContainer.java

/**
 * Gets the table from row.//from  w ww . ja  v a 2s  .  com
 * 
 * @param clazz the clazz
 * 
 * @return the table from row
 */
public DataTableBase getTableFromRow(Class<? extends DataRowBase> clazz) {
    if (clazz == null) {
        throw new InternalError("DataRow is null (clazz)");
    }

    String strClassName = clazz.getName();

    strClassName = strClassName.replaceAll("DataRow", "DataTable");
    strClassName = strClassName.replaceAll("datarow", "datatable");

    return getTableByAbsoluteName(strClassName);
}

From source file:com.clustercontrol.accesscontrol.dialog.SystemPrivilegeDialog.java

/**
 * ???//from   w ww. j a v a  2s  .com
 *
 * @param roleInfo ????
 */
protected void setInputData(String managerName, RoleInfo roleInfo) {

    this.inputData = roleInfo;

    // ????

    java.util.List<String> allSystemPrivilegeList = null;
    java.util.List<SystemPrivilegeInfo> roleSystemPrivilegeKeyList = null;
    // ??
    allSystemPrivilegeList = SystemPrivilegePropertyUtil.getSystemPrivilegeNameList(managerName);
    //TODO ?????????????????????SWT?????????
    java.util.Collections.sort(allSystemPrivilegeList);
    // ??
    try {
        AccessEndpointWrapper wrapper = AccessEndpointWrapper.getWrapper(managerName);
        roleSystemPrivilegeKeyList = wrapper.getSystemPrivilegeInfoListByRoleId(roleId);
    } catch (InvalidRole_Exception e) {
        // ???
        MessageDialog.openInformation(null, Messages.getString("message"),
                Messages.getString("message.accesscontrol.16"));
        throw new InternalError(e.getMessage());
    } catch (Exception e) {
        // ?
        m_log.warn("getOwnUserList(), " + HinemosMessage.replace(e.getMessage()), e);
        MessageDialog.openError(null, Messages.getString("failed"),
                Messages.getString("message.hinemos.failure.unexpected") + ", "
                        + HinemosMessage.replace(e.getMessage()));
        throw new InternalError(e.getMessage());
    }
    java.util.List<String> roleSystemPrivilegeValueList = getSystemPrivilegeValueList(
            roleSystemPrivilegeKeyList);
    // ?
    for (String SystemPrivilege : allSystemPrivilegeList) {
        if (roleSystemPrivilegeValueList.contains(SystemPrivilege)) {
            this.listRoleSystemPrivilege.add(SystemPrivilege);
        } else {
            this.listNotRoleSystemPrivilege.add(SystemPrivilege);
        }
    }
}

From source file:com.manydesigns.portofino.persistence.QueryUtils.java

/**
 * Tranforms a {@link TableCriteria} to a query string with an associated array of parameters.
 * /*from w w w  .j a v a2  s .  com*/
 * @param criteria the criteria.
 * @param alias the alias to use for the main entity.
 * @return the same criteria encoded as a HQL query with parameters.
 */
public static QueryStringWithParameters getQueryStringWithParametersForCriteria(
        @Nullable TableCriteria criteria, @Nullable String alias) {
    if (criteria == null) {
        return new QueryStringWithParameters("", new Object[0]);
    }
    Table table = criteria.getTable();

    ArrayList<Object> parametersList = new ArrayList<Object>();
    StringBuilder whereBuilder = new StringBuilder();
    for (Criterion criterion : criteria) {
        PropertyAccessor accessor = criterion.getPropertyAccessor();
        String hqlFormat;
        if (criterion instanceof TableCriteria.EqCriterion) {
            TableCriteria.EqCriterion eqCriterion = (TableCriteria.EqCriterion) criterion;
            Object value = eqCriterion.getValue();
            hqlFormat = "{0} = ?";
            parametersList.add(value);
        } else if (criterion instanceof TableCriteria.InCriterion) {
            TableCriteria.InCriterion inCriterion = (TableCriteria.InCriterion) criterion;
            Object[] values = inCriterion.getValues();
            StringBuilder params = new StringBuilder();
            if (values != null) {
                boolean first = true;
                for (Object value : values) {
                    if (!first) {
                        params.append(", ?");
                    } else {
                        params.append("?");
                        first = false;
                    }
                    parametersList.add(value);
                }
                hqlFormat = "{0} in (" + params.toString() + ")";
            } else {
                hqlFormat = null;
            }
        } else if (criterion instanceof TableCriteria.NeCriterion) {
            TableCriteria.NeCriterion neCriterion = (TableCriteria.NeCriterion) criterion;
            Object value = neCriterion.getValue();
            hqlFormat = "{0} <> ?";
            parametersList.add(value);
        } else if (criterion instanceof TableCriteria.BetweenCriterion) {
            TableCriteria.BetweenCriterion betweenCriterion = (TableCriteria.BetweenCriterion) criterion;
            Object min = betweenCriterion.getMin();
            Object max = betweenCriterion.getMax();
            hqlFormat = "{0} >= ? AND {0} <= ?";
            parametersList.add(min);
            parametersList.add(max);
        } else if (criterion instanceof TableCriteria.GtCriterion) {
            TableCriteria.GtCriterion gtCriterion = (TableCriteria.GtCriterion) criterion;
            Object value = gtCriterion.getValue();
            hqlFormat = "{0} > ?";
            parametersList.add(value);
        } else if (criterion instanceof TableCriteria.GeCriterion) {
            TableCriteria.GeCriterion gtCriterion = (TableCriteria.GeCriterion) criterion;
            Object value = gtCriterion.getValue();
            hqlFormat = "{0} >= ?";
            parametersList.add(value);
        } else if (criterion instanceof TableCriteria.LtCriterion) {
            TableCriteria.LtCriterion ltCriterion = (TableCriteria.LtCriterion) criterion;
            Object value = ltCriterion.getValue();
            hqlFormat = "{0} < ?";
            parametersList.add(value);
        } else if (criterion instanceof TableCriteria.LeCriterion) {
            TableCriteria.LeCriterion leCriterion = (TableCriteria.LeCriterion) criterion;
            Object value = leCriterion.getValue();
            hqlFormat = "{0} <= ?";
            parametersList.add(value);
        } else if (criterion instanceof TableCriteria.LikeCriterion) {
            TableCriteria.LikeCriterion likeCriterion = (TableCriteria.LikeCriterion) criterion;
            String value = (String) likeCriterion.getValue();
            String pattern = processTextMatchMode(likeCriterion.getTextMatchMode(), value);
            hqlFormat = "{0} like ?";
            parametersList.add(pattern);
        } else if (criterion instanceof TableCriteria.IlikeCriterion) {
            TableCriteria.IlikeCriterion ilikeCriterion = (TableCriteria.IlikeCriterion) criterion;
            String value = (String) ilikeCriterion.getValue();
            String pattern = processTextMatchMode(ilikeCriterion.getTextMatchMode(), value);
            hqlFormat = "lower({0}) like lower(?)";
            parametersList.add(pattern);
        } else if (criterion instanceof TableCriteria.IsNullCriterion) {
            hqlFormat = "{0} is null";
        } else if (criterion instanceof TableCriteria.IsNotNullCriterion) {
            hqlFormat = "{0} is not null";
        } else {
            logger.error("Unrecognized criterion: {}", criterion);
            throw new InternalError("Unrecognied criterion");
        }

        if (hqlFormat == null) {
            continue;
        }

        String accessorName = accessor.getName();
        if (alias != null) {
            accessorName = alias + "." + accessorName;
        }
        String hql = MessageFormat.format(hqlFormat, accessorName);

        if (whereBuilder.length() > 0) {
            whereBuilder.append(" AND ");
        }
        whereBuilder.append(hql);
    }
    String whereClause = whereBuilder.toString();
    String queryString;
    String actualEntityName = table.getActualEntityName();
    if (alias != null) {
        actualEntityName += " " + alias;
    }
    if (whereClause.length() > 0) {
        queryString = MessageFormat.format("FROM {0}" + WHERE_STRING + "{1}", actualEntityName, whereClause);
    } else {
        queryString = MessageFormat.format("FROM {0}", actualEntityName);
    }

    Object[] parameters = new Object[parametersList.size()];
    parametersList.toArray(parameters);

    return new QueryStringWithParameters(queryString, parameters);
}

From source file:org.projectforge.database.XmlDump.java

/**
 * @param o1/*  w  w  w  .j  a va 2s .  com*/
 * @param o2
 * @param logDifference If true than the difference is logged.
 * @return True if the given objects are equal.
 */
private boolean equals(final Object o1, final Object o2, final boolean logDifference) {
    if (o1 == null) {
        final boolean equals = (o2 == null);
        if (equals == false && logDifference == true) {
            log.error("Value 1 is null and value 2 is " + o2);
        }
        return equals;
    } else if (o2 == null) {
        if (logDifference == true) {
            log.error("Value 2 is null and value 1 is " + o1);
        }
        return false;
    }
    final Class<?> cls1 = o1.getClass();
    final Field[] fields = cls1.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (final Field field : fields) {
        if (accept(field) == false) {
            continue;
        }
        try {
            final Object fieldValue1 = getValue(o1, o2, field);
            final Object fieldValue2 = getValue(o2, o1, field);
            if (field.getType().isPrimitive() == true) {
                if (ObjectUtils.equals(fieldValue2, fieldValue1) == false) {
                    if (logDifference == true) {
                        log.error("Field '" + field.getName() + "': value 1 '" + fieldValue1
                                + "' is different from value 2 '" + fieldValue2 + "'.");
                    }
                    return false;
                }
                continue;
            } else if (fieldValue1 == null) {
                if (fieldValue2 != null) {
                    if (logDifference == true) {
                        log.error("Field '" + field.getName() + "': value 1 '" + fieldValue1
                                + "' is different from value 2 '" + fieldValue2 + "'.");
                    }
                    return false;
                }
            } else if (fieldValue2 == null) {
                if (fieldValue1 != null) {
                    if (logDifference == true) {
                        log.error("Field '" + field.getName() + "': value 1 '" + fieldValue1
                                + "' is different from value 2 '" + fieldValue2 + "'.");
                    }
                    return false;
                }
            } else if (fieldValue1 instanceof Collection<?>) {
                final Collection<?> col1 = (Collection<?>) fieldValue1;
                final Collection<?> col2 = (Collection<?>) fieldValue2;
                if (col1.size() != col2.size()) {
                    if (logDifference == true) {
                        log.error("Field '" + field.getName() + "': colection's size '" + col1.size()
                                + "' is different from collection's size '" + col2.size() + "'.");
                    }
                    return false;
                }
                if (equals(field, col1, col2, logDifference) == false
                        || equals(field, col2, col1, logDifference) == false) {
                    return false;
                }
            } else if (HibernateUtils.isEntity(fieldValue1.getClass()) == true) {
                if (fieldValue2 == null || ObjectUtils.equals(HibernateUtils.getIdentifier(fieldValue1),
                        HibernateUtils.getIdentifier(fieldValue2)) == false) {
                    if (logDifference == true) {
                        log.error("Field '" + field.getName() + "': Hibernate object id '"
                                + HibernateUtils.getIdentifier(fieldValue1) + "' is different from id '"
                                + HibernateUtils.getIdentifier(fieldValue2) + "'.");
                    }
                    return false;
                }
            } else if (fieldValue1 instanceof BigDecimal) {
                if (fieldValue2 == null
                        || ((BigDecimal) fieldValue1).compareTo((BigDecimal) fieldValue2) != 0) {
                    if (logDifference == true) {
                        log.error("Field '" + field.getName() + "': value 1 '" + fieldValue1
                                + "' is different from value 2 '" + fieldValue2 + "'.");
                    }
                    return false;
                }
            } else if (ObjectUtils.equals(fieldValue2, fieldValue1) == false) {
                if (logDifference == true) {
                    log.error("Field '" + field.getName() + "': value 1 '" + fieldValue1
                            + "' is different from value 2 '" + fieldValue2 + "'.");
                }
                return false;
            }
        } catch (final IllegalAccessException ex) {
            throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
        }
    }
    return true;
}

From source file:fullThreadDump.java

private void parseMBeanInfo() throws IOException {
    try {/* w  w  w . ja va2 s.  com*/
        MBeanOperationInfo[] mopis = server.getMBeanInfo(objname).getOperations();
        // look for findDeadlockedThreads operations;
        boolean found = false;
        for (MBeanOperationInfo op : mopis) {
            if (op.getName().equals(findDeadlocksMethodName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            // if findDeadlockedThreads operation doesn't exist,
            // the target VM is running on JDK 5 and details about
            // synchronizers and locks cannot be dumped.
            findDeadlocksMethodName = "findMonitorDeadlockedThreads";
            canDumpLocks = false;
        }
    } catch (IntrospectionException e) {
        InternalError ie = new InternalError(e.getMessage());
        ie.initCause(e);
        throw ie;
    } catch (InstanceNotFoundException e) {
        InternalError ie = new InternalError(e.getMessage());
        ie.initCause(e);
        throw ie;
    } catch (ReflectionException e) {
        InternalError ie = new InternalError(e.getMessage());
        ie.initCause(e);
        throw ie;
    }
}

From source file:org.dasein.cloud.azure.platform.AzureSqlDatabaseSupport.java

@Override
public void revokeAccess(String providerDatabaseId, String sourceCide)
        throws CloudException, InternalException {
    Database database = getDatabase(providerDatabaseId);
    if (database == null)
        throw new InternalException("Invaid database provider Id");

    List<String> ruleParts = Arrays.asList(sourceCide.split("::"));
    if (ruleParts.size() != 3)
        throw new InternalError("Invalid parameter sourceCidr");

    String ruleName = ruleParts.get(0);
    String serverName = Arrays.asList(database.getProviderDatabaseId().split(":")).get(0);

    HttpUriRequest deleteRuleRequest = new AzureSQLDatabaseSupportRequests(provider)
            .deleteFirewallRule(serverName, ruleName).build();
    new AzureRequester(provider, deleteRuleRequest).execute();
}

From source file:net.sf.firemox.tools.MToolKit.java

/**
 * Write the specified positive short coded on 2 bytes to the specified input
 * stream//from ww  w .  j a  v a 2  s  .  c o  m
 * 
 * @param out
 *          is the output stream where the specified integer would be written
 * @param int16
 *          the 2 bytes integer to write
 */
public static void writeInt16(OutputStream out, int int16) {
    try {
        out.write(int16 / 256);
        out.write(int16 % 256);
    } catch (Exception e) {
        throw new InternalError("writing int16 in file," + e);
    }
}

From source file:org.diorite.config.impl.ConfigPropertyTemplateImpl.java

private Object getPrimitiveDefault() {
    Class<T> rawType = this.rawType;
    if (rawType == boolean.class) {
        return false;
    }/* ww w  .ja  va 2s.  c o  m*/
    if (rawType == byte.class) {
        return (byte) 0;
    }
    if (rawType == short.class) {
        return (short) 0;
    }
    if (rawType == char.class) {
        return '\0';
    }
    if (rawType == int.class) {
        return 0;
    }
    if (rawType == long.class) {
        return 0L;
    }
    if (rawType == float.class) {
        return 0.0F;
    }
    if (rawType == double.class) {
        return 0.0;
    }
    throw new InternalError("Unknown primitive type:" + rawType);
}

From source file:com.clustercontrol.hub.session.FluentdTransferFactory.java

/**
 * ?????????//from   ww  w.jav  a 2  s  .  co m
 * 
 */
@Override
public Transfer createTansfer(final TransferInfo info, final PropertyBinder binder) throws TransferException {
    // HTTP ?????
    TransferDestProp urlProp = null;
    TransferDestProp connectTimeoutProp = null;
    TransferDestProp requestTimeoutProp = null;
    for (TransferDestProp prop : info.getDestProps()) {
        switch (prop.getName()) {
        case prop_url:
            urlProp = prop;
            break;
        case prop_connect_timeout:
            connectTimeoutProp = prop;
            break;
        case prop_request_timeout:
            requestTimeoutProp = prop;
            break;
        default:
            logger.warn(String.format("createTansfer() : unknown property(%s)", prop.getValue()));
            break;
        }
    }

    if (urlProp == null || urlProp.getValue() == null)
        throw new TransferException(String.format("createTansfer() : Value of \"%s\" must be set.", prop_url));

    if (!urlPattern.matcher(urlProp.getValue()).matches())
        throw new TransferException(
                String.format("createTansfer() : invalid url format. url=%s", urlProp.getValue()));

    final String urlStr = urlProp.getValue();

    Integer timeout;
    try {
        timeout = Integer.valueOf(connectTimeoutProp.getValue());
    } catch (NumberFormatException e) {
        timeout = DEFAULT_CONNECT_TIMEOUT;
        logger.warn(String.format("createTansfer() : can't regognize connectTimeout(%s) as number.",
                connectTimeoutProp.getValue()));
    } catch (NullPointerException e) {
        timeout = DEFAULT_CONNECT_TIMEOUT;
        logger.warn(String.format(
                "createTansfer() : connectTimeout is null, then use default value as connectTimeout(%s).",
                timeout));
    }
    final Integer connectTimeout = timeout;

    try {
        timeout = Integer.valueOf(requestTimeoutProp.getValue());
    } catch (NumberFormatException e) {
        timeout = DEFAULT_REQUEST_TIMEOUT;
        logger.warn(String.format("createTansfer() : can't regognize requestTimeout(%s) as number.",
                requestTimeoutProp.getValue()));
    } catch (NullPointerException e) {
        timeout = DEFAULT_CONNECT_TIMEOUT;
        logger.warn(String.format(
                "createTansfer() : requestTimeout is null, then use default value as requestTimeout(%s).",
                timeout));
    }
    final Integer requestTimeout = timeout;

    // ??
    return new Transfer() {
        private static final int BUFF_SIZE = 1024 * 1024;
        private static final int BODY_MAX_SIZE = 5 * BUFF_SIZE;

        private CloseableHttpClient client = null;

        /*
         * ??
         * 
         */
        @Override
        public TransferNumericData transferNumerics(Iterable<TransferNumericData> numerics,
                TrasferCallback<TransferNumericData> callback) throws TransferException {
            TransferNumericData lastPosition = null;
            for (TransferNumericData numeric : numerics) {
                ObjectNode root = JsonNodeFactory.instance.objectNode();
                root.put("item_name", numeric.key.getItemName());
                root.put("display_name", numeric.key.getDisplayName());
                root.put("monitor_id", numeric.key.getMonitorId());
                root.put("facility_id", numeric.key.getFacilityid());
                root.put("time", numeric.data.getTime());
                root.put("value", numeric.data.getValue());
                root.put("position", numeric.data.getPosition());

                String url = binder.bind(numeric.key, numeric.data, urlStr);
                String data = root.toString();
                try {
                    send(url, data);
                    lastPosition = numeric;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_monitor(numeric.key.getMonitorId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         * ??
         * 
         */
        @Override
        public TransferStringData transferStrings(Iterable<TransferStringData> strings,
                TrasferCallback<TransferStringData> callback) throws TransferException {
            TransferStringData lastPosition = null;
            for (TransferStringData string : strings) {
                ObjectNode root = JsonNodeFactory.instance.objectNode();
                root.put("target_name", string.key.getTargetName());
                root.put("monitor_id", string.key.getMonitorId());
                root.put("facility_id", string.key.getFacilityId());
                root.put("log_format_id", string.data.getLogformatId());
                root.put("time", string.data.getTime());
                root.put("source", string.data.getValue());

                for (CollectDataTag t : string.data.getTagList()) {
                    root.put(t.getKey(), t.getValue());
                }

                root.put("position", string.data.getDataId());

                String url = binder.bind(string.key, string.data, urlStr);
                String data = root.toString();
                try {
                    send(url, data);
                    lastPosition = string;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_monitor(string.key.getMonitorId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         * ??
         * 
         */
        @Override
        public JobSessionEntity transferJobs(Iterable<JobSessionEntity> sessions,
                TrasferCallback<JobSessionEntity> callback) throws TransferException {
            JobSessionEntity lastPosition = null;
            for (JobSessionEntity session : sessions) {
                ObjectNode sessionNode = JsonNodeFactory.instance.objectNode();
                sessionNode.put("ssession_id", session.getSessionId());
                sessionNode.put("job_id", session.getJobId());
                sessionNode.put("jobunit_id", session.getJobunitId());
                sessionNode.put("schedule_date", session.getScheduleDate());
                sessionNode.put("position", session.getPosition());

                ArrayNode jobArray = sessionNode.putArray("jobs");
                for (JobSessionJobEntity job : session.getJobSessionJobEntities()) {
                    ObjectNode jobNode = jobArray.addObject();
                    jobNode.put("job_id", job.getId().getJobId());
                    jobNode.put("jobunit_id", job.getId().getJobunitId());
                    if (job.getScopeText() != null)
                        jobNode.put("scope_text", job.getScopeText());
                    if (job.getStatus() != null)
                        jobNode.put("status", job.getStatus());
                    if (job.getStartDate() != null)
                        jobNode.put("start_date", job.getStartDate());
                    if (job.getEndDate() != null)
                        jobNode.put("end_date", job.getEndDate());
                    if (job.getEndValue() != null)
                        jobNode.put("end_value", job.getEndValue());
                    if (job.getEndStatus() != null)
                        jobNode.put("end_status", job.getEndStatus());
                    if (job.getResult() != null)
                        jobNode.put("result", job.getResult());
                    if (job.getJobInfoEntity() != null)
                        jobNode.put("job_type", job.getJobInfoEntity().getJobType());

                    if (!job.getJobSessionNodeEntities().isEmpty()) {
                        ArrayNode nodeArray = jobNode.putArray("nodes");
                        for (JobSessionNodeEntity node : job.getJobSessionNodeEntities()) {
                            ObjectNode nodeNode = nodeArray.addObject();
                            nodeNode.put("facility_id", node.getId().getFacilityId());
                            nodeNode.put("node_name", node.getNodeName());
                            nodeNode.put("status", node.getStatus());
                            nodeNode.put("start_date", node.getStartDate());
                            nodeNode.put("end_date", node.getEndDate());
                            nodeNode.put("end_value", node.getEndValue());
                            nodeNode.put("message", node.getMessage());
                            nodeNode.put("result", node.getResult());
                            nodeNode.put("start_date", node.getStartDate());
                            nodeNode.put("startup_time", node.getStartupTime());
                            nodeNode.put("instance_id", node.getInstanceId());
                        }
                    }
                }

                String url = binder.bind(session, urlStr);
                String data = sessionNode.toString();
                try {
                    send(url, data);
                    lastPosition = session;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_session(session.getSessionId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         * ??
         * 
         */
        @Override
        public EventLogEntity transferEvents(Iterable<EventLogEntity> events,
                TrasferCallback<EventLogEntity> callback) throws TransferException {
            EventLogEntity lastPosition = null;
            for (EventLogEntity event : events) {
                ObjectNode eventNode = JsonNodeFactory.instance.objectNode();
                eventNode.put("monitor_id", event.getId().getMonitorId());
                eventNode.put("monitor_detail_id", event.getId().getMonitorDetailId());
                eventNode.put("plugin_id", event.getId().getPluginId());
                eventNode.put("generation_date", event.getGenerationDate());
                eventNode.put("facility_id", event.getId().getFacilityId());
                eventNode.put("scope_text", event.getScopeText());
                eventNode.put("application", event.getApplication());
                eventNode.put("message", event.getMessage());
                eventNode.put("message_org", event.getMessageOrg());
                eventNode.put("priority", event.getPriority());
                eventNode.put("confirm_flg", event.getConfirmFlg());
                eventNode.put("confirm_date", event.getCommentDate());
                eventNode.put("confirm_user", event.getCommentUser());
                eventNode.put("duplication_count", event.getDuplicationCount());
                eventNode.put("output_date", event.getId().getOutputDate());
                eventNode.put("inhibited_flg", event.getInhibitedFlg());
                eventNode.put("comment_date", event.getCommentDate());
                eventNode.put("comment_user", event.getCommentUser());
                eventNode.put("comment", event.getComment());
                eventNode.put("position", event.getPosition());

                String url = binder.bind(event, urlStr);
                String data = eventNode.toString();
                try {
                    send(url, data);
                    lastPosition = event;

                    if (callback != null)
                        callback.onTransferred(lastPosition);
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                    internalError_monitor(event.getId().getMonitorId(), data, e, url);
                    break;
                }
            }
            return lastPosition;
        }

        /*
         *  ID ??
         * 
         */
        @Override
        public String getDestTypeId() {
            return transfer_id;
        }

        /*
         * Fluentd ?????? HttpClient ??
         * ?????????
         * 
         */
        private CloseableHttpClient getHttpClient() {
            if (client == null) {
                client = createHttpClient();
            }
            return client;
        }

        /*
         * Fluentd ?????? HttpClient ??
         * 
         */
        private CloseableHttpClient createHttpClient() {
            String proxyHost = null;
            Integer proxyPort = null;
            CredentialsProvider cledentialProvider = null;
            List<String> ignoreHostList = new ArrayList<>();

            try {
                // Hinemos ???
                proxyHost = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.host", null);
                Long proxyPortLong = HinemosPropertyUtil.getHinemosPropertyNum("hub.fluentd.proxy.port", null);
                if (proxyPortLong != null)
                    proxyPort = proxyPortLong.intValue();
                if (proxyPort == null)
                    proxyPort = 80;
                String proxyUser = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.user", null);
                String proxyPassword = HinemosPropertyUtil.getHinemosPropertyStr("hub.fluentd.proxy.password",
                        null);

                if (proxyHost != null && proxyPort != null) {
                    logger.debug(
                            "initializing fluentd proxy : proxyHost = " + proxyHost + ", port = " + proxyPort);
                    String ignoreHostStr = HinemosPropertyUtil
                            .getHinemosPropertyStr("hub.fluentd.proxy.ignorehosts", null);
                    if (ignoreHostStr != null) {
                        ignoreHostList = Arrays.asList(ignoreHostStr.split(","));
                    }

                    if (proxyUser != null && proxyPassword != null) {
                        cledentialProvider = new BasicCredentialsProvider();
                        cledentialProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                                new UsernamePasswordCredentials(proxyUser, proxyPassword));
                    }
                }
            } catch (Throwable t) {
                logger.warn("invalid proxy configuration.", t);
                proxyHost = null;
                proxyPort = null;
                cledentialProvider = null;
                ignoreHostList = Collections.emptyList();
            }

            List<Header> headers = new ArrayList<>();
            HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(cledentialProvider)
                    .setDefaultHeaders(headers);

            Builder requestBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT);
            if (connectTimeout != null)
                requestBuilder.setConnectTimeout(connectTimeout);
            if (connectTimeout != null)
                requestBuilder.setSocketTimeout(requestTimeout);

            builder.setDefaultRequestConfig(requestBuilder.build());

            if (proxyHost != null) {
                Matcher m = urlPattern.matcher(urlStr);
                if (!m.matches())
                    throw new InternalError(String.format("invalid url(%s)", urlStr));

                m.toMatchResult();

                boolean ignore = false;
                String host = m.group("host");
                for (String ignoreHost : ignoreHostList) {
                    if (ignoreHost.equals(host)) {
                        ignore = true;
                        break;
                    }
                }

                if (!ignore) {
                    HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
                    builder.setProxy(proxy);
                }
            }

            if (keepAlive) {
                headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE));
            } else {
                headers.add(new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
            }
            return builder.build();
        }

        /*
         * ?? URL ???
         * 
         */
        private void send(String url, String data) throws Exception {
            // URL  ?
            Matcher m = urlPattern.matcher(url);
            if (!m.matches())
                throw new InternalError(String.format("invalid url(%s)", urlStr));
            m.toMatchResult();
            String path = m.group("path");
            if (path != null && !path.isEmpty()) {
                String host = m.group("host");
                String port = m.group("port");

                String[] paths = path.split("/");
                for (int i = 1; i < paths.length; ++i) {
                    paths[i] = URLEncoder.encode(paths[i], "utf-8");
                }
                url = "http://" + host + (port == null || port.isEmpty() ? "" : (":" + port));
                for (int i = 1; i < paths.length; ++i) {
                    url += "/" + paths[i];
                }
            }

            HttpPost requestPost = new HttpPost(url);
            requestPost.addHeader("content-type", "application/json");
            requestPost.setEntity(new StringEntity(data, StandardCharsets.UTF_8));

            logger.debug(String.format("send() : request start. url=%s", url));

            int count = 0;
            int maxTryCount = PropertyConstants.hub_transfer_max_try_count.number();

            while (count < maxTryCount) {
                try {
                    long start = HinemosTime.currentTimeMillis();
                    try (CloseableHttpResponse response = getHttpClient().execute(requestPost)) {
                        long responseTime = HinemosTime.currentTimeMillis() - start;
                        logger.debug(String.format("send() : url=%s, responseTime=%d", url, responseTime));

                        int statusCode = response.getStatusLine().getStatusCode();
                        logger.debug(String.format("send() : url=%s, code=%d", url, statusCode));
                        if (statusCode == HttpStatus.SC_OK) {
                            logger.debug(String.format("send() : url=%s, success=%s", url,
                                    response.getStatusLine().toString()));
                            if (logger.isDebugEnabled()) {
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                try (InputStream in = response.getEntity().getContent()) {
                                    byte[] buffer = new byte[BUFF_SIZE];
                                    while (out.size() < BODY_MAX_SIZE) {
                                        int len = in.read(buffer);
                                        if (len < 0) {
                                            break;
                                        }
                                        out.write(buffer, 0, len);
                                    }
                                }
                                String res = new String(out.toByteArray(), "UTF-8");
                                if (!res.isEmpty())
                                    logger.debug(String.format("send() : url=%s, response=%s", url, res));
                            }
                        } else {
                            throw new RuntimeException(
                                    String.format("http status code isn't 200. code=%d, message=%s", statusCode,
                                            response.getStatusLine().toString()));
                        }
                    }

                    logger.debug(String.format("send() : success. url=%s, count=%d", url, count));
                    break;
                } catch (RuntimeException e) {
                    ++count;

                    if (count < maxTryCount) {
                        logger.debug(e.getMessage(), e);
                        logger.debug(String.format(
                                "send() : fail to send, and then wait to retry. url=%s, count=%d", url, count));
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                            logger.debug(e.getMessage());
                        }
                    } else {
                        throw new TransferException(
                                String.format("send() : fail to send. url=%s, retry count=%d, error=\"%s\"",
                                        url, count, e.getMessage()));
                    }
                }
            }
        }

        @Override
        public void close() throws Exception {
            if (client != null)
                client.close();
        }

        private void internalError_session(String sessionId, String data, Exception error, String url) {
            internalError_session(sessionId, data,
                    error.getMessage() == null || error.getMessage().isEmpty()
                            ? error.getClass().getSimpleName()
                            : error.getMessage(),
                    url);
        }

        private void internalError_session(String sessionId, String data, String error, String url) {
            AplLogger.put(PriorityConstant.TYPE_WARNING, HinemosModuleConstant.HUB_TRANSFER,
                    MessageConstant.MESSAGE_HUB_DATA_TRANSFER_FAILED, new String[] { info.getTransferId() },
                    String.format("error=%s%ntransferId=%s%ndestTypeId=%s%nsessionId=%s%ndata=%s%nurl=%s",
                            error, info.getTransferId(), info.getDestTypeId(), sessionId, data, url));
        }

        private void internalError_monitor(String sessionId, String data, Exception error, String url) {
            internalError_monitor(sessionId, data,
                    error.getMessage() == null || error.getMessage().isEmpty()
                            ? error.getClass().getSimpleName()
                            : error.getMessage(),
                    url);
        }

        private void internalError_monitor(String monitorId, String data, String error, String url) {
            AplLogger.put(PriorityConstant.TYPE_WARNING, HinemosModuleConstant.HUB_TRANSFER,
                    MessageConstant.MESSAGE_HUB_DATA_TRANSFER_FAILED, new String[] { info.getTransferId() },
                    String.format("error=%s%ntransferId=%s%ndestTypeId=%s%nmonitorId=%s%ndata=%s%nurl=%s",
                            error, info.getTransferId(), info.getDestTypeId(), monitorId, data, url));
        }
    };
}

From source file:stc.app.bean.lang.ReflectionToStringBuilder.java

/**
 * <p>/*www. j  av  a  2 s . c om*/
 * Appends the fields and values defined by the given object of the given Class.
 * </p>
 * 
 * <p>
 * If a cycle is detected as an object is &quot;toString()'ed&quot;, such an object is rendered as
 * if <code>Object.toString()</code> had been called and not implemented by the object.
 * </p>
 * 
 * @param clazz The class of object parameter
 */
protected void appendFieldsIn(Class clazz) {
    if (clazz.isArray()) {
        this.reflectionAppendArray(this.getObject());
        return;
    }
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        String fieldName = field.getName();
        if (this.accept(field)) {
            try {
                // Warning: Field.get(Object) creates wrappers objects
                // for primitive types.
                Object fieldValue = this.getValue(field);
                this.append(fieldName, fieldValue);
            } catch (IllegalAccessException ex) {
                // this can't happen. Would get a Security exception
                // instead
                // throw a runtime exception in case the impossible
                // happens.
                throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
            }
        }
    }
}