Example usage for java.lang Enum valueOf

List of usage examples for java.lang Enum valueOf

Introduction

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

Prototype

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

Source Link

Document

Returns the enum constant of the specified enum type with the specified name.

Usage

From source file:com.alliander.osgp.webdevicesimulator.service.OslpChannelHandler.java

private Message createGetConfigurationResponse(final Device device) {
    final DaliConfiguration.Builder daliConfiguration = DaliConfiguration.newBuilder()
            .addAddressMap(IndexAddressMap.newBuilder().setIndex(ByteString.copyFrom(new byte[] { 1 }))
                    .setAddress(ByteString.copyFrom(new byte[] { 1 })).setRelayType(RelayType.RT_NOT_SET))
            .setNumberOfLights(ByteString.copyFrom(new byte[] { 1 }));

    final Oslp.GetConfigurationResponse.Builder configuration = Oslp.GetConfigurationResponse.newBuilder();
    try {/*from   w  ww  .  j  a  v a  2s. c om*/
        configuration.setStatus(Oslp.Status.OK)
                .setPreferredLinkType(Enum.valueOf(Oslp.LinkType.class, device.getPreferredLinkType().name()))
                .setLightType(Enum.valueOf(Oslp.LightType.class, device.getLightType().name()))
                .setShortTermHistoryIntervalMinutes(15);

        if (device.getProtocol().equals(ProtocolType.OSLP.toString())) {
            // AME devices
            configuration.setMeterType(MeterType.P1);
            configuration.setLongTermHistoryIntervalType(LongTermIntervalType.DAYS);
            configuration.setLongTermHistoryInterval(1);
        } else {
            // ELSTER devices
            configuration.setMeterType(MeterType.MT_NOT_SET);
            configuration.setLongTermHistoryIntervalType(LongTermIntervalType.LT_INT_NOT_SET);
            configuration.setLongTermHistoryInterval(1);
            configuration.setTimeSyncFrequency(86400);
            configuration.setDeviceFixIpValue(
                    ByteString.copyFrom(InetAddress.getByName("192.168.0.100").getAddress()));
            configuration.setNetMask(ByteString.copyFrom(InetAddress.getByName("255.255.255.0").getAddress()));
            configuration.setGateWay(ByteString.copyFrom(InetAddress.getByName("192.168.0.1").getAddress()));
            configuration.setIsDhcpEnabled(false);
            configuration.setCommunicationTimeout(30);
            configuration.setCommunicationNumberOfRetries(5);
            configuration.setCommunicationPauseTimeBetweenConnectionTrials(120);
            configuration
                    .setOspgIpAddress(ByteString.copyFrom(InetAddress.getByName("168.63.97.65").getAddress()));
            configuration.setOsgpPortNumber(12122);
            configuration.setIsTestButtonEnabled(false);
            configuration.setIsAutomaticSummerTimingEnabled(false);
            configuration.setAstroGateSunRiseOffset(-15);
            configuration.setAstroGateSunSetOffset(15);
            configuration.addSwitchingDelay(1);
            configuration.addSwitchingDelay(2);
            configuration.addSwitchingDelay(3);
            configuration.addSwitchingDelay(4);
            configuration.addRelayLinking(Oslp.RelayMatrix.newBuilder()
                    .setMasterRelayIndex(ByteString.copyFrom(new byte[] { 1 })).setMasterRelayOn(false)
                    .setIndicesOfControlledRelaysOn(ByteString.copyFrom(new byte[] { 2, 3, 4 }))
                    .setIndicesOfControlledRelaysOff(ByteString.copyFrom(new byte[] { 2, 3, 4 })));
            configuration.setRelayRefreshing(false).setSummerTimeDetails("0360100")
                    .setWinterTimeDetails("1060200");
        }

        if (device.getDeviceType().equals(Device.PSLD_TYPE)) {
            configuration.setDaliConfiguration(daliConfiguration);
        }

        if (device.getDeviceType().equals(Device.SSLD_TYPE)) {
            configuration.setRelayConfiguration(createRelayConfiguration(device.getOutputSettings()));
        }

        return Oslp.Message.newBuilder().setGetConfigurationResponse(configuration).build();
    } catch (final Exception e) {
        LOGGER.error("Unexpected UnknownHostException", e);
        return null;
    }
}

From source file:org.apache.openjpa.persistence.jdbc.XMLPersistenceMappingParser.java

/**
 * Create a column with the given attributes.
 *//* w  w  w. ja  v  a2s  . c  o  m*/
