Example usage for java.lang String getClass

List of usage examples for java.lang String getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.bol.crazypigs.HBaseStorage15.java

@SuppressWarnings("unchecked")
@Override//from w  w  w  .  ja  v  a  2  s .  c o  m
public void putNext(Tuple t) throws IOException {
    ResourceFieldSchema[] fieldSchemas = (schema_ == null) ? null : schema_.getFields();
    byte type = (fieldSchemas == null) ? DataType.findType(t.get(0)) : fieldSchemas[0].getType();
    long ts;

    int startIndex = 1;
    if (includeTimestamp_) {
        byte timestampType = (fieldSchemas == null) ? DataType.findType(t.get(startIndex))
                : fieldSchemas[startIndex].getType();
        LoadStoreCaster caster = (LoadStoreCaster) caster_;

        switch (timestampType) {
        case DataType.BYTEARRAY:
            ts = caster.bytesToLong(((DataByteArray) t.get(startIndex)).get());
            break;
        case DataType.LONG:
            ts = ((Long) t.get(startIndex)).longValue();
            break;
        case DataType.DATETIME:
            ts = ((DateTime) t.get(startIndex)).getMillis();
            break;
        default:
            throw new IOException("Unable to find a converter for timestamp field " + t.get(startIndex));
        }

        startIndex++;
    } else {
        ts = System.currentTimeMillis();
    }

    // check for deletes
    if (includeTombstone_) {
        if (((Boolean) t.get(startIndex)).booleanValue()) {
            Delete delete = createDelete(t.get(0), type, ts);
            try {
                // this is a delete so there will be
                // no put and we are done here
                writer.write(null, delete);
                return;
            } catch (InterruptedException e) {
                throw new IOException(e);
            }
        }

        startIndex++;
    }

    Put put = createPut(t.get(0), type);

    if (LOG.isDebugEnabled()) {
        LOG.debug("putNext -- WAL disabled: " + noWAL_);
        for (ColumnInfo columnInfo : columnInfo_) {
            LOG.debug("putNext -- col: " + columnInfo);
        }
    }

    for (int i = startIndex; i < t.size(); ++i) {
        ColumnInfo columnInfo = columnInfo_.get(i - startIndex);
        if (LOG.isDebugEnabled()) {
            LOG.debug("putNext - tuple: " + i + ", value=" + t.get(i) + ", cf:column=" + columnInfo);
        }

        if (!columnInfo.isColumnMap()) {
            put.add(columnInfo.getColumnFamily(), columnInfo.getColumnName(), ts, objToBytes(t.get(i),
                    (fieldSchemas == null) ? DataType.findType(t.get(i)) : fieldSchemas[i].getType()));
        } else {
            Map<String, Object> cfMap = (Map<String, Object>) t.get(i);
            if (cfMap != null) {
                for (String colName : cfMap.keySet()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("putNext - colName=" + colName + ", class: " + colName.getClass());
                    }
                    // TODO deal with the fact that maps can have types now. Currently we detect types at
                    // runtime in the case of storing to a cf, which is suboptimal.
                    put.add(columnInfo.getColumnFamily(), Bytes.toBytes(colName.toString()), ts,
                            objToBytes(cfMap.get(colName), DataType.findType(cfMap.get(colName))));
                }
            }
        }
    }

    try {
        if (!put.isEmpty()) {
            writer.write(null, put);
        }
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:catalina.mbeans.MBeanFactory.java

/**
 * Create a new HttpsConnector/*from ww w.  ja  va  2  s .  c om*/
 *
 * @param parent MBean Name of the associated parent component
 * @param address The IP address on which to bind
 * @param port TCP port number to listen on
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createHttpsConnector(String parent, String address, int port) throws Exception {

    Object retobj = null;

    try {

        // Create a new CoyoteConnector instance
        // use reflection to avoid j-t-c compile-time circular dependencies
        Class cls = Class.forName("org.apache.coyote.tomcat4.CoyoteConnector");
        Constructor ct = cls.getConstructor(null);
        retobj = ct.newInstance(null);
        Class partypes1[] = new Class[1];
        // Set address
        String str = new String();
        partypes1[0] = str.getClass();
        Method meth1 = cls.getMethod("setAddress", partypes1);
        Object arglist1[] = new Object[1];
        arglist1[0] = address;
        meth1.invoke(retobj, arglist1);
        // Set port number
        Class partypes2[] = new Class[1];
        partypes2[0] = Integer.TYPE;
        Method meth2 = cls.getMethod("setPort", partypes2);
        Object arglist2[] = new Object[1];
        arglist2[0] = new Integer(port);
        meth2.invoke(retobj, arglist2);
        // Set scheme
        Class partypes3[] = new Class[1];
        partypes3[0] = str.getClass();
        Method meth3 = cls.getMethod("setScheme", partypes3);
        Object arglist3[] = new Object[1];
        arglist3[0] = new String("https");
        meth3.invoke(retobj, arglist3);
        // Set secure
        Class partypes4[] = new Class[1];
        partypes4[0] = Boolean.TYPE;
        Method meth4 = cls.getMethod("setSecure", partypes4);
        Object arglist4[] = new Object[1];
        arglist4[0] = new Boolean(true);
        meth4.invoke(retobj, arglist4);
        // Set factory 
        Class serverSocketFactoryCls = Class.forName("org.apache.catalina.net.ServerSocketFactory");
        Class coyoteServerSocketFactoryCls = Class
                .forName("org.apache.coyote.tomcat4.CoyoteServerSocketFactory");
        Constructor factoryConst = coyoteServerSocketFactoryCls.getConstructor(null);
        Object factoryObj = factoryConst.newInstance(null);
        Class partypes5[] = new Class[1];
        partypes5[0] = serverSocketFactoryCls;
        Method meth5 = cls.getMethod("setFactory", partypes5);
        Object arglist5[] = new Object[1];
        arglist5[0] = factoryObj;
        meth5.invoke(retobj, arglist5);
    } catch (Exception e) {
        throw new MBeanException(e);
    }

    try {
        // Add the new instance to its parent component
        ObjectName pname = new ObjectName(parent);
        Server server = ServerFactory.getServer();
        Service service = server.findService(pname.getKeyProperty("name"));
        service.addConnector((Connector) retobj);
    } catch (Exception e) {
        // FIXME
        // disply error message 
        // the user needs to use keytool to configure SSL first
        // addConnector will fail otherwise
        return null;
    }

    // Return the corresponding MBean name
    ManagedBean managed = registry.findManagedBean("CoyoteConnector");
    ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), (Connector) retobj);
    return (oname.toString());

}

