Example usage for java.util.logging Level FINER

List of usage examples for java.util.logging Level FINER

Introduction

In this page you can find the example usage for java.util.logging Level FINER.

Prototype

Level FINER

To view the source code for java.util.logging Level FINER.

Click Source Link

Document

FINER indicates a fairly detailed tracing message.

Usage

From source file:org.b3log.latke.cache.PageCaches.java

/**
 * Synchronizes the {@linkplain #KEYS keys} collection and cached page
 * objects.//from  w ww.  j ava2 s .c o  m
 */
private static void syncKeys() {
    @SuppressWarnings("unchecked")
    final Iterator<String> iterator = KEYS.iterator();
    final Set<String> toRemove = new HashSet<String>();

    while (iterator.hasNext()) {
        final String key = iterator.next();

        if (!CACHE.contains(key)) {
            toRemove.add(key);
            // iterator.remove() will also throw ConcurrentModificationException on GAE
        }
    }

    if (!toRemove.isEmpty()) {
        KEYS.removeAll(toRemove);
        LOGGER.log(Level.FINER, "Removed page cache keys[{0}] for sync", toRemove);
    }
}

From source file:org.geoserver.jdbcconfig.internal.ConfigDatabase.java

public <T extends Info> CloseableIterator<T> query(final Class<T> of, final Filter filter,
        @Nullable Integer offset, @Nullable Integer limit, @Nullable SortBy... sortOrder) {

    checkNotNull(of);/*from   ww w. jav a  2  s .c om*/
    checkNotNull(filter);
    checkArgument(offset == null || offset.intValue() >= 0);
    checkArgument(limit == null || limit.intValue() >= 0);

    QueryBuilder<T> sqlBuilder = QueryBuilder.forIds(dialect, of, dbMappings).filter(filter).offset(offset)
            .limit(limit).sortOrder(sortOrder);

    final StringBuilder sql = sqlBuilder.build();
    final Map<String, Object> namedParameters = sqlBuilder.getNamedParameters();
    final Filter unsupportedFilter = sqlBuilder.getUnsupportedFilter();
    final boolean fullySupported = Filter.INCLUDE.equals(unsupportedFilter);

    if (LOGGER.isLoggable(Level.FINER)) {
        LOGGER.finer("Original filter: " + filter);
        LOGGER.finer("Supported filter: " + sqlBuilder.getSupportedFilter());
        LOGGER.finer("Unsupported filter: " + sqlBuilder.getUnsupportedFilter());
    }
    logStatement(sql, namedParameters);

    Stopwatch sw = Stopwatch.createStarted();
    // the oracle offset/limit implementation returns a two column result set
    // with rownum in the 2nd - queryForList will throw an exception
    List<String> ids = template.query(sql.toString(), namedParameters, new RowMapper<String>() {
        @Override
        public String mapRow(ResultSet rs, int rowNum) throws SQLException {
            return rs.getString(1);
        }
    });
    sw.stop();
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(Joiner.on("").join("query returned ", ids.size(), " records in ", sw.toString()));
    }

    List<T> lazyTransformed = Lists.transform(ids, new Function<String, T>() {
        @Nullable
        @Override
        public T apply(String id) {
            return getById(id, of);
        }
    });

    CloseableIterator<T> result;
    Iterator<T> iterator = Iterators.filter(lazyTransformed.iterator(),
            com.google.common.base.Predicates.notNull());

    if (fullySupported) {
        result = new CloseableIteratorAdapter<T>(iterator);
    } else {
        // Apply the filter
        result = CloseableIteratorAdapter.filter(iterator, filter);
        // The offset and limit should not have been applied as part of the query
        assert (!sqlBuilder.isOffsetLimitApplied());
        // Apply offset and limits after filtering
        result = applyOffsetLimit(result, offset, limit);
    }

    return result;
}

From source file:de.theit.hudson.crowd.CrowdSecurityRealm.java

/**
 * {@inheritDoc}/*from  ww w  . j  av  a 2  s .  com*/
 * 
 * @see hudson.security.SecurityRealm#loadGroupByGroupname(java.lang.String)
 */