private Column parseColumn(Attributes attrs) throws SAXException {
    Column col = new Column();
    String val = attrs.getValue("name");
    if (val != null)
        col.setIdentifier(DBIdentifier.newColumn(val, delimit()));
    val = attrs.getValue("referenced-column-name");
    if (val != null) {
        setTargetIdentifier(col, val);
    }
    val = attrs.getValue("column-definition");
    if (val != null)
        col.setTypeIdentifier(DBIdentifier.newColumnDefinition(val));
    val = attrs.getValue("precision");
    if (val != null)
        col.setSize(Integer.parseInt(val));
    val = attrs.getValue("length");
    if (val != null)
        col.setSize(Integer.parseInt(val));
    val = attrs.getValue("scale");
    if (val != null)
        col.setDecimalDigits(Integer.parseInt(val));
    val = attrs.getValue("nullable");
    if (val != null)
        col.setNotNull("false".equals(val));
    val = attrs.getValue("insertable");
    if (val != null)
        col.setFlag(Column.FLAG_UNINSERTABLE, "false".equals(val));
    val = attrs.getValue("updatable");
    if (val != null)
        col.setFlag(Column.FLAG_UNUPDATABLE, "false".equals(val));

    val = attrs.getValue("unique");
    if (val != null)
        _unique.add(Enum.valueOf(UniqueFlag.class, val.toUpperCase()));
    val = attrs.getValue("table");
    if (val != null) {
        if (_colTable != null && !_colTable.equals(val))
            throw getException(_loc.get("second-inconsist", currentElement()));
        _colTable = val;
    }
    return col;
}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * This method gets called by the WdsRdbMapper bean to handle a HTTP
 * request. This method must be multi-thread capable. Note that since we're
 * not using Views, this method must return null.
 * /*w w w. j ava2 s . c om*/
 * @param request
 *            the http request that is being serviced
 * @param response
 *            the response that will be sent back to the service consumer
 * @return must return null since we're not using a view
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    LOG.debug(getBeanName() + ": handleRequestInternal - **** new request ****");

    // dump the request if trace is on
    if (LOG.isTraceEnabled()) {
        LOG.trace(getBeanName() + ":handleRequestInternal - method = " + request.getMethod());
        LOG.trace(getBeanName() + ":handleRequestInternal - uri  = " + request.getRequestURI());
        LOG.trace(getBeanName() + ":handleRequestInternal - protocol  = " + request.getProtocol());
        LOG.trace(getBeanName() + ":handleRequestInternal - secure  = " + request.isSecure());

        // dump all the http headers and their values
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                LOG.trace(getBeanName() + ":handleRequestInternal - " + headerName + " = "
                        + request.getHeader(headerName));
            }
        }

        if (request.getQueryString() != null) {
            LOG.trace(getBeanName() + ":handleRequestInternal - queryString  = " + request.getQueryString());
        }
    }

    long currentTime = System.currentTimeMillis();

    // give the response a Date header with the current time
    response.setDateHeader(DATE_HDR, currentTime);

    // assign the Server header this container's info
    response.setHeader(SERVER_HDR, getServerInfo());

    // determine the HTTP protocol version being used by the client
    // default version will be 0
    int protocolVersion = 0;
    try {
        protocolVersion = Integer
                .parseInt(request.getProtocol().split(FORWARD_SLASH_STR)[1].split(ESC_DOT_STR)[1]);
    } catch (Exception exc) {
        LOG.warn(getBeanName() + ": handleRequestInternal - unable to get http protocol "
                + "version, stack trace follows: ");
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
    }

    LOG.trace(getBeanName() + ":handleRequestInternal - using this " + "protocol version: " + protocolVersion);

    /*
     * Ok, the request first needs to run the security gauntlet
     * 
     * We do not want to send any error messages back to the client that
     * would give it a hint that we're invoking SQL statements. This is a
     * countermeasure for SQL injection probes.
     */

    // see if this RDB is restricting user agents and if so, validate user
    // agent
    if ((getAllowedAgents() != null && !getAllowedAgents().isEmpty())
            || (getNotAllowedAgents() != null && !getNotAllowedAgents().isEmpty())) {

        String userAgent = request.getHeader(USER_AGENT_HDR);

        if (userAgent != null && userAgent.length() > 0) {
            LOG.debug(
                    getBeanName() + ": handleRequestInternal - validating this " + "user agent: " + userAgent);

            // Convert to lower case as allowed agents have been
            // converted to lower case as well
            userAgent = userAgent.toLowerCase();

            boolean allow = false;
            if (getAllowedAgents() != null && !getAllowedAgents().isEmpty()) {
                for (String agent : getAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this allowed agent "
                                + "was found: " + agent);
                        allow = true;
                        break;
                    }
                }
            } else {
                allow = true;
                for (String agent : getNotAllowedAgents()) {
                    LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this "
                            + "non-allowed agent : " + agent);
                    if (userAgent.indexOf(agent) >= 0) {
                        LOG.trace(getBeanName() + ": handleRequestInternal - this non-allowed "
                                + "agent was found: " + agent);
                        allow = false;
                        break;
                    }
                }
            }
            if (!allow) {
                response.sendError(SC_UNAUTHORIZED, "ERROR, user agent " + "is not authorized");
                LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent is " + "not authorized");
                return null;
            }
        } else {
            response.sendError(SC_UNAUTHORIZED,
                    "ERROR, user agent info " + "was not received and is required!");
            LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent header "
                    + "is required but was not provided by the client");
            return null;
        }
    }

    // we do not support chunked transfer encoding, which is a http
    // 1.1 feature.
    if (request.getHeader(TRANSFER_ENCODING_HDR) != null
            && request.getHeader(TRANSFER_ENCODING_HDR).equalsIgnoreCase(CHUNKED)) {
        response.sendError(SC_BAD_REQUEST, "Chunked tranfer encoding is not " + "supported");
        return null;
    }

    /*
     * isSecure returns a boolean indicating whether this request was made
     * using a secure channel, such as HTTPS. so, if the channel must be
     * secure, but it is not, then throw an exception and return an error.
     */
    if (isSecure() && !request.isSecure()) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, channel is not secure");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, channel is not secure");
        return null;
    }

    /*
     * getUserPrincipal() returns a java.security.Principal containing the
     * name of the user making this request, else it returns null if the
     * user has not been authenticated. so, if it is mandated that the user
     * be authenticated, but has not been authenticated, then throw an
     * exception and return an error
     */
    if (isAuthenticated() && request.getUserPrincipal() == null) {
        response.sendError(SC_UNAUTHORIZED, "ERROR, user is not authenticated");
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user is not authenticated");
        return null;
    }

    /*
     * Check for valid method - the only supported http methods are GET,
     * POST, PUT, and DELETE. Here are some good descriptions regarding the
     * methods and their use with respect to this servlet.
     * 
     * The GET method is used for projecting data from the DB. So it maps to
     * a select statement.
     * 
     * The PUT and POST methods are used for inserting or updating an entity
     * in the DB. So they map to either an update or insert.
     * 
     * The DELETE is used for removing one or more entities from the DB. So
     * it maps to a delete.
     * 
     * The bean must be assigned at least one of the methods to service
     */
    Method method = null;
    try {
        method = Enum.valueOf(Method.class, request.getMethod().toUpperCase());
        LOG.debug(getBeanName() + ": handleRequestInternal - processing this method: " + method.toString());
    } catch (IllegalArgumentException e) {
        LOG.error(getBeanName() + ":handleRequestInternal - This method is not allowed [" + request.getMethod()
                + "]");
        response.setHeader("Allow", allowedMethodsRsp);
        response.sendError(SC_METHOD_NOT_ALLOWED, "This method is not allowed [" + request.getMethod() + "]");
        return null;
    }

    // do some more method validation; i.e., make sure requested method has
    // been assigned a SQL statement
    //
    // TODO: we may be able to remove this block of code
    String s1 = null;
    if (method.isGet() && sqlStmnts4Get == null || method.isPost() && sqlStmnts4Post == null
            || method.isPut() && sqlStmnts4Put == null || method.isDelete() && sqlStmnts4Delete == null) {
        response.setHeader("Allow", allowedMethodsRsp);
        s1 = "HTTP method [" + method + "] is not supported";
        response.sendError(SC_METHOD_NOT_ALLOWED, s1);
        LOG.error(getBeanName() + ":handleRequestInternal - " + s1);
        return null;
    }

    // If the client has specified an 'Accept' header field, then determine
    // if it is willing or capable of accepting JSON or anything (*/*)
    //
    // TODO: what about the client accepting urlencoded strings??
    s1 = request.getHeader(ACCEPT_HDR);
    if (s1 != null && s1.length() > 0) {
        LOG.debug(getBeanName() + ":handleRequestInternal - client-specified media "
                + "type in accept header = " + s1);
        // parse the accept header's content
        String[] mediaTypes = s1.trim().split(COMMA_STR);
        boolean match = false;
        for (String mediaType : mediaTypes) {
            mediaType = mediaType.trim().toLowerCase();
            if (mediaType.startsWith(anyContentType) || mediaType.startsWith(jsonContentType)) {
                match = true;
                break;
            }
        }
        if (!match) {
            LOG.error(getBeanName() + ":handleRequestInternal - client-specified media type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            response.sendError(SC_NOT_ACCEPTABLE, "client-specified media " + "type of '" + s1
                    + "' does not include '" + "'" + jsonContentType);
            return null;
        }
    }

    // pick up the corresponding list of SQL statements for this request
    List<SqlStmnt> sqlStmnts = null;
    switch (method) {
    case GET:
        sqlStmnts = getSqlStmnts4Get();
        break;
    case DELETE:
        sqlStmnts = getSqlStmnts4Delete();
        break;
    case PUT:
        sqlStmnts = getSqlStmnts4Put();
        break;
    case POST:
        sqlStmnts = getSqlStmnts4Post();
        break;
    default:
        response.sendError(SC_METHOD_NOT_ALLOWED, "ERROR, unsupported method type: " + method);
        LOG.error(getBeanName() + ": handleRequestInternal - ERROR, encountered unknown " + "method type: "
                + method);
        return null;
    }

    // ~~~~~~ EXTRACT PARAMERTERS, IF ANY ~~~~~~~~~~~

    // GETs with entity bodies are illegal
    if (method.isGet() && request.getContentLength() > 0) {
        response.sendError(SC_BAD_REQUEST,
                "Client has issued a malformed or illegal request; " + "GET cannot include entity body");
        return null;
    }

    // the DELETE method also cannot include an entity body; however, the
    // servlet containers already ignore them. so no need to check for that

    // see if json object arrived
    boolean jsonObjectPresent = (method.isPost() || method.isPut())
            && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(jsonContentType));

    LOG.debug(getBeanName() + ": jsonObjectPresent = " + jsonObjectPresent);

    // see if this is a PUT with entity. we've learned that for PUTs,
    // getParameterMap does not work the same across all servlet containers.
    // so we need take care of this ourselves
    boolean putWithBodyPresent = (method.isPut()) && (request.getContentLength() > 0
            && request.getContentType().equalsIgnoreCase(urlEncodedContentType));

    LOG.debug(getBeanName() + ": putWithBodyPresent = " + putWithBodyPresent);

    // collect incoming parameters and place them in a common bucket
    //
    // ~~~~ ALL PARAMETER KEY NAMES MUST BE FORCED TO LOWER CASE ~~~
    //
    List<Map<String, String>> cParams = new ArrayList<Map<String, String>>();

    // first, get the incoming query or form parameters (if any); we will
    // assume that each key has only one parameter. in other words,
    // we're not dealing with drop-down boxes or things similar
    if (!putWithBodyPresent && !jsonObjectPresent) {
        Map<String, String[]> qParams = request.getParameterMap();
        if (qParams != null && !qParams.isEmpty()) {
            Map<String, String> qMap = new HashMap<String, String>();
            for (String key : qParams.keySet()) {
                qMap.put(key.toLowerCase(), qParams.get(key)[0]);
            }
            if (!qMap.isEmpty()) {
                cParams.add(qMap);
                LOG.debug(getBeanName() + ": query params = " + qMap.toString());
            }
        }
    }

    // a put with entity body arrived, so get the parameters from the
    // body and place them in the common bucket
    else if (putWithBodyPresent) {

        try {
            Map<String, String> putParams = null;
            // parseUrlEncoded will force keys to lower case
            putParams = Utils.parseUrlEncoded(request.getInputStream());
            if (putParams != null && !putParams.isEmpty()) {
                cParams.add(putParams);
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing urlencoded string: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "urlencoded string parsing error: " + exc.getMessage());
            return null;
        }
    }

    // ok, a json object arrived, so get parameters defined in that object
    // and place them in the common bucket
    else {
        // its a json object, so parse it to extract params from it
        try {
            List<Map<String, String>> jParams = null;
            // parseJson will ensure that all passed-in JSON objects have
            // the same set of identical keys
            jParams = Utils.parseJson(request.getInputStream());
            if (jParams != null && !jParams.isEmpty()) {
                // if we also got query params then ensure they have the
                // same set of keys as the json params. why anyone would
                // ever do this is beyond me, but I'll leave it in for now
                if (!cParams.isEmpty()) {
                    Map<String, String> cMap = cParams.get(0);
                    Map<String, String> jMap = jParams.get(0);
                    for (String key : cMap.keySet()) {
                        if (jMap.get(key) == null) {
                            String eStr = getBeanName() + ": ERROR, json "
                                    + "object key set does not match query " + "param key set";
                            LOG.error(eStr);
                            response.sendError(SC_BAD_REQUEST, eStr);
                            return null;
                        }
                    }
                    // place the passed in query params in the jParams
                    // bucket
                    jParams.add(cMap);
                }
                // assign the jParams bucket to the common bucket
                cParams = jParams;
            }
        } catch (Exception exc) {
            LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing json object: "
                    + exc.toString());
            LOG.error(getBeanName() + ": exception stack trace follows:");
            dumpStackTrace(exc.getStackTrace());
            if (exc.getCause() != null) {
                LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
                LOG.error(getBeanName() + ": causing exception stack trace follows:");
                dumpStackTrace(exc.getCause().getStackTrace());
            }
            response.sendError(SC_BAD_REQUEST, "json parsing error: " + exc.getMessage());
            return null;
        }
    }

    // if trace is on, dump the params (if any) to the log
    if (LOG.isDebugEnabled()) {
        if (!cParams.isEmpty()) {
            for (int i = 0; i < cParams.size(); i++) {
                LOG.debug(getBeanName() + ": handleRequestInternal - received these params: "
                        + cParams.get(i).toString());
            }
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - did not receive any params");
        }
    }

    // ensure none of the params' values have been black listed
    if (!cParams.isEmpty() && getBlackList().length() > 0) {
        char[] bl = getBlackList().toCharArray();
        for (int i = 0; i < cParams.size(); i++) {
            for (String value : cParams.get(i).values()) {
                if (Utils.isOnBlackList(value, bl)) {
                    response.sendError(SC_BAD_REQUEST,
                            "encountered black listed character in this param " + "value: " + value);
                    LOG.error(getBeanName() + "handleRequestInternal - encountered black listed "
                            + "character in this param value: " + value);
                    return null;
                }

            }
        }
    }

    // find the proper SQL statement based on the incoming parameters' (if
    // any) keys
    SqlStmnt sqlStmnt = null;
    try {
        // getMatch will try and find a match, even if no params were
        // provided.
        // @formatter:off
        sqlStmnt = (cParams.isEmpty()) ? SqlStmnt.getMatch(sqlStmnts, null)
                : SqlStmnt.getMatch(sqlStmnts, cParams.get(0).keySet());
        // @formatter:on

        if (sqlStmnt == null && !cParams.isEmpty()) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this incoming param set: "
                    + cParams.toString());
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        } else if (sqlStmnt == null) {
            LOG.warn(getBeanName() + ": warning, unable to find sql "
                    + "statement on first pass, will use extra path info");
        } else {
            LOG.debug(getBeanName() + ": handleRequestInternal - matching sql stmt = " + sqlStmnt.toString());
        }
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this exception " + "while mapping sql to params: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "mapping error");
        return null;
    }

    // if getMatch could not find a match - perhaps input params were not
    // provided - then use the URI's 'extended path' information as an input
    // param
    if (sqlStmnt == null) {
        LOG.debug(getBeanName() + ": invoking getExtraPathInfo");
        String[] xtraPathInfo = Utils.getExtraPathInfo(request.getPathInfo());
        if (xtraPathInfo != null && xtraPathInfo.length >= 2) {
            LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]);
        } else {
            LOG.error(getBeanName() + ":ERROR, getExtraPathInfo failed to find info");
            response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error");
            return null;
        }
        // put the xtra path info in the common param bucket and try again
        cParams.clear();
        Map<String, String> xMap = new HashMap<String, String>();
        xMap.put(xtraPathInfo[0], xtraPathInfo[1]);
        cParams.add(xMap);
        // try again with the extra path info
        sqlStmnt = SqlStmnt.getMatch(sqlStmnts, xMap.keySet());
        if (sqlStmnt == null) {
            LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this xtra path info: "
                    + cParams.toString());
            response.sendError(SC_NOT_FOUND, "internal server error: mapping error");
            return null;
        }
    }

    // if we've gotten this far, we've gotten past the security gauntlet and
    // we have a SQL statement to work with.
    SqlResult sqlResult = null;
    try {
        // get the output stream
        OutputStream os = response.getOutputStream();

        // FIRE IN THE DB HOLE :)
        if ((sqlResult = sqlStmnt.execute(cParams)) == null) {
            // execute will have logged the necessary debug/error info
            response.sendError(SC_INTERNAL_SERVER_ERROR);
            return null;
        }

        // execute went through ok, lets see how to respond
        switch (method) {
        case GET:
            // if a resultset was returned, then set the content type,
            // convert it to json, and write it out
            List<Map<String, Object>> listMap = sqlResult.getResultSet();
            if (listMap != null) {
                // tell the client the content type
                response.setContentType(rspJsonContentType);
                String jsonOutput = Utils.generateJson(sqlResult.getResultSet());
                LOG.trace(getBeanName() + ": returning this payload - " + jsonOutput);
                os.write(jsonOutput.getBytes());

                // ensure that only the client can cache the data and tell
                // the client how long the data can remain active
                response.setHeader(CACHE_CNTRL_HDR,
                        (getCacheControl() != null) ? getCacheControl() : DFLT_CACHE_CNTRL_STR);
                response.setHeader(PRAGMA_HDR, PRAGMA_NO_CACHE_STR);
                response.setDateHeader(EXPIRES_HDR, currentTime + (getExpires() * 1000));
            } else {
                LOG.debug(getBeanName() + ": NOT returning json message");
            }
            response.setStatus(SC_OK);
            break;
        case DELETE:
            // a DELETE should not send back an entity body
            response.setStatus(SC_NO_CONTENT);
            break;
        case PUT:
            /*
             * PUTs are idempotent; therefore, they must provide ALL the
             * properties that pertain to the resource/entity that they are
             * creating or updating. Updates cannot be partial updates; they
             * must be full updates. A PUT is issued by a client that knows
             * the identifier (in our case, primary key) of the
             * resource/entity. Therefore, we do not have to send back a
             * Location header in response to a PUT that has created a
             * resource.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
            } else {
                response.setStatus(SC_OK);
            }
            break;
        case POST:
            /*
             * A POST is not idempotent; therefore, it can be used to
             * perform a 'partial' update, as well as a full create. When
             * creating a resource via POST, the client does not know the
             * primary key, and it assumes it will be auto-generated;
             * therefore, a Location header with auto-generated key must be
             * returned to client.
             */
            if (sqlStmnt.isInsert()) {
                response.setStatus(SC_CREATED);
                // we need to return the new key, but only if it was not a
                // batch insert. the new key should be returned via the
                // location header

                // check if a key holder exists; if not, then table was not
                // configured with auto-generated key.
                String locationPath = request.getRequestURL().toString();
                if (sqlResult.getKeyHolder() != null) {
                    // key holder exists, check and see if a key is
                    // present
                    if (sqlResult.getKeyHolder().getKey() != null) {
                        String id = sqlResult.getKeyHolder().getKey().toString();
                        LOG.debug(getBeanName() + ": getKey() returns " + id);
                        locationPath += ("/" + id);
                        LOG.debug(getBeanName() + ": locationPath = " + locationPath);
                        response.setHeader(LOCATION_HDR, locationPath);
                    }
                    // no key, check for multiple keys
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeys() != null) {
                        Map<String, Object> keyMap = sqlResult.getKeyHolder().getKeys();
                        LOG.debug(getBeanName() + ": getKeys() returns " + keyMap);
                    }
                    // maybe map of keys?
                    // TODO: should we send back all keys?
                    else if (sqlResult.getKeyHolder().getKeyList() != null) {
                        for (Map<String, Object> map : sqlResult.getKeyHolder().getKeyList()) {
                            LOG.debug(getBeanName() + ": Map from getKeyList(): " + map);
                        }
                    }
                } else {
                    // if it was not an insert, then it was an update.
                    LOG.debug(getBeanName() + ": key holder was not returned for the insert");
                }
            } else {
                // it was not an insert, so just send back an OK for the
                // update
                response.setStatus(SC_OK);
            }
            break;
        default:
            response.setStatus(SC_OK);
            break;
        }
    } catch (JsonProcessingException exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "JsonProcessingException while trying to gen json "
                + "message: " + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;
    } catch (Exception exc) {
        LOG.error(getBeanName() + ":ERROR, caught this " + "Exception while trying to gen json " + "message: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        if (exc.getCause() != null) {
            LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
            LOG.error(getBeanName() + ": causing exception stack trace follows:");
            dumpStackTrace(exc.getCause().getStackTrace());
        }
        response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error");
        return null;

    } finally {
        if (sqlResult != null) {
            SqlResult.enqueue(sqlResult);
        }
    }

    // must return null, because we're not using views!
    return null;
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Reads an array from JSON, where each value is of the listed in types; EG the first element
 * is class type[0], the second element is class type[1] etc
 * @param jp/*from ww w  . j ava  2  s . c  o m*/
 * @param types
 * @return
 * @throws IOException
 */