From source file:org.kuali.rice.krms.framework.engine.expression.DefaultComparisonOperator.java

/**
 * /*ww  w  .  java2 s .  c  om*/
 * @param objectArg
 * @param stringArg
 * @return Object
 * @throws IncompatibleTypeException
 */
private Object coerceStringOperand(Object objectArg, String stringArg) {
    Object result = stringArg;
    if (objectArg != null && stringArg != null) {
        if (!(objectArg instanceof String)) {
            result = coerceHelper(objectArg, stringArg, Double.class, Float.class, Long.class, Integer.class,
                    Boolean.class);

            if (result instanceof String) { // was coercion successful?
                if (objectArg instanceof BigDecimal) {
                    try {
                        result = BigDecimal.valueOf(Double.valueOf(stringArg.toString()));
                    } catch (NumberFormatException e) {
                        throw new IncompatibleTypeException("Could not coerce String to BigDecimal" + this,
                                stringArg, objectArg.getClass());
                    }
                } else if (objectArg instanceof BigInteger) {
                    try {
                        result = BigInteger.valueOf(Long.valueOf(stringArg.toString()));
                    } catch (NumberFormatException e) {
                        throw new IncompatibleTypeException("Could not coerce String to BigInteger" + this,
                                stringArg, objectArg.getClass());
                    }
                } else {
                    throw new IncompatibleTypeException("Could not compare values for operator " + this,
                            objectArg, stringArg.getClass());
                }
            }
        }
    }
    return result;
}

From source file:org.nuclos.server.ruleengine.ejb3.RuleInterfaceFacadeBean.java

/**
 * This Method sets the Connectionsettings defined in the Webservice Entity to the Stub.
 * The Service is looked up by the serviceName.
 *
 * Everything set like Username, Encoding etc is set to the Stub.
 * Somehow a Connection Initializer.// w w  w.j a  va 2 s . c  o m
 *
 * @param Stub stub
 * @param String servicename
 */