@Override
public GroupDetails loadGroupByGroupname(String groupname)
        throws UsernameNotFoundException, DataAccessException {

    try {
        // load the user object from the remote Crowd server
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("Trying to load group: " + groupname);
        }
        final Group crowdGroup = this.configuration.crowdClient.getGroup(groupname);

        return new GroupDetails() {
            @Override
            public String getName() {
                return crowdGroup.getName();
            }
        };
    } catch (GroupNotFoundException ex) {
        if (LOG.isLoggable(Level.INFO)) {
            LOG.info(groupNotFound(groupname));
        }
        throw new DataRetrievalFailureException(groupNotFound(groupname), ex);
    } catch (ApplicationPermissionException ex) {
        LOG.warning(applicationPermission());
        throw new DataRetrievalFailureException(applicationPermission(), ex);
    } catch (InvalidAuthenticationException ex) {
        LOG.warning(invalidAuthentication());
        throw new DataRetrievalFailureException(invalidAuthentication(), ex);
    } catch (OperationFailedException ex) {
        LOG.log(Level.SEVERE, operationFailed(), ex);
        throw new DataRetrievalFailureException(operationFailed(), ex);
    }
}

From source file:com.granule.json.utils.internal.JSONObject.java

/**
 * Internal method to escape special attribute name characters, to handle things like name spaces.
 * @param str The string to escape the characters in.
 *//* w  ww  .  j a v a2  s. c o m*/