private Object[] readArray(JsonParser jp, Class[] types) throws IOException {
    if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
        return null;

    ArrayList result = new ArrayList();
    for (int paramIndex = 0; jp.nextToken() != JsonToken.END_ARRAY; paramIndex++) {
        Class type = null;
        if (types != null && paramIndex < types.length)
            type = types[paramIndex];

        if (type != null && type.isArray()) {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
                result.add(null);
            else if (jp.getCurrentToken() == JsonToken.START_ARRAY) {
                Object obj = readArray(jp, type.getComponentType());
                result.add(obj);
            } else
                throw new IllegalStateException("Expected array but found " + jp.getCurrentToken());

        } else if (type != null && Proxied.class.isAssignableFrom(type)) {
            Integer id = jp.readValueAs(Integer.class);
            if (id != null) {
                Proxied obj = getProxied(id);
                result.add(obj);
            } else
                result.add(null);

        } else if (type != null && Enum.class.isAssignableFrom(type)) {
            Object obj = jp.readValueAs(Object.class);
            if (obj != null) {
                String str = Helpers.camelCaseToEnum(obj.toString());
                obj = Enum.valueOf(type, str);
                result.add(obj);
            }
        } else {
            Object obj = jp.readValueAs(type != null ? type : Object.class);
            result.add(obj);
        }
    }
    return result.toArray(new Object[result.size()]);
}