public void setConnectionSettingsForWebservice(Object stub, String serviceName)
        throws NuclosBusinessRuleException {
    //public void setConnectionSettingsForWebservice(Stub stub, String serviceName) throws NuclosBusinessRuleException {

    MasterDataMetaVO webserviceMeta = getMasterDataFacade()
            .getMetaData(NuclosEntity.WEBSERVICE.getEntityName());
    CollectableComparison condition = SearchConditionUtils.newMDComparison(webserviceMeta, "name",
            ComparisonOperator.EQUAL, serviceName);
    Collection<Object> foundService = getMasterDataIds(NuclosEntity.WEBSERVICE.getEntityName(),
            new CollectableSearchExpression(condition));

    if (foundService.size() == 0) {
        throw new NuclosBusinessRuleException("Kein Service gefunden");
    } else if (foundService.size() > 1) {
        throw new NuclosBusinessRuleException("Mehrere Services gefunden");
    }

    Object serviceId = foundService.iterator().next();
    MasterDataVO service = getMasterData(NuclosEntity.WEBSERVICE.getEntityName(), (Integer) serviceId);

    String username = (String) service.getField("user");
    String password = (String) service.getField("password");
    String url = (String) service.getField("host");

    try {
        //          stub._getServiceClient().getOptions().setTo(new EndpointReference(url));
        Class<?> clzzEndpointReference = stub.getClass().getClassLoader()
                .loadClass("org.apache.axis2.addressing.EndpointReference");
        Object serviceClient = stub.getClass().getMethod("_getServiceClient").invoke(stub);
        Object serviceClientOptions = serviceClient.getClass().getMethod("getOptions").invoke(serviceClient);
        serviceClientOptions.getClass().getMethod("setTo", clzzEndpointReference).invoke(serviceClientOptions,
                clzzEndpointReference.getConstructor(url.getClass()).newInstance(url));
        Method mthdSetProperty = serviceClientOptions.getClass().getMethod("setProperty", String.class,
                Object.class);

        Boolean useProxy = (Boolean) service.getField("useproxy");
        String authentificationType = (String) service.getField("authtype");
        String encoding = (String) service.getField("encoding");

        //PROXY
        if (useProxy != null) {
            if (useProxy) {
                String proxyName = (String) service.getField("proxyname");
                Integer proxyPort = (Integer) service.getField("proxyport");
                String proxyusername = (String) service.getField("proxyuser");
                String proxypasswort = (String) service.getField("proxypassword");
                String proxydomain = (String) service.getField("proxydomain");

                // PROXY Configuration
                //               ProxyProperties proxyConfig = new ProxyProperties();
                Class<?> clzzProxyProperties = stub.getClass().getClassLoader()
                        .loadClass("org.apache.axis2.transport.http.HttpTransportProperties$ProxyProperties");
                Object proxyConfig = clzzProxyProperties.newInstance();

                if (!StringUtils.isNullOrEmpty(proxyName))
                    //                  proxyConfig.setProxyName(proxyName);
                    clzzProxyProperties.getMethod("setProxyName", String.class).invoke(proxyConfig, proxyName);
                if (proxyPort != null)
                    //                  proxyConfig.setProxyPort(proxyPort);
                    clzzProxyProperties.getMethod("setProxyPort", int.class).invoke(proxyConfig, proxyPort);
                if (!StringUtils.isNullOrEmpty(proxyusername))
                    //                  proxyConfig.setUserName(proxyusername);
                    clzzProxyProperties.getMethod("setUserName", String.class).invoke(proxyConfig,
                            proxyusername);
                if (!StringUtils.isNullOrEmpty(proxypasswort))
                    //                  proxyConfig.setPassWord(proxypasswort);
                    clzzProxyProperties.getMethod("setPassWord", String.class).invoke(proxyConfig,
                            proxypasswort);
                if (!StringUtils.isNullOrEmpty(proxydomain))
                    //                  proxyConfig.setDomain(proxydomain);
                    clzzProxyProperties.getMethod("setDomain", String.class).invoke(proxyConfig, proxydomain);

                //            stub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.PROXY, proxyConfig);
                mthdSetProperty.invoke(serviceClientOptions, "PROXY", proxyConfig);
                //            stub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_PROTOCOL_VERSION, org.apache.axis2.transport.http.HTTPConstants.HEADER_PROTOCOL_10);
                mthdSetProperty.invoke(serviceClientOptions, "__HTTP_PROTOCOL_VERSION__", "HTTP/1.0");
            }
        }

        // AUTHENTIFICATION
        //         HttpTransportProperties.Authenticator auth = null;
        Class<?> clzzAuthenticator = stub.getClass().getClassLoader()
                .loadClass("org.apache.axis2.transport.http.HttpTransportProperties$Authenticator");
        Object auth = null;
        if (!"NONE".equals(authentificationType)) {
            auth = clzzAuthenticator.newInstance();
            //            auth.setPreemptiveAuthentication(true);
            clzzAuthenticator.getMethod("setPreemptiveAuthentication", boolean.class).invoke(auth, true);

            if (password != null) {
                //               auth.setPassword(password);
                clzzAuthenticator.getMethod("setPassword", String.class).invoke(auth, password);
            }
            if (username != null) {
                //               auth.setUsername(username);
                clzzAuthenticator.getMethod("setUsername", String.class).invoke(auth, username);
            }
            //         stub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
            mthdSetProperty.invoke(serviceClientOptions, "_NTLM_DIGEST_BASIC_AUTHENTICATION_", auth);
        }

        if ("BASIC".equals(authentificationType)) {
            ArrayList<String> authSchema = new ArrayList<String>();
            //            authSchema.add(HttpTransportProperties.Authenticator.BASIC);
            authSchema.add("Basic");
            //            auth.setAuthSchemes(authSchema);
            clzzAuthenticator.getMethod("setAuthSchemes", List.class).invoke(auth, authSchema);
        } else if ("NTLM".equals(authentificationType)) {
            ArrayList<String> authSchema = new ArrayList<String>();
            //            authSchema.add(HttpTransportProperties.Authenticator.NTLM);
            authSchema.add("NTLM");
            //            auth.setAuthSchemes(authSchema);
            clzzAuthenticator.getMethod("setAuthSchemes", List.class).invoke(auth, authSchema);
        } else if ("DIGEST".equals(authentificationType)) {
            ArrayList<String> authSchema = new ArrayList<String>();
            //            authSchema.add(HttpTransportProperties.Authenticator.DIGEST);
            authSchema.add("Digest");
            //            auth.setAuthSchemes(authSchema);
            clzzAuthenticator.getMethod("setAuthSchemes", List.class).invoke(auth, authSchema);
        }

        // ENCODING
        if ("UTF-8".equals(encoding))
            //         stub._getServiceClient().getOptions().setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, "UTF-8");
            mthdSetProperty.invoke(serviceClientOptions, "CHARACTER_SET_ENCODING", "UTF-8");
        else if ("UTF-16".equals(encoding))
            //         stub._getServiceClient().getOptions().setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, "UTF-16");
            mthdSetProperty.invoke(serviceClientOptions, "CHARACTER_SET_ENCODING", "UTF-16");
        else if ("ISO-8859".equals(encoding))
            //         stub._getServiceClient().getOptions().setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, "ISO-8859");
            mthdSetProperty.invoke(serviceClientOptions, "CHARACTER_SET_ENCODING", "ISO-8859");
        else if ("ISO-8859-1".equals(encoding))
            //         stub._getServiceClient().getOptions().setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING, "ISO-8859-1");
            mthdSetProperty.invoke(serviceClientOptions, "CHARACTER_SET_ENCODING", "ISO-8859-1");

    } catch (Exception e) {
        throw new NuclosFatalException(e);
    }
}