private String escapeStringSpecialCharacters(String str) {
    if (logger.isLoggable(Level.FINER))
        logger.exiting(className, "escapeStringSpecialCharacters(String)");

    if (str != null) {
        StringBuffer strBuf = new StringBuffer("");

        for (int i = 0; i < str.length(); i++) {
            char strChar = str.charAt(i);

            switch (strChar) {
            case '"': {
                strBuf.append("\\\"");
                break;
            }
            case '\t': {
                strBuf.append("\\t");
                break;
            }
            case '\b': {
                strBuf.append("\\b");
                break;
            }
            case '\\': {
                strBuf.append("\\\\");
                break;
            }
            case '\f': {
                strBuf.append("\\f");
                break;
            }
            case '\r': {
                strBuf.append("\\r");
                break;
            }
            case '/': {
                strBuf.append("\\/");
                break;
            }
            default: {
                if ((strChar >= 32) && (strChar <= 126)) {
                    strBuf.append(strChar);
                } else {
                    strBuf.append("\\u");
                    StringBuffer sb = new StringBuffer(Integer.toHexString(strChar));
                    while (sb.length() < 4) {
                        sb.insert(0, '0');
                    }
                    strBuf.append(sb.toString());
                }

                break;
            }
            }
        }
        str = strBuf.toString();
    }
    if (logger.isLoggable(Level.FINER))
        logger.exiting(className, "escapeStringSpecialCharacters(String)");
    return str;
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    final String sourceMethod = "doGet"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { req, resp });
        log.finer("Request URL=" + req.getRequestURI()); //$NON-NLS-1$
    }/*from  w  w  w .  j a va 2s .c  om*/

    if (isShuttingDown) {
        // Server has been shut-down, or is in the process of shutting down.
        resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        if (isTraceLogging) {
            log.finer("Processing request after server shutdown.  Returning SC_SERVICE_UNAVAILABLE"); //$NON-NLS-1$
            log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
        }
        return;
    }
    resp.addHeader("Server", "JavaScript Aggregator"); //$NON-NLS-1$ //$NON-NLS-2$
    String pathInfo = req.getPathInfo();
    if (pathInfo == null) {
        processAggregatorRequest(req, resp);
    } else {
        boolean processed = false;
        // search resource paths to see if we should treat as aggregator request or resource request
        for (Map.Entry<String, IResource> entry : resourcePaths.entrySet()) {
            String path = entry.getKey();
            if (path.equals(pathInfo) && entry.getValue() == null) {
                processAggregatorRequest(req, resp);
                processed = true;
                break;
            }
            if (pathInfo.startsWith(path)) {
                if ((path.length() == pathInfo.length() || pathInfo.charAt(path.length()) == '/')
                        && entry.getValue() != null) {
                    String resPath = path.length() == pathInfo.length() ? "" //$NON-NLS-1$
                            : pathInfo.substring(path.length() + 1);
                    IResource res = entry.getValue();
                    processResourceRequest(req, resp, res, resPath);
                    processed = true;
                    break;
                }
            }
        }
        if (!processed) {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   ww  w.  j  a  v  a 2 s .  co m
        printRequest(request);

        sessionId.set(request.getSession().getId());
        String dataSource = request.getParameter("_dataSource");

        // List grid export
        if ("export".equals(request.getParameter("_operationType"))) {
            exportData(dataSource, response);
            return;
        }

        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "-1");

        if ("getMenu".equals(dataSource)) {
            response.getWriter().write(listServices());
        } else if ("userInfo".equals(dataSource)) {
            ServiceContext ctx = ServiceContextStore.get();
            PrintWriter out = response.getWriter();
            out.print(ctx.getUserId());
            for (String role : ctx.getRoles()) {
                out.print(",");
                out.print(role);
            }
            out.flush();
        } else if ("createDataSource".equals(dataSource)) {
            HashMap<String, String> classToServiceName = new HashMap<String, String>();
            for (ServiceDescription serviceDesc : getServiceDescription()) {
                log.log(Level.INFO, "Service translation from {0} to {1}",
                        new Object[] { serviceDesc.getExpectedClass().getName(), serviceDesc.getName() });
                classToServiceName.put(serviceDesc.getExpectedClass().getName(), serviceDesc.getName());
            }
            GuiDataSourceService dataSourceService = getGuiDataSourceService();
            dataSourceService.setServiceMapping(ServiceContextStore.get(), classToServiceName);

            StringBuilder output = new StringBuilder();
            output.append("dataSources###");
            List<GuiDataSource> allDataSources = dataSourceService.findAll(ServiceContextStore.get());
            for (GuiDataSource dataSourceDef : allDataSources) {
                ds2Ref.put(dataSourceDef.getBaseClass(), dataSourceDef.getTitleField());
                dataSourceDef.setBaseClass(null);
                log.log(Level.INFO, "Entity def for {0}", dataSourceDef.getXxxID());
                dataSourceDef.setDataURL(getServiceUrl(request));

                output.append("$wnd.isc.RestDataSource.create(")
                        .append(mapObjToOutput(dataSourceDef, 6, new Stack<Object>(), true, false))
                        .append(");\n");
            }

            ListSettingsService listInstance = (ListSettingsService) findService(LIST_SETTINGS_SERVICE)
                    .getInstance();
            List<ListSettings> guiList = listInstance.findUserSettings(ServiceContextStore.get());
            for (ListSettings listSettings : guiList) {
                output.append("\n###").append(listSettings.getListID()).append("###")
                        .append(listSettings.getSettings());
            }

            log.log(Level.INFO, "Create datasource {0}", output.toString());
            response.getWriter().append(output);

        } else if (findService(dataSource) != null) {
            ServiceDescription serviceDesc = findService(dataSource);
            String operationType = request.getParameter("_operationType");
            String methodName = request.getParameter("_operationId");

            if (methodName != null && !methodName.endsWith("_fetch")) {
                log.log(Level.FINER, "Executing method '" + dataSource + "." + methodName + "'");
                MethodDescription methodDescription = serviceDesc.getOtherMethods().get(methodName);
                if (methodDescription != null) {
                    Object valObj = null;
                    HashMap<String, Object> jsData = unifyRequest(request);
                    Object[] params = prepareMethodParam(jsData, true, methodDescription.parameterNames,
                            methodDescription.method.getParameterTypes());
                    // Resolve "ids" for iterations
                    int iterate = -1;
                    if (jsData.get("ids") != null) {
                        Class<?>[] paramTypes = methodDescription.method.getParameterTypes();
                        for (int i = 0; i < paramTypes.length; i++) {
                            if (Long.class.equals(paramTypes[i]) || paramTypes[i].equals(Long.TYPE)
                                    && methodDescription.parameterNames[i].equals("id") && params[i] == null) {
                                iterate = i;
                                break;
                            } else if (Collection.class.isAssignableFrom(paramTypes[i])
                                    && methodDescription.parameterNames[i].equals("ids") && params[i] == null) {
                                List<Long> longList = new ArrayList<Long>();
                                String ids = (String) jsData.get("ids");
                                String[] idSplit = ids.split(",");
                                for (int k = 0; k < idSplit.length; k++) {
                                    if (idSplit[i].length() > 0) {
                                        longList.add(Long.parseLong(idSplit[i]));
                                    }
                                }
                                params[i] = longList;
                                break;
                            }
                        }
                    }

                    if (iterate != -1) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        String ids = (String) jsData.get("ids");
                        String[] idSplit = ids.split(",");
                        ArrayList<Object> listResult = new ArrayList<Object>();
                        valObj = listResult;
                        for (int i = 0; i < idSplit.length; i++) {
                            if (idSplit[i].length() > 0) {
                                params[iterate] = Long.parseLong(idSplit[i]);
                                Object subValObj = methodDescription.method.invoke(serviceDesc.getInstance(),
                                        params);
                                if (subValObj != null && subValObj instanceof Collection) {
                                    listResult.addAll((Collection) subValObj);
                                } else if (subValObj != null) {
                                    listResult.add(subValObj);
                                }
                            }
                        }
                        log.info("Return value: " + valObj);
                    } else if (params != null) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        valObj = methodDescription.method.invoke(serviceDesc.getInstance(), params);
                        log.info("Return value: " + valObj);
                    }
                    Collection<Object> collResult;
                    PagedResult<?> pagedResult = null;
                    if (valObj == null) {
                        collResult = new ArrayList<Object>();
                        for (int i = 0; i < params.length; i++) {
                            if (params[i] != null
                                    && params[i].getClass().equals(serviceDesc.getExpectedClass())) {
                                collResult.add(params[i]);
                                break;
                            }
                        }
                    } else if (valObj instanceof Collection) {
                        collResult = (Collection) valObj;
                    } else if (valObj instanceof PagedResult) {
                        collResult = null;
                        pagedResult = (PagedResult) valObj;
                    } else {
                        ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                        serviceResultArray.add(valObj);
                        collResult = serviceResultArray;
                    }
                    if (collResult != null) {
                        sendResponse(response.getWriter(), 0, collResult.size(), collResult);
                    } else if (pagedResult != null) {
                        sendResponse(response.getWriter(), pagedResult);
                    }
                } else {
                    throw new IllegalArgumentException(
                            "No " + methodName + " operation available on " + dataSource);
                }
            } else if (operationType == null) {
                throw makeApplicationException("Unsupported operation", "ERR9001", "NULL");
            } else if (operationType.equals("fetch") && request.getParameter("id") != null) {
                Long idVal = Long.parseLong(request.getParameter("id"));
                if (serviceDesc.getFindById() != null) {
                    Object serviceResult = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), idVal);
                    ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                    serviceResultArray.add(serviceResult);

                    sendResponse(response.getWriter(), 0, 1, serviceResultArray);
                } else {
                    throw new IllegalArgumentException("No fetch operation available");
                }
            } else if (operationType.equals("fetch")) {
                List<?> serviceResult;
                PagedResult<?> pagedServiceResult = null;

                String sRow = request.getParameter("_startRow");
                int startRow = sRow == null ? 0 : Integer.parseInt(sRow);
                String eRow = request.getParameter("_endRow");
                int endRow = eRow == null ? 0 : Integer.parseInt(eRow);

                ArrayList<String> queryParams = new ArrayList();
                Enumeration pNames = request.getParameterNames();
                while (pNames.hasMoreElements()) {
                    String paramName = (String) pNames.nextElement();
                    if (!paramName.startsWith("_")) {
                        queryParams.add(paramName);
                    } else if ("_sortBy".equals(paramName)) {
                        queryParams.add("sortBy");
                    }
                }

                if (queryParams.size() > 0) {
                    Collection<MethodDescription> methods = serviceDesc.getOtherMethods().values();
                    MethodDescription matchedMethod = null;
                    int matchLength = 1000;
                    for (MethodDescription method : methods) {
                        String[] methodParamNames = method.parameterNames;
                        if (methodParamNames != null && methodParamNames.length >= queryParams.size()
                                && (List.class.isAssignableFrom(method.method.getReturnType())
                                        || PagedResult.class.isAssignableFrom(method.method.getReturnType()))) {
                            boolean matchParam = false;
                            for (String queryParam : queryParams) {
                                matchParam = false;
                                for (String methodParamName : methodParamNames) {
                                    if (queryParam.equals(methodParamName)) {
                                        matchParam = true;
                                        break;
                                    }
                                }
                                if (!matchParam) {
                                    break;
                                }
                            }
                            if (matchParam && method.parameterNames.length < matchLength) {
                                matchedMethod = method;
                                matchLength = method.parameterNames.length;
                            }
                        }
                    }

                    Object[] params = null;
                    if (matchedMethod != null) {
                        HashMap<String, Object> jsData = unifyRequest(request);
                        params = prepareMethodParam(jsData, true, matchedMethod.parameterNames,
                                matchedMethod.method.getParameterTypes());
                    } else {
                        List<ConditionalCriteria> conditions = new ArrayList();
                        for (MethodDescription method : methods) {
                            if (method.getMethodName().equals("findByCondition")) {
                                Class<?>[] parameterTypes = method.method.getParameterTypes();
                                if (List.class.isAssignableFrom(parameterTypes[0])) {
                                    params = new Object[] { conditions };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 3
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])
                                        && PagingParameter.class.isAssignableFrom(parameterTypes[2])) {
                                    endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                                    PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow,
                                            LOOK_AHEAD);
                                    params = new Object[] { ServiceContextStore.get(), conditions,
                                            pagingParam };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 2
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])) {
                                    params = new Object[] { ServiceContextStore.get(), conditions };
                                    matchedMethod = method;
                                    break;
                                }
                            }
                        }
                        if (matchedMethod != null) {
                            for (String queryParam : queryParams) {
                                LeafProperty<?> queryProp = new LeafProperty(queryParam, ScServlet.class);
                                String matchStyle = request.getParameter("_textMatchStyle");
                                String queryValue = request.getParameter(queryParam);
                                if (queryParam.equals("sortBy")) {
                                    queryValue = normalizeAssoc(serviceDesc, request.getParameter("_sortBy"));
                                    if (queryValue.startsWith("+")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    } else if (queryValue.startsWith("-")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderDesc(sortProp));
                                    } else {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue,
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    }
                                } else if (queryValue.indexOf('%') != -1) {
                                    conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                            request.getParameter(queryParam) + "%"));
                                } else {
                                    String[] queryParamSplit = queryParam.split("\\.");
                                    Class watchClass = serviceDesc.getExpectedClass();
                                    Object otherEqVal = null;
                                    boolean isString = false;
                                    for (String queryParamPart : queryParamSplit) {
                                        try {
                                            Method method = watchClass.getMethod(
                                                    makeGetMethodName(queryParamPart), (Class[]) null);
                                            watchClass = method.getReturnType();
                                            if (Collection.class.isAssignableFrom(watchClass)) {
                                                // TODO look deeper into class of collection
                                                break;
                                            } else if (Enum.class.isAssignableFrom(watchClass)) {
                                                otherEqVal = Enum.valueOf(watchClass, queryValue);
                                                break;
                                            } else if (String.class.equals(watchClass)) {
                                                isString = true;
                                                break;
                                            } else if (Long.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Long.parseLong(queryValue);
                                                break;
                                            } else if (Integer.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Integer.parseInt(queryValue);
                                                break;
                                            } else if (Double.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Double.parseDouble(queryValue);
                                                break;
                                            } else if (Date.class.equals(watchClass)) {
                                                otherEqVal = dateFormat.parse(queryValue);
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && "null".equals(queryValue)) {
                                                otherEqVal = "null";
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && findServiceByClassName(watchClass.getName())
                                                            .getFindById() != null) {
                                                ServiceDescription srvc = findServiceByClassName(
                                                        watchClass.getName());
                                                otherEqVal = srvc.getFindById().invoke(srvc.getInstance(),
                                                        ServiceContextStore.get(), Long.parseLong(queryValue));
                                            }
                                        } catch (NoSuchMethodException nsme) {
                                            // Ignore error, isString will stay false
                                            break;
                                        }
                                    }
                                    boolean isLike = "substring".equals(matchStyle)
                                            || "startsWith".equals(matchStyle);
                                    if ("null".equals(otherEqVal)) {
                                        conditions.add(ConditionalCriteria.isNull(queryProp));
                                    } else if (otherEqVal instanceof Date) {
                                        DateMidnight start = (new DateTime(otherEqVal)).toDateMidnight();
                                        DateMidnight stop = start.plusDays(1);
                                        conditions.add(ConditionalCriteria.between(queryProp, start.toDate(),
                                                stop.toDate()));
                                    } else if (isString && otherEqVal != null && isLike) {
                                        conditions.add(ConditionalCriteria.like(queryProp, otherEqVal));
                                    } else if (isString && "substring".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                "%" + request.getParameter(queryParam) + "%"));
                                    } else if (isString && "startsWith".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                request.getParameter(queryParam) + "%"));
                                    } else if (otherEqVal != null) {
                                        conditions.add(ConditionalCriteria.equal(queryProp, otherEqVal));
                                    } else {
                                        conditions.add(ConditionalCriteria.equal(queryProp, queryValue));
                                    }
                                }
                            }
                        }
                    }

                    if (matchedMethod != null && params != null) {
                        for (int j = 0; j < params.length; j++) {
                            log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                        }
                        if (matchedMethod.method.getReturnType().equals(PagedResult.class)) {
                            serviceResult = null;
                            pagedServiceResult = (PagedResult) matchedMethod.method
                                    .invoke(serviceDesc.getInstance(), params);
                        } else {
                            serviceResult = (List<?>) matchedMethod.method.invoke(serviceDesc.getInstance(),
                                    params);
                        }
                    } else {
                        throw makeApplicationException("You can''t filter with such condition.", "ERR9015",
                                (Serializable[]) null);
                    }
                } else if (queryParams.size() == 0 && serviceDesc.getFindAll() != null) {
                    Class<?>[] paramTypes = serviceDesc.getFindAll().getParameterTypes();
                    if (paramTypes.length == 2 && paramTypes[0].equals(ServiceContext.class)
                            && paramTypes[1].equals(PagingParameter.class)
                            && serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) {
                        endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                        PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD);
                        pagedServiceResult = (PagedResult<?>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get(), pagingParam);
                        serviceResult = null;
                    } else if (paramTypes.length == 1 && paramTypes[0].equals(ServiceContext.class)) {
                        serviceResult = (List<? extends Object>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get());
                    } else {
                        serviceResult = null;
                    }
                } else {
                    throw new ApplicationException("", "No fetch operation available");
                }

                if (pagedServiceResult != null) {
                    sendResponse(response.getWriter(), pagedServiceResult);
                } else {
                    int resultSize = serviceResult == null ? 0 : serviceResult.size();
                    endRow = (endRow == 0 ? resultSize : endRow);
                    sendResponse(response.getWriter(), startRow, endRow < resultSize ? endRow : resultSize,
                            serviceResult);
                }
            } else if (operationType.equals("update") && request.getParameter("id") != null) {
                Object val = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), Long.parseLong(request.getParameter("id")));
                HashMap<String, Object> reqData = unifyRequest(request);
                mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), val);
                ArrayList<Object> list = new ArrayList<Object>();
                list.add(val);
                sendResponse(response.getWriter(), 0, 1, list);
            } else if ((operationType.equals("add") || operationType.equals("update"))
                    && request.getParameter("id") == null) {
                HashMap<String, Object> reqData = unifyRequest(request);
                Object val = makeNewInstance(serviceDesc.getExpectedClass(), reqData);
                if (val != null) {
                    mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                    serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), val);
                    ArrayList<Object> list = new ArrayList<Object>();
                    list.add(val);
                    sendResponse(response.getWriter(), 0, 1, list);
                } else {
                    throw makeApplicationException("Can't create new instance", "ERR9003",
                            serviceDesc.getExpectedClass().getName());
                }
            } else {
                throw makeApplicationException("Unsupported operation", "ERR9001", operationType);
            }
        } else {
            throw makeApplicationException("Wrong datasource name", "ERR9002", dataSource);
        }
    } catch (Throwable ex) {
        // Find most relevant exception in embedded exceptions
        ApplicationException appException = null;
        Throwable relevantException = ex;
        while (ex != null) {
            relevantException = ex;
            if (ex instanceof ApplicationException) {
                appException = (ApplicationException) ex;
                break;
            }
            if (ex instanceof ValidationException) {
                break;
            }

            ex = ex.getCause();
        }

        // Prepare message
        String msg = null;
        if (appException != null) {
            msg = translate(appException.getMessage());
            Serializable[] msgParams = appException.getMessageParameters();
            if (msgParams != null) {
                Object[] params = new Object[msgParams.length];
                for (int i = 0; i < msgParams.length; i++) {
                    if (msgParams[i] instanceof Translatable) {
                        params[i] = translate(((Translatable) msgParams[i]).getContent());
                    } else {
                        params[i] = msgParams[i];
                    }
                }
                msg = MessageFormat.format(msg, params);
            }
        } else if (relevantException instanceof ValidationException) {
            StringBuilder b = new StringBuilder();
            for (InvalidValue iv : ((ValidationException) relevantException).getInvalidValues()) {
                b.append("<b>").append(translate(iv.getPropertyName()) + ":</b> " + iv.getMessage())
                        .append("<br/>");
            }
            msg = b.toString();
        } else {
            msg = translate("ERR9000");
            msg = MessageFormat.format(msg,
                    new Object[] { relevantException.getClass().getName(), relevantException.getMessage() });
        }

        // Print stack trace
        log.log(Level.WARNING, "Relevant exception", relevantException);

        if (msg != null) {
            log.log(Level.WARNING, "SENDING BACK ERROR '" + msg + "'");
            response.getWriter()
                    .write("{response:{ status:-1, data:\""
                            + msg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"")
                            + "\", startRow:0, endRow:0, totalRows:0}}");
        }
        response.flushBuffer();
        // response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        throw new ServletException(msg);
    }
    response.flushBuffer();
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