From source file:net.firejack.platform.core.store.AbstractStore.java

private <T extends Enum<T>> T prepareEnumFromSearchCriteria(Class<T> type, Object item) {
    T enumItem;/*  ww w.  java 2 s  .  com*/
    if (item instanceof String) {
        try {
            enumItem = Enum.valueOf(type, (String) item);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new IllegalArgumentException("Failed to convert enum value from the search criteria.");
        }
    } else if (item instanceof Enum) {
        enumItem = (T) item;
    } else {
        throw new IllegalArgumentException("Failed to convert enum value from the search criteria.");
    }
    return enumItem;
}

From source file:com.github.helenusdriver.driver.impl.DataDecoder.java

/**
 * Gets an element decoder that can be used to convert a Cassandra
 * returned data type into another data type based on special supported
 * combinations.//from www.  j  a v  a 2  s .  c om
 *
 * @author paouelle
 *
 * @param  eclass the non-<code>null</code> element class to decode to
 * @param  reclass the non-<code>null</code> row's element class
 * @return a non-<code>null</code> element decoder for the provided combination
 * @throws IllegalArgumentException if the combination is not supported
 */
@SuppressWarnings("rawtypes")
static ElementConverter getConverter(final Class eclass, Class reclass) {
    if (Enum.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @SuppressWarnings("unchecked")
            @Override
            public Object convert(Object re) {
                return Enum.valueOf(eclass, (String) re);
            }
        };
    } else if (Locale.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return LocaleUtils.toLocale((String) re);
            }
        };
    } else if (ZoneId.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                try {
                    return ZoneId.of((String) re);
                } catch (DateTimeException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        };
    } else if (eclass.isArray() && (Byte.TYPE == eclass.getComponentType())
            && ByteBuffer.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return Bytes.getArray((ByteBuffer) re);
            }
        };
    } else if ((Long.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).getTime();
            }
        };
    } else if ((Instant.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).toInstant();
            }
        };
    } else if (eclass == reclass) { // special case for maps
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return re;
            }
        };
    }
    throw new IllegalArgumentException(
            "unsupported element conversion from: " + reclass.getName() + " to: " + eclass.getName());
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Reads the current token value, with special consideration for enums
 * @param jp//w  w  w  . j a va2 s .  c  o  m
 * @param clazz
 * @return
 * @throws IOException
 */