From source file:org.kantega.dogmaticmvc.web.DefaultMethodParameterFactory.java

@Override
public Object[] getMethodParameters(Method method, HttpServletRequest req, HttpServletResponse resp,
        Map<String, Object> model) {
    Object[] params = new Object[method.getParameterTypes().length];

    try {//  w  w  w.ja  v a 2s.c  om
        for (int i = 0; i < method.getParameterTypes().length; i++) {
            Class parameterType = method.getParameterTypes()[i];
            RequestParam requestParam;
            SessionAttr sessionAttr;
            if (parameterType == ServletContext.class) {
                params[i] = servletContext;
            } else if (parameterType == HttpServletRequest.class) {
                params[i] = req;
            } else if (parameterType == HttpSession.class) {
                params[i] = req.getSession(true);
            } else if (parameterType == HttpServletResponse.class) {
                params[i] = resp;
            } else if (parameterType == OutputStream.class) {
                params[i] = resp.getOutputStream();
            } else if (parameterType == PrintWriter.class) {
                params[i] = resp.getWriter();
            } else if (parameterType == ServletOutputStream.class) {
                params[i] = resp.getOutputStream();
            } else if (parameterType == ApplicationContext.class && applicationContext != null) {
                params[i] = applicationContext;
            } else if (parameterType == Map.class) {
                params[i] = model;
            } else if ((requestParam = getParamAnnotation(method, i, RequestParam.class)) != null) {
                String name = requestParam.value();
                String value = req.getParameter(name);
                if (value == null) {
                    if (requestParam.required()) {
                        throw new IllegalArgumentException("Missing required parameter '" + name + "'");
                    }
                    params[i] = null;
                } else if (parameterType == String.class) {
                    params[i] = value;
                } else if (parameterType == int.class || parameterType == Integer.class) {
                    params[i] = Integer.parseInt(value);
                } else if (parameterType == long.class || parameterType == Long.class) {
                    params[i] = Long.parseLong(value);
                } else if (parameterType == boolean.class || parameterType == Boolean.class) {
                    params[i] = Boolean.parseBoolean(value);
                } else {
                    throw new RuntimeException("Unknown parameter type " + parameterType);
                }
            } else if ((sessionAttr = getParamAnnotation(method, i, SessionAttr.class)) != null) {
                String name = sessionAttr.value();
                Object value = req.getSession(true).getAttribute(name);
                if (value == null) {
                    if (sessionAttr.required()) {
                        throw new IllegalArgumentException("Missing required session attribute '" + name + "'");
                    }
                    params[i] = null;
                } else if (parameterType.isAssignableFrom(value.getClass())) {
                    params[i] = value;
                } else {
                    throw new ServletException("Session value of type " + value.getClass()
                            + "is not assignalble to parameter " + name + " of type " + parameterType);
                }
            } else if (applicationContext != null
                    && applicationContext.getBeansOfType(parameterType).size() > 1) {
                throw new ServletException(
                        "Spring context has multiple beans of type " + parameterType.getName());
            } else if (applicationContext != null
                    && applicationContext.getBeansOfType(parameterType).size() == 1) {
                params[i] = applicationContext.getBeansOfType(parameterType).values().iterator().next();
            } else if (applicationContext != null
                    && applicationContext.getBeansOfType(parameterType).size() == 0) {
                throw new ServletException("Unknown parameter type " + parameterType.getName());
            } else {
                throw new ServletException("Unknown parameter type " + parameterType.getName());
            }

        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    return params;
}

From source file:jsondb.JsonDBTemplate.java

public void join(String sourceID, String sourceCollection, String destID, String destiCollection) {
    Object sourceObj = this.findById(sourceID, sourceCollection);
    Object destObj = this.findById(destID, destiCollection);

    Class sc = sourceObj.getClass();
    Class dc = destObj.getClass();

    String scgettermethod = null;
    String scsettermethod = null;
    String destCollection = null;
    String destField = null;/*www  .j  av a 2 s.  c  om*/
    String dcgettermethod = null;
    String dcsettermethod = null;

    Field[] fields = sc.getDeclaredFields();
    for (Field field : fields) {
        DBRef d = field.getDeclaredAnnotation(DBRef.class);
        if (d != null) {
            // destCollection = d.destcollection();
            destField = d.destfieldname();
            // sourcefield = field.getName();
            scgettermethod = "get" + field.getName();
            scsettermethod = "set" + field.getName();
            Method[] methods = sc.getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equalsIgnoreCase(scsettermethod)) {
                    scsettermethod = method.getName();
                }
                if (method.getName().equalsIgnoreCase(scgettermethod)) {
                    scgettermethod = method.getName();
                }
            }
        }
    }
    try {
        Method s = sc.getDeclaredMethod(scgettermethod, (Class[]) null);
        String p = (String) s.invoke(sourceObj);

        Field df = dc.getDeclaredField(destField);
        dcgettermethod = "get" + df.getName();
        dcsettermethod = "set" + df.getName();
        Method[] methods = dc.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equalsIgnoreCase(dcsettermethod)) {
                dcsettermethod = method.getName();
            }
            if (method.getName().equalsIgnoreCase(dcgettermethod)) {
                dcgettermethod = method.getName();
            }
        }
        if (p == null) {
            String rs = UUID.randomUUID().toString();
            Method sm = sc.getDeclaredMethod(scsettermethod, rs.getClass());
            sm.invoke(sourceObj, rs);

            Method dm = dc.getDeclaredMethod(dcsettermethod, rs.getClass());
            dm.invoke(destObj, rs);
        } else {
            Method d = dc.getDeclaredMethod(dcsettermethod, p.getClass());
            d.invoke(destObj, p);
        }
        this.upsert(sourceObj);
        this.upsert(destObj);

    } catch (NoSuchMethodException ex) {
        Logger.error("NoSuchMethodExeption");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.error("SecurityException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.error("IllegalAccessException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.error("IllegalArgumentException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.error("InvokationTargetException");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchFieldException ex) {
        Logger.error("Feld not found");
        java.util.logging.Logger.getLogger(JsonDBTemplate.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.reloadCollection(destCollection);
    this.reloadCollection(sourceCollection);
}

From source file:org.apache.myfaces.webapp.filter.PortletMultipartRequestWrapper.java

private void parseRequest() {
    if (cacheFileSizeErrors) {
        fileUpload = new PortletChacheFileSizeErrorsFileUpload();
    } else {/*from  w  w  w  .j  a  va  2s.  c  o  m*/
        fileUpload = new PortletFileUpload();
    }

    fileUpload.setSizeMax(maxSize);
    fileUpload.setFileSizeMax(maxFileSize);

    //fileUpload.setSizeThreshold(thresholdSize);

    if (repositoryPath != null && repositoryPath.trim().length() > 0) {
        //fileUpload.setRepositoryPath(repositoryPath);
        fileUpload.setFileItemFactory(new DiskFileItemFactory(thresholdSize, new File(repositoryPath)));
    } else {
        fileUpload.setFileItemFactory(
                new DiskFileItemFactory(thresholdSize, new File(System.getProperty("java.io.tmpdir"))));
    }

    String charset = request.getCharacterEncoding();
    fileUpload.setHeaderEncoding(charset);

    List requestParameters = null;

    try {
        if (cacheFileSizeErrors) {
            requestParameters = ((PortletChacheFileSizeErrorsFileUpload) fileUpload)
                    .parseRequestCatchingFileSizeErrors(request, fileUpload);
        } else {
            requestParameters = fileUpload.parseRequest(request);
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // Since commons-fileupload does not allow to continue processing files
        // if this exception is thrown, we can't do anything else.
        // So, the current request is rejected and we can't restore state, so 
        // this request is dealt like a new request, but note that caching the params
        // below it is possible to detect if the current request has been aborted
        // or not.
        // Note that if cacheFileSizeErrors is true, this is not thrown, so the request
        // is not aborted unless other different error occur.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "fileSizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxFileSize));

        if (log.isWarnEnabled())
            log.warn("FileSizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // This exception is thrown when the max request size has been reached.
        // In this case, the current request is rejected. The current 
        // request is dealt like a new request, but note that caching the params below
        // params it is possible to detect if the current request has been aborted
        // or not.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "sizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxSize));

        if (log.isWarnEnabled())
            log.warn("SizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadException fue) {
        if (log.isErrorEnabled())
            log.error("Exception while uploading file.", fue);

        requestParameters = Collections.EMPTY_LIST;
    }

    parametersMap = new HashMap(requestParameters.size());
    fileItems = new HashMap();

    for (Iterator iter = requestParameters.iterator(); iter.hasNext();) {
        FileItem fileItem = (FileItem) iter.next();

        if (fileItem.isFormField()) {
            String name = fileItem.getFieldName();

            // The following code avoids commons-fileupload charset problem.
            // After fixing commons-fileupload, this code should be
            //
            //     String value = fileItem.getString();
            //
            String value = null;
            if (charset == null) {
                value = fileItem.getString();
            } else {
                try {
                    value = new String(fileItem.get(), charset);
                } catch (UnsupportedEncodingException e) {
                    value = fileItem.getString();
                }
            }

            addTextParameter(name, value);
        } else { // fileItem is a File
            if (fileItem.getName() != null) {
                fileItems.put(fileItem.getFieldName(), fileItem);
            }
        }
    }

    //Add the query string paramters
    for (Iterator it = request.getParameterMap().entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();

        Object value = entry.getValue();

        if (value instanceof String[]) {
            String[] valuesArray = (String[]) entry.getValue();
            for (int i = 0; i < valuesArray.length; i++) {
                addTextParameter((String) entry.getKey(), valuesArray[i]);
            }
        } else if (value instanceof String) {
            String strValue = (String) entry.getValue();
            addTextParameter((String) entry.getKey(), strValue);
        } else if (value != null)
            throw new IllegalStateException("value of type : " + value.getClass() + " for key : "
                    + entry.getKey() + " cannot be handled.");

    }
}

From source file:com.impetus.ankush2.cassandra.monitor.CassandraClusterMonitor.java

private void insertdata() {
    try {/*w ww .j  av  a2 s.c om*/
        String ksName = (String) parameterMap.get("keyspace");
        String cfName = (String) parameterMap.get("columnfamily");
        Map<String, Object> fields = (Map<String, Object>) parameterMap.get("fields");
        String cassandraHome = componentConfig.getHomeDir();
        String fileName = cassandraHome + "insertdatascript";
        for (String host : CassandraUtils.getCassandraActiveNodes(componentConfig.getNodes().keySet())) {
            String connectionPort = getRpcPort(cassandraHome, host);
            if (componentConfig.getVersion().contains("2.1.")) {
                connectionPort = getNativeTransportPort(cassandraHome, host);
            }
            String cmdFileContent2 = "echo \"INSERT INTO " + ksName + "." + cfName + " (";

            for (String field : fields.keySet()) {
                cmdFileContent2 += field + ",";
            }
            cmdFileContent2 = cmdFileContent2.replaceAll(",$", "");
            cmdFileContent2 += ") VALUES (";
            for (Object field : fields.values()) {
                if (field.getClass().equals(String.class)) {
                    field = "'" + field + "'";
                }
                cmdFileContent2 += field + ",";
            }
            cmdFileContent2 = cmdFileContent2.replaceAll(",$", "");
            cmdFileContent2 += ");\" > " + fileName + " ; " + cassandraHome + "bin/cqlsh " + host + " "
                    + connectionPort + " -f " + fileName;

            System.out.println("cmdFileContent2: " + cmdFileContent2);
            SSHConnection sshConnection = new SSHConnection(host, clusterConf.getAuthConf().getUsername(),
                    clusterConf.getAuthConf().isUsingPassword() ? clusterConf.getAuthConf().getPassword()
                            : clusterConf.getAuthConf().getPrivateKey(),
                    clusterConf.getAuthConf().isUsingPassword());
            sshConnection.exec(cmdFileContent2);

            if (sshConnection.getExitStatus() != 0) {
                throw new AnkushException("Unable to create Column family");
            } else {
                logger.info("Column family created");
            }
            return;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opencms.configuration.CmsVfsConfiguration.java

/**
 * @see org.opencms.configuration.I_CmsXmlConfiguration#generateXml(org.dom4j.Element)
 *//*from   w w w  .j a  v a2  s  . c  o m*/
public Element generateXml(Element parent) {

    if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
        m_resourceManager = OpenCms.getResourceManager();
        m_xmlContentTypeManager = OpenCms.getXmlContentTypeManager();
        m_defaultFiles = OpenCms.getDefaultFiles();
    }

    // generate vfs node and subnodes
    Element vfs = parent.addElement(N_VFS);

    // add resources main element
    Element resources = vfs.addElement(N_RESOURCES);

    // add resource loader
    Element resourceloadersElement = resources.addElement(N_RESOURCELOADERS);
    for (I_CmsResourceLoader loader : m_resourceManager.getLoaders()) {
        // add the loader node
        Element loaderNode = resourceloadersElement.addElement(N_LOADER);
        loaderNode.addAttribute(A_CLASS, loader.getClass().getName());
        CmsParameterConfiguration loaderConfiguration = loader.getConfiguration();
        if (loaderConfiguration != null) {
            loaderConfiguration.appendToXml(loaderNode);
        }
    }

    // add resource types
    Element resourcetypesElement = resources.addElement(N_RESOURCETYPES);
    List<I_CmsResourceType> resourceTypes = new ArrayList<I_CmsResourceType>();
    if (m_resourceManager.getResTypeUnknownFolder() != null) {
        resourceTypes.add(m_resourceManager.getResTypeUnknownFolder());
    }
    if (m_resourceManager.getResTypeUnknownFile() != null) {
        resourceTypes.add(m_resourceManager.getResTypeUnknownFile());
    }
    resourceTypes.addAll(m_resourceManager.getResourceTypes());
    generateResourceTypeXml(resourcetypesElement, resourceTypes, false);

    // add VFS content collectors
    Element collectorsElement = resources.addElement(N_COLLECTORS);
    for (I_CmsResourceCollector collector : m_resourceManager.getRegisteredContentCollectors()) {
        collectorsElement.addElement(N_COLLECTOR).addAttribute(A_CLASS, collector.getClass().getName())
                .addAttribute(A_ORDER, String.valueOf(collector.getOrder()));
    }

    Element namegeneratorElement = resources.addElement(N_NAMEGENERATOR);
    String nameGeneratorClass = m_resourceManager.getNameGenerator().getClass().getName();
    namegeneratorElement.addAttribute(A_CLASS, nameGeneratorClass);

    // add MIME types
    Element mimeTypesElement = resources.addElement(N_MIMETYPES);
    for (CmsMimeType type : m_resourceManager.getMimeTypes()) {
        mimeTypesElement.addElement(N_MIMETYPE).addAttribute(A_EXTENSION, type.getExtension())
                .addAttribute(A_TYPE, type.getType());
    }

    // add relation types
    Element relationTypesElement = resources.addElement(N_RELATIONTYPES);
    for (CmsRelationType type : m_resourceManager.getRelationTypes()) {
        relationTypesElement.addElement(N_RELATIONTYPE).addAttribute(A_NAME, type.getName())
                .addAttribute(A_TYPE, type.getType());
    }

    // HTML converter configuration
    boolean writeConfig = false;
    for (CmsHtmlConverterOption converter : m_resourceManager.getHtmlConverters()) {
        if (!converter.isDefault()) {
            // found a non default converter configuration, set flag to write configuration
            writeConfig = true;
            break;
        }
    }
    if (writeConfig) {
        // configuration is written because non default options were found
        Element htmlConvertersElement = resources.addElement(N_HTML_CONVERTERS);
        for (CmsHtmlConverterOption converter : m_resourceManager.getHtmlConverters()) {
            Element converterElement = htmlConvertersElement.addElement(N_HTML_CONVERTER).addAttribute(A_NAME,
                    converter.getName());
            converterElement.addAttribute(A_CLASS, converter.getClassName());
        }
    }

    // add default file names
    Element defaultFileElement = vfs.addElement(N_DEFAULTFILES);
    for (String element : m_defaultFiles) {
        defaultFileElement.addElement(N_DEFAULTFILE).addAttribute(A_NAME, element);
    }

    // add translation rules
    Element translationsElement = vfs.addElement(N_TRANSLATIONS);

    // file translation rules
    Element fileTransElement = translationsElement.addElement(N_FILETRANSLATIONS).addAttribute(A_ENABLED,
            String.valueOf(m_fileTranslationEnabled));
    for (String translation : m_fileTranslations) {
        fileTransElement.addElement(N_TRANSLATION).setText(translation);
    }

    // folder translation rules
    Element folderTransElement = translationsElement.addElement(N_FOLDERTRANSLATIONS).addAttribute(A_ENABLED,
            String.valueOf(m_folderTranslationEnabled));
    for (String translation : m_folderTranslations) {
        folderTransElement.addElement(N_TRANSLATION).setText(translation);
    }

    // XSD translation rules
    Element xsdTransElement = translationsElement.addElement(N_XSDTRANSLATIONS).addAttribute(A_ENABLED,
            String.valueOf(m_xsdTranslationEnabled));
    for (String translation : m_xsdTranslations) {
        xsdTransElement.addElement(N_TRANSLATION).setText(translation);
    }

    // XML content configuration
    Element xmlContentsElement = vfs.addElement(N_XMLCONTENT);

    // XML widgets
    Element xmlWidgetsElement = xmlContentsElement.addElement(N_WIDGETS);
    for (String widget : m_xmlContentTypeManager.getRegisteredWidgetNames()) {
        Element widgetElement = xmlWidgetsElement.addElement(N_WIDGET).addAttribute(A_CLASS, widget);
        String alias = m_xmlContentTypeManager.getRegisteredWidgetAlias(widget);
        if (alias != null) {
            widgetElement.addAttribute(A_ALIAS, alias);
        }
        String defaultConfiguration = m_xmlContentTypeManager.getWidgetDefaultConfiguration(widget);
        if (CmsStringUtil.isNotEmpty(defaultConfiguration)) {
            widgetElement.addAttribute(A_CONFIGURATION, defaultConfiguration);
        }
    }

    // XML content types 
    Element xmlSchemaTypesElement = xmlContentsElement.addElement(N_SCHEMATYPES);
    for (I_CmsXmlSchemaType type : m_xmlContentTypeManager.getRegisteredSchemaTypes()) {
        I_CmsWidget widget = m_xmlContentTypeManager.getWidgetDefault(type.getTypeName());
        xmlSchemaTypesElement.addElement(N_SCHEMATYPE).addAttribute(A_CLASS, type.getClass().getName())
                .addAttribute(A_DEFAULTWIDGET, widget.getClass().getName());
    }

    // return the vfs node
    return vfs;
}

From source file:edu.si.services.beans.cameratrap.UnifiedCameraTrapIngestRoutesTest.java

/**
 * Testing the MODS datastream is created and has the correct field values in the UnifiedCameraTrapAddMODSDataStream route
 * @throws Exception/*  w  w  w . ja  v a 2  s .com*/
 */
@Test
public void addMODSDatastream_Test() throws Exception {
    //RouteId and endpoint uri
    String routeId = "UnifiedCameraTrapAddMODSDataStream";
    String routeURI = "direct:addMODSDataStream";

    File MODS_DatastreamTestFile = new File(testDataDir + "/DatastreamTestFiles/MODS/valid_MODS.xml");

    String MODS_DatastreamExpected = FileUtils.readFileToString(MODS_DatastreamTestFile);

    //the header thats used for the Unified_ManifestImage.xsl param
    headers.put("imageid", "d18981s1i1");

    //manually setting the FITSCreatedDate header
    headers.put("FITSCreatedDate", "2016:02:13 12:11:26");

    //Configure and use adviceWith to mock for testing purpose
    context.getRouteDefinition(routeId).adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {

            //Remove the setheader definition for FITSCreatedDate we are manually passing this header in already
            //weaveByType(SetHeaderDefinition.class).selectFirst().remove();
            //set the mockEndpoint result and stop the route before adding the MODS datastream to fedora
            weaveByToString(".*fedora:addDatastream.*").before()
                    .log(LoggingLevel.DEBUG, "uct.test", "============ BODY ============\n${body}")
                    .to("mock:result").stop();
        }
    });

    mockEndpoint = getMockEndpoint("mock:result");

    // set mock expectations
    mockEndpoint.expectedMessageCount(1);
    mockEndpoint.expectedBodyReceived().body().isEqualTo(MODS_DatastreamExpected);
    mockEndpoint.expectedBodiesReceived(MODS_DatastreamExpected);

    template.sendBodyAndHeaders(routeURI, "d18981s1i1.JPG", headers);

    String resultBody = mockEndpoint.getExchanges().get(0).getIn().getBody(String.class);

    log.debug("expectedBody:\n" + MODS_DatastreamExpected + "\nresultBody:\n" + resultBody);

    log.debug("expectedBody Type:\n" + MODS_DatastreamExpected.getClass() + "\nresultBody Type:\n"
            + resultBody.getClass());

    assertEquals("mock:result Body containing MODS datastream xml assertEquals failed!",
            MODS_DatastreamExpected, resultBody);

    assertMockEndpointsSatisfied();

}