private void execute(Match match, HttpRequestBase method, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    LOG.log(Level.FINE, "Requesting {0}", method.getURI());

    HttpClient client = this.getClient();
    HttpResponse response = client.execute(method);

    for (Header h : response.getHeaders("Set-Cookie")) {
        String line = parseCookie(h.getValue());
        LOG.log(Level.FINER, method.getURI() + "{0}", new Object[] { line });

        if (line != null) {
            LOG.log(Level.INFO, "Bonding session {0} to host {1}",
                    new Object[] { line, match.destination.hostAndPort() });

            try {
                resolver.bond(line, match);
            } catch (ExecutionException ex) {
                Logger.getLogger(ProxyServlet.class.getName()).log(Level.SEVERE, null, ex);
                this.releaseClient(client);

                throw new ServletException(ex);
            }//from  www. ja v  a2  s.co m
        }
    }

    int rc = response.getStatusLine().getStatusCode();

    if ((rc >= HttpServletResponse.SC_MULTIPLE_CHOICES) && (rc < HttpServletResponse.SC_NOT_MODIFIED)) {
        String location = response.getFirstHeader(HEADER_LOCATION).getValue();

        if (location == null) {
            throw new ServletException("Recieved status code: " + rc + " but no " + HEADER_LOCATION
                    + " header was found in the response");
        }

        String hostname = req.getServerName();

        if ((req.getServerPort() != 80) && (req.getServerPort() != 443)) {
            hostname += (":" + req.getServerPort());
        }

        hostname += req.getContextPath();

        String replaced = location.replace(match.destination.hostAndPort() + match.path.getDestination(),
                hostname);

        if (replaced.startsWith("http://")) {
            replaced = replaced.replace("http:", req.getScheme() + ":");
        }

        resp.sendRedirect(replaced);
        this.releaseClient(client);

        return;
    } else if (rc == HttpServletResponse.SC_NOT_MODIFIED) {
        resp.setIntHeader(HEADER_CONTENT_LENTH, 0);
        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        this.releaseClient(client);

        return;
    }

    resp.setStatus(rc);

    Header[] headerArrayResponse = response.getAllHeaders();

    for (Header header : headerArrayResponse) {
        resp.setHeader(header.getName(), header.getValue());
    }

    if (response.getEntity() != null) {
        resp.setContentLength((int) response.getEntity().getContentLength());

        response.getEntity().writeTo(resp.getOutputStream());
    }

    this.releaseClient(client);

    LOG.finer("Done.");
}