private Object readSimpleValue(JsonParser jp, Class clazz) throws IOException {
    if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
        return null;

    Object obj = null;
    if (Enum.class.isAssignableFrom(clazz)) {
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME)
            obj = jp.getCurrentName();
        else
            obj = jp.readValueAs(Object.class);
        if (obj != null) {
            String str = Helpers.camelCaseToEnum(obj.toString());
            obj = Enum.valueOf(clazz, str);
        }
    } else {
        if (jp.getCurrentToken() == JsonToken.FIELD_NAME)
            obj = jp.getCurrentName();
        else
            obj = jp.readValueAs(clazz);
    }
    return obj;
}

From source file:com.microsoft.azure.management.notificationhubs.NamespaceOperationsImpl.java

/**
* Creates/Updates a service namespace. Once created, this namespace's
* resource manifest is immutable. This operation is idempotent.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for
* more information)/*from w w w  .  j  av a2  s. co  m*/
*
* @param resourceGroupName Required. The name of the resource group.
* @param namespaceName Required. The namespace name.
* @param parameters Required. Parameters supplied to the create a Namespace
* Resource.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The response of the CreateOrUpdate Namespace.
*/
@Override
public NamespaceCreateOrUpdateResponse createOrUpdate(String resourceGroupName, String namespaceName,
        NamespaceCreateOrUpdateParameters parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    if (parameters.getProperties() == null) {
        throw new NullPointerException("parameters.Properties");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("namespaceName", namespaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createOrUpdateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.NotificationHubs";
    url = url + "/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-09-01");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode namespaceCreateOrUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = namespaceCreateOrUpdateParametersValue;

    ((ObjectNode) namespaceCreateOrUpdateParametersValue).put("location", parameters.getLocation());

    if (parameters.getTags() != null) {
        if (parameters.getTags() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getTags()).isInitialized()) {
            ObjectNode tagsDictionary = objectMapper.createObjectNode();
            for (Map.Entry<String, String> entry : parameters.getTags().entrySet()) {
                String tagsKey = entry.getKey();
                String tagsValue = entry.getValue();
                ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue);
            }
            ((ObjectNode) namespaceCreateOrUpdateParametersValue).put("tags", tagsDictionary);
        }
    }

    ObjectNode propertiesValue = objectMapper.createObjectNode();
    ((ObjectNode) namespaceCreateOrUpdateParametersValue).put("properties", propertiesValue);

    if (parameters.getProperties().getName() != null) {
        ((ObjectNode) propertiesValue).put("name", parameters.getProperties().getName());
    }

    if (parameters.getProperties().getProvisioningState() != null) {
        ((ObjectNode) propertiesValue).put("provisioningState",
                parameters.getProperties().getProvisioningState());
    }

    if (parameters.getProperties().getRegion() != null) {
        ((ObjectNode) propertiesValue).put("region", parameters.getProperties().getRegion());
    }

    if (parameters.getProperties().getStatus() != null) {
        ((ObjectNode) propertiesValue).put("status", parameters.getProperties().getStatus());
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    ((ObjectNode) propertiesValue).put("createdAt",
            simpleDateFormat.format(parameters.getProperties().getCreatedAt().getTime()));

    if (parameters.getProperties().getServiceBusEndpoint() != null) {
        ((ObjectNode) propertiesValue).put("serviceBusEndpoint",
                parameters.getProperties().getServiceBusEndpoint().toString());
    }

    if (parameters.getProperties().getSubscriptionId() != null) {
        ((ObjectNode) propertiesValue).put("subscriptionId", parameters.getProperties().getSubscriptionId());
    }

    if (parameters.getProperties().getScaleUnit() != null) {
        ((ObjectNode) propertiesValue).put("scaleUnit", parameters.getProperties().getScaleUnit());
    }

    ((ObjectNode) propertiesValue).put("enabled", parameters.getProperties().isEnabled());

    ((ObjectNode) propertiesValue).put("critical", parameters.getProperties().isCritical());

    if (parameters.getProperties().getNamespaceType() != null) {
        ((ObjectNode) propertiesValue).put("namespaceType",
                parameters.getProperties().getNamespaceType().toString());
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        NamespaceCreateOrUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new NamespaceCreateOrUpdateResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                NamespaceResource valueInstance = new NamespaceResource();
                result.setValue(valueInstance);

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    valueInstance.setId(idInstance);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    valueInstance.setLocation(locationInstance);
                }

                JsonNode nameValue = responseDoc.get("name");
                if (nameValue != null && nameValue instanceof NullNode == false) {
                    String nameInstance;
                    nameInstance = nameValue.getTextValue();
                    valueInstance.setName(nameInstance);
                }

                JsonNode typeValue = responseDoc.get("type");
                if (typeValue != null && typeValue instanceof NullNode == false) {
                    String typeInstance;
                    typeInstance = typeValue.getTextValue();
                    valueInstance.setType(typeInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                    while (itr.hasNext()) {
                        Map.Entry<String, JsonNode> property = itr.next();
                        String tagsKey2 = property.getKey();
                        String tagsValue2 = property.getValue().getTextValue();
                        valueInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    NamespaceProperties propertiesInstance = new NamespaceProperties();
                    valueInstance.setProperties(propertiesInstance);

                    JsonNode nameValue2 = propertiesValue2.get("name");
                    if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                        String nameInstance2;
                        nameInstance2 = nameValue2.getTextValue();
                        propertiesInstance.setName(nameInstance2);
                    }

                    JsonNode provisioningStateValue = propertiesValue2.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        propertiesInstance.setProvisioningState(provisioningStateInstance);
                    }

                    JsonNode regionValue = propertiesValue2.get("region");
                    if (regionValue != null && regionValue instanceof NullNode == false) {
                        String regionInstance;
                        regionInstance = regionValue.getTextValue();
                        propertiesInstance.setRegion(regionInstance);
                    }

                    JsonNode statusValue = propertiesValue2.get("status");
                    if (statusValue != null && statusValue instanceof NullNode == false) {
                        String statusInstance;
                        statusInstance = statusValue.getTextValue();
                        propertiesInstance.setStatus(statusInstance);
                    }

                    JsonNode createdAtValue = propertiesValue2.get("createdAt");
                    if (createdAtValue != null && createdAtValue instanceof NullNode == false) {
                        Calendar createdAtInstance;
                        createdAtInstance = DatatypeConverter.parseDateTime(createdAtValue.getTextValue());
                        propertiesInstance.setCreatedAt(createdAtInstance);
                    }

                    JsonNode serviceBusEndpointValue = propertiesValue2.get("serviceBusEndpoint");
                    if (serviceBusEndpointValue != null
                            && serviceBusEndpointValue instanceof NullNode == false) {
                        URI serviceBusEndpointInstance;
                        serviceBusEndpointInstance = new URI(serviceBusEndpointValue.getTextValue());
                        propertiesInstance.setServiceBusEndpoint(serviceBusEndpointInstance);
                    }

                    JsonNode subscriptionIdValue = propertiesValue2.get("subscriptionId");
                    if (subscriptionIdValue != null && subscriptionIdValue instanceof NullNode == false) {
                        String subscriptionIdInstance;
                        subscriptionIdInstance = subscriptionIdValue.getTextValue();
                        propertiesInstance.setSubscriptionId(subscriptionIdInstance);
                    }

                    JsonNode scaleUnitValue = propertiesValue2.get("scaleUnit");
                    if (scaleUnitValue != null && scaleUnitValue instanceof NullNode == false) {
                        String scaleUnitInstance;
                        scaleUnitInstance = scaleUnitValue.getTextValue();
                        propertiesInstance.setScaleUnit(scaleUnitInstance);
                    }

                    JsonNode enabledValue = propertiesValue2.get("enabled");
                    if (enabledValue != null && enabledValue instanceof NullNode == false) {
                        boolean enabledInstance;
                        enabledInstance = enabledValue.getBooleanValue();
                        propertiesInstance.setEnabled(enabledInstance);
                    }

                    JsonNode criticalValue = propertiesValue2.get("critical");
                    if (criticalValue != null && criticalValue instanceof NullNode == false) {
                        boolean criticalInstance;
                        criticalInstance = criticalValue.getBooleanValue();
                        propertiesInstance.setCritical(criticalInstance);
                    }

                    JsonNode namespaceTypeValue = propertiesValue2.get("namespaceType");
                    if (namespaceTypeValue != null && namespaceTypeValue instanceof NullNode == false) {
                        NamespaceType namespaceTypeInstance;
                        namespaceTypeInstance = Enum.valueOf(NamespaceType.class,
                                namespaceTypeValue.getTextValue());
                        propertiesInstance.setNamespaceType(namespaceTypeInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.alliander.osgp.webdevicesimulator.service.OslpChannelHandler.java

private static Message createGetStatusResponse(final Device device) {

    final List<LightValue> outputValues = new ArrayList<>();
    for (final DeviceOutputSetting dos : device.getOutputSettings()) {
        final LightValue.Builder lightValue = LightValue.newBuilder()
                .setIndex(OslpUtils.integerToByteString(dos.getInternalId()));

        if (dos.getOutputType().equals(OutputType.LIGHT)) {
            lightValue.setOn(device.isLightOn());

            if (device.getDimValue() != null) {
                lightValue.setDimValue(OslpUtils.integerToByteString(device.getDimValue()));
            }/* www. j a v  a2s  .com*/

            // Real device specifies dimvalue 0 when off.
            if (!device.isLightOn()) {
                lightValue.setDimValue(OslpUtils.integerToByteString(0));
            }

        } else if (dos.getOutputType().equals(OutputType.TARIFF)) {
            lightValue.setOn(device.isTariffOn());
        }
        outputValues.add(lightValue.build());
    }

    // Fallback in case output settings are not yet defined.
    if (outputValues.isEmpty()) {
        final LightValue.Builder lightValue = LightValue.newBuilder().setIndex(OslpUtils.integerToByteString(0))
                .setOn(device.isLightOn());

        if (device.getDimValue() != null) {
            lightValue.setDimValue(OslpUtils.integerToByteString(device.getDimValue()));
        }

        // Real device specifies dimvalue 0 when off.
        if (!device.isLightOn()) {
            lightValue.setDimValue(OslpUtils.integerToByteString(0));
        }

        outputValues.add(lightValue.build());
    }

    final Oslp.GetStatusResponse.Builder builder = GetStatusResponse.newBuilder();

    builder.setStatus(Oslp.Status.OK);
    builder.addAllValue(outputValues);
    builder.setPreferredLinktype(Enum.valueOf(Oslp.LinkType.class, device.getPreferredLinkType().name()));
    builder.setActualLinktype(Enum.valueOf(Oslp.LinkType.class, device.getActualLinkType().name()));
    builder.setLightType(Enum.valueOf(Oslp.LightType.class, device.getLightType().name()));
    builder.setEventNotificationMask(device.getEventNotificationMask());

    LOGGER.info("device.getProtocol(): {}", device.getProtocol());
    LOGGER.info("ProtocolType.OSLP_ELSTER.name(): {}", ProtocolType.OSLP_ELSTER.name());

    if (device.getProtocol().equals(ProtocolType.OSLP_ELSTER.toString())) {
        builder.setNumberOfOutputs(4);
        builder.setDcOutputVoltageMaximum(24000);
        builder.setDcOutputVoltageCurrent(24000);
        builder.setMaximumOutputPowerOnDcOutput(15000);
        builder.setSerialNumber(
                ByteString.copyFrom(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9 }));
        builder.setMacAddress(ByteString.copyFrom(new byte[] { 1, 2, 3, 4, 5, 6 }));
        builder.setHardwareId("Hardware ID").setInternalFlashMemSize(1024);
        builder.setExternalFlashMemSize(2048).setLastInternalTestResultCode(0).setStartupCounter(42);
        builder.setBootLoaderVersion("1.1.1").setFirmwareVersion("2.8.5");
        builder.setCurrentConfigurationBackUsed(ByteString.copyFrom(new byte[] { 0 }));
        builder.setName("ELS_DEV-SIM-DEVICE").setCurrentTime("20251231155959");
        builder.setCurrentIp("127.0.0.1");
    }

    return Oslp.Message.newBuilder().setGetStatusResponse(builder.build()).build();
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanConverter.java

private <T> T unmarshallPrimitive(PrimitiveXNode<?> xprim, Class<T> classType) throws SchemaException {
    if (XmlAsStringType.class.equals(classType)) {
        return (T) new XmlAsStringType((String) xprim.getParsedValue(DOMUtil.XSD_STRING));
    }/*from   w w w  .  j a  v a 2s  .c  o m*/
    if (XmlTypeConverter.canConvert(classType)) {
        // Trivial case, direct conversion
        QName xsdType = XsdTypeMapper.toXsdType(classType);
        T primValue = postConvertUnmarshall(xprim.getParsedValue(xsdType));
        return primValue;
    }

    if (RawType.class.isAssignableFrom(classType)) {
        RawType rawType = new RawType(xprim, prismContext);
        return (T) rawType;
    }

    if (PolyStringType.class.isAssignableFrom(classType)) {
        String value = (String) xprim.getParsedValue(DOMUtil.XSD_STRING);
        PolyString polyString = new PolyString(value);
        if (value != null) {
            if (prismContext != null) { // actually this should be always so [med]
                // TODO should we always use default normalizer?
                polyString.recompute(prismContext.getDefaultPolyStringNormalizer());
            }
        }
        return (T) new PolyStringType(polyString);
    }

    if (ItemPathType.class.isAssignableFrom(classType)) {
        Object parsedValue = xprim.getParsedValue(ItemPathType.COMPLEX_TYPE);
        T primValue = postConvertUnmarshall(parsedValue);
        return (T) primValue;
    }

    if (SearchFilterType.class.isAssignableFrom(classType)) {
        throw new SchemaException("Cannot unmarshall search filter from " + xprim);
    }

    if (xprim.isEmpty() && !classType.isEnum()) {
        // Special case. Just return empty object
        try {
            return classType.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new SystemException("Cannot instantiate " + classType + ": " + e.getMessage(), e);
        }
    }

    if (!classType.isEnum()) {
        throw new SchemaException("Cannot convert primitive value to non-enum bean of type " + classType);
    }
    // Assume string, maybe TODO extend later
    String primValue = (String) xprim.getParsedValue(DOMUtil.XSD_STRING);
    if (StringUtils.isBlank(primValue)) {
        return null;
    }
    primValue = StringUtils.trim(primValue);

    String javaEnumString = inspector.findEnumFieldName(classType, primValue);
    //      for (Field field: classType.getDeclaredFields()) {
    //         XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
    //         if (xmlEnumValue != null && xmlEnumValue.value() != null && xmlEnumValue.value().equals(primValue)) {
    //            javaEnumString = field.getName();
    //            break;
    //         }
    //      }

    if (javaEnumString == null) {
        for (Field field : classType.getDeclaredFields()) {
            if (field.getName().equals(primValue)) {
                javaEnumString = field.getName();
                break;
            }
        }
    }

    if (javaEnumString == null) {
        throw new SchemaException("Cannot find enum value for string '" + primValue + "' in " + classType);
    }

    T bean = (T) Enum.valueOf((Class<Enum>) classType, javaEnumString);

    return bean;
}