From source file:com.google.enterprise.connector.salesforce.BaseTraversalManager.java

/**
 * Looks into the storetype and populates any the internal doclist with
 * items in the store that was crawled by quartz after the checkpoint date
 * /*w w  w.  j  a  v  a2s.  c o  m*/
 * @param checkpoint
 *            the checkpoint file the traversal manager should resume from
 */

private void getDocListAfter(String checkpoint) {
    logger.log(Level.FINER,
            "[" + connector.getInstanceName() + "]" + " Traversal manager requesting docs after " + checkpoint);
    DocListEntry dr = store.getDocsImmediatelyAfter(checkpoint);
    if (dr != null)
        docListIndex.add(dr);
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to take an XML file and return a String of the JSON format.  
 * //from   w ww . jav a  2  s  . c om
 * @param xmlFile The XML file to transform to JSON.
 * @param verbose Boolean flag denoting whther or not to write the JSON in verbose (formatted), or compact form (no whitespace)
 * @return A string of the JSON representation of the XML file
 * 
 * @throws SAXException Thrown if an error occurs during parse.
 * @throws IOException Thrown if an IOError occurs.
 */
public static String toJson(File xmlFile, boolean verbose) throws SAXException, IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, boolean)");
    }

    FileInputStream fis = new FileInputStream(xmlFile);
    String result = null;

    result = toJson(fis, verbose);
    fis.close();

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, boolean)");
    }

    return result;
}

From source file:edu.emory.cci.aiw.i2b2etl.dest.I2b2QueryResultsHandler.java

/**
 * Creates a new query results handler that will use the provided
 * configuration file. This constructor, through the
 * <code>inferPropositionIdsNeeded</code> parameter, lets you control
 * whether proposition ids to be returned from the Protempa processing run
 * should be inferred from the i2b2 configuration file.
 *
 * @param confXML an i2b2 query results handler configuration file. Cannot
 * be <code>null</code>./* www .  j  a  v a2 s . c  o  m*/
 * @param inferPropositionIdsNeeded <code>true</code> if proposition ids to
 * be returned from the Protempa processing run should include all of those
 * specified in the i2b2 configuration file, <code>false</code> if the
 * proposition ids returned should be only those specified in the Protempa
 * {@link Query}.
 * @param dataInsertMode whether to truncate existing data or append to it
 */
I2b2QueryResultsHandler(Query query, DataSource dataSource, KnowledgeSource knowledgeSource,
        Configuration configuration, List<? extends ProtempaEventListener> eventListeners)
        throws QueryResultsHandlerInitException {
    if (dataSource == null) {
        throw new IllegalArgumentException("dataSource cannot be null");
    }
    if (knowledgeSource == null) {
        throw new IllegalArgumentException("knowledgeSource cannot be null");
    }
    Logger logger = I2b2ETLUtil.logger();
    this.query = query;
    this.knowledgeSource = knowledgeSource;
    this.configuration = configuration;
    logger.log(Level.FINE, String.format("Using configuration: %s", this.configuration.getName()));
    logger.log(Level.FINER, "STEP: read conf.xml");
    this.settings = this.configuration.getSettings();

    this.data = this.configuration.getData();
    this.conceptsSection = this.configuration.getConcepts();
    this.database = this.configuration.getDatabase();
    DatabaseSpec dataSchemaSpec = this.database.getDataSpec();
    if (dataSchemaSpec != null) {
        this.dataConnectionSpec = dataSchemaSpec.toConnectionSpec();
    } else {
        this.dataConnectionSpec = null;
    }

    DatabaseSpec metadataSchemaSpec = this.database.getMetadataSpec();
    if (metadataSchemaSpec != null) {
        this.metadataConnectionSpec = metadataSchemaSpec.toConnectionSpec();
    } else {
        this.metadataConnectionSpec = null;
    }

    this.providerFullNameSpec = this.data.get(this.settings.getProviderFullName());
    this.providerFirstNameSpec = this.data.get(this.settings.getProviderFirstName());
    this.providerMiddleNameSpec = this.data.get(this.settings.getProviderMiddleName());
    this.providerLastNameSpec = this.data.get(this.settings.getProviderLastName());
    this.visitPropId = this.settings.getVisitDimension();

    RemoveMethod removeMethod = this.settings.getDataRemoveMethod();
    if (removeMethod != null) {
        this.dataRemoveMethod = removeMethod;
    } else {
        this.dataRemoveMethod = RemoveMethod.TRUNCATE;
    }
    RemoveMethod metaRemoveMethod2 = this.settings.getMetaRemoveMethod();
    if (metaRemoveMethod2 != null) {
        this.metaRemoveMethod = metaRemoveMethod2;
    } else {
        this.metaRemoveMethod = RemoveMethod.TRUNCATE;
    }

    DataSourceBackend[] dsBackends = dataSource.getBackends();
    this.dataSourceBackendIds = new HashSet<>();
    for (int i = 0; i < dsBackends.length; i++) {
        String id = dsBackends[i].getId();
        if (id != null) {
            this.dataSourceBackendIds.add(id);
        }
    }
    String sourceSystemCd = this.settings.getSourceSystemCode();
    if (sourceSystemCd != null) {
        this.qrhId = sourceSystemCd;
    } else {
        this.qrhId = I2B2QueryResultsHandlerSourceId.getInstance().getStringRepresentation();
    }
    this.dataSourceBackendIds.add(this.qrhId);

    KnowledgeSourceBackend[] ksBackends = knowledgeSource.getBackends();
    this.knowledgeSourceBackendIds = new HashSet<>();
    for (int i = 0; i < ksBackends.length; i++) {
        String id = ksBackends[i].getId();
        if (id != null) {
            this.knowledgeSourceBackendIds.add(id);
        }
    }
    this.knowledgeSourceBackendIds.add(this.qrhId);

    this.eventListeners = eventListeners;
}