Example usage for java.lang Class getPackage

List of usage examples for java.lang Class getPackage

Introduction

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

Prototype

public Package getPackage() 

Source Link

Document

Gets the package of this class.

Usage

From source file:org.j2free.servlet.EntityAdminServlet.java

/**
 *
 * @param request/*from  w w  w  .  j a  v  a 2s .c o  m*/
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Controller controller = Controller.get(); // Get the controller associated with the current thread;

    String uri = request.getRequestURI();
    uri = uri.replaceFirst(".*?/(list|find|inspect|create|save|update|delete)", "$1"); // chop off the part before what we care about
    String path[] = uri.split("/");

    log.debug(uri);
    log.debug("path.length = " + path.length);

    if (path.length < 1) {
        log.debug("too little path info " + uri);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    RequestDispatcher rd = null;

    if (path[0].equals("list")) {
        log.debug("in list");
        if (path.length < 2) {
            log.debug("too few parts for list");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            int start = ServletUtils.getIntParameter(request, "start", 0);
            int limit = ServletUtils.getIntParameter(request, "limit", 100);

            List entities;
            if (path.length == 3) {
                String[] stringIds = path[2].split(",");
                Object[] ignoredIds = new Object[stringIds.length];

                Class idType = marshaller.getIdType();

                // NOTE: this will only work with integer entityIds
                if (idType == Integer.class) {
                    for (int i = 0; i < stringIds.length; i++)
                        ignoredIds[i] = Integer.parseInt(stringIds[i]);
                } else if (idType == String.class) {
                    for (int i = 0; i < stringIds.length; i++)
                        ignoredIds[i] = stringIds[i];
                } else if (idType == Long.class) {
                    for (int i = 0; i < stringIds.length; i++)
                        ignoredIds[i] = Long.parseLong(stringIds[i]);
                }

                entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName()),
                        Restrictions.not(Restrictions.in(marshaller.getIdName(), ignoredIds)));
            } else
                entities = controller.listByCriterions(klass, start, limit, Order.asc(marshaller.getIdName()));

            TreeMap<String, Object> entityMap = new TreeMap<String, Object>();
            for (Object obj : entities) {
                entityMap.put(marshaller.extractId(obj).toString(), obj);
            }

            request.setAttribute("start", start);
            request.setAttribute("limit", limit);

            request.setAttribute("total", controller.count(klass));

            request.setAttribute("simpleName", klass.getSimpleName());
            request.setAttribute("package", klass.getPackage().getName() + ".");
            request.setAttribute("entities", entityMap);

            if (ServletUtils.getBooleanParameter(request, "selector", false))
                rd = request.getRequestDispatcher(Dispatch.ENTITY_SELECTOR);
            else
                rd = request.getRequestDispatcher(Dispatch.ENTITY_LIST);

        } catch (Exception e) {
            log.error("Error listing entities", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    } else if (path[0].equals("find") || path[0].equals("inspect")) {
        log.debug("in find");
        if (path.length < 3) {
            log.debug("too few parts for find");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2]));
            request.setAttribute("entity", entity);
            request.setAttribute("entityId", marshaller.extractId(entity));
            request.setAttribute("fields", marshaller.marshallOut(entity, true));

            if (path[0].equals("find"))
                rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT);
            else
                rd = request.getRequestDispatcher(Dispatch.ENTITY_INSPECT);

        } catch (Exception e) {
            log.error("error finding entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    } else if (path[0].equals("create")) {
        log.debug("in create");
        if (path.length < 2) {
            log.debug("too few parts for create");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Constructor zeroArgsConst = klass.getConstructor();
            if (!zeroArgsConst.isAccessible())
                zeroArgsConst.setAccessible(true);

            Object entity = zeroArgsConst.newInstance();
            request.setAttribute("simpleName", klass.getSimpleName());
            request.setAttribute("package", klass.getPackage().getName() + ".");
            request.setAttribute("fields", marshaller.marshallOut(entity, true));

            rd = request.getRequestDispatcher(Dispatch.ENTITY_CREATE);

        } catch (Exception e) {
            log.error("error creating entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    } else if (path[0].equals("save")) {
        log.debug("in save");

        if (path.length < 2) {
            log.debug("too few parts for save");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        Marshaller marshaller = null;

        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = klass.newInstance();

            entity = marshaller.marshallIn(entity, request.getParameterMap(), controller);

            controller.persist(entity, true);

            if (controller.hasErrors()) {
                response.getWriter().println(controller.getErrorsAsString("<br />", true));
                return;
            } else {
                response.setStatus(HttpServletResponse.SC_CREATED);

                // need this to display dates in the DB stored format
                entity = controller.findPrimaryKey(klass, marshaller.extractId(entity));

                request.setAttribute("entity", entity);
                request.setAttribute("entityId", marshaller.extractId(entity));
                request.setAttribute("fields", marshaller.marshallOut(entity, true));

                rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT);
            }

        } catch (MarshallingException e) {
            log.error("error saving entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().println(e.getMessage());
            return;
        } catch (Exception e) {
            log.error("error saving entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

    } else if (path[0].equals("update")) {
        log.debug("in update");

        if (path.length < 3) {
            log.debug("too few parts for update");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2]));

            entity = marshaller.marshallIn(entity, request.getParameterMap(), controller);

            controller.merge(entity);

            if (controller.hasErrors()) {
                response.getWriter().println(controller.getErrorsAsString("<br />", true));
                return;
            } else {
                response.setStatus(HttpServletResponse.SC_CREATED);

                // need this to display dates in the DB stored format
                entity = controller.findPrimaryKey(klass, marshaller.extractId(entity));

                request.setAttribute("entity", entity);
                request.setAttribute("entityId", marshaller.extractId(entity));
                request.setAttribute("fields", marshaller.marshallOut(entity, true));

                rd = request.getRequestDispatcher(Dispatch.ENTITY_EDIT);
            }

        } catch (MarshallingException e) {
            log.error("error saving entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().println(e.getMessage());
            return;
        } catch (Exception e) {
            log.error("error updating entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

    } else if (path[0].equals("delete")) {

        log.debug("in delete");

        if (path.length < 3) {
            log.debug("too few parts for delete");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        try {
            Class klass = entityLookup.get(path[1]);

            if (klass == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().println("Could not find class for entity type: " + path[1]);
                return;
            }

            Marshaller marshaller = ReflectionMarshaller.getForClass(klass);

            Object entity = controller.findPrimaryKey(klass, marshaller.asIdType(path[2]));

            controller.remove(entity);
            entity = null;
            controller.flush();

            if (controller.hasErrors()) {
                response.getWriter().println(controller.getErrorsAsString("<br />", true));
                return;
            } else {
                response.setStatus(HttpServletResponse.SC_CREATED);
                return;
            }

        } catch (Exception e) {
            log.error("error updating entity", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

    } else {
        log.debug("Don't know what to do!");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    CharArrayWrapper responseWrapper = new CharArrayWrapper((HttpServletResponse) response);
    rd.forward(request, responseWrapper);

    String responseString = responseWrapper.toString().replaceAll("\n", " ").replaceAll("\\s{2,}", " ")
            .replaceAll("> ", ">").replaceAll(" <", "<").replaceAll(" />", "/>");
    response.setContentLength(responseString.length());
    response.setContentType("text/javascript");

    PrintWriter out = response.getWriter();
    out.write(responseString);
    out.flush();
    out.close();
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* gets the packagename of a given object.
*
* @param  obj the object to retrieve the package name from.
* @return the packagename./*from  www  .  j a v a 2 s .  co m*/
*/
static public String getPackageName(Object obj) throws Exception {
    Class c = null;
    if (obj instanceof Class) {
        c = (Class) obj;
    } else {
        c = obj.getClass();
    }
    return c.getPackage().getName();
}

From source file:com.evolveum.midpoint.prism.marshaller.BeanUnmarshaller.java

private <T> T unmarshalInternal(@NotNull XNode xnode, @NotNull Class<T> beanClass, @NotNull ParsingContext pc)
        throws SchemaException {
    if (beanClass == null) {
        throw new IllegalStateException("No bean class for node: " + xnode.debugDump());
    }// ww w  .  j  av  a 2s .  com
    if (xnode instanceof RootXNode) {
        XNode subnode = ((RootXNode) xnode).getSubnode();
        if (subnode == null) {
            throw new IllegalStateException("Couldn't parse " + beanClass
                    + " from a root node with a null content: " + xnode.debugDump());
        } else {
            return unmarshal(subnode, beanClass, pc);
        }
    } else if (!(xnode instanceof MapXNode) && !(xnode instanceof PrimitiveXNode)
            && !xnode.isHeterogeneousList()) {
        throw new IllegalStateException("Couldn't parse " + beanClass
                + " from non-map/non-primitive/non-hetero-list node: " + xnode.debugDump());
    }

    // only maps and primitives and heterogeneous lists after this point

    if (xnode instanceof PrimitiveXNode) {
        PrimitiveXNode<T> prim = (PrimitiveXNode) xnode;
        if (XmlTypeConverter.canConvert(beanClass)) {
            QName xsdType = XsdTypeMapper.toXsdType(beanClass);
            Object parsedValue = prim.getParsedValue(xsdType, beanClass);
            return postConvertUnmarshal(parsedValue, pc);
        } else if (beanClass.isEnum()) {
            return unmarshalEnumFromPrimitive(prim, beanClass, pc);
        }
        @SuppressWarnings("unchecked")
        PrimitiveUnmarshaller<T> unmarshaller = specialPrimitiveUnmarshallers.get(beanClass);
        if (unmarshaller != null) {
            return unmarshaller.unmarshal(prim, beanClass, pc);
        } else {
            return unmarshallPrimitive(prim, beanClass, pc);
        }
    } else {

        if (beanClass.getPackage() == null || beanClass.getPackage().getName().equals("java.lang")) {
            // We obviously have primitive data type, but we are asked to unmarshall from map xnode
            // NOTE: this may happen in XML when we have "empty" element, but it has some whitespace in it
            //       such as those troublesome newlines. This also happens if there is "empty" element
            //       but it contains an expression (so it is not PrimitiveXNode but MapXNode).
            // TODO: more robust implementation
            // TODO: look for "value" subnode with primitive value and try that.
            // This is most likely attempt to parse primitive value with dynamic expression.
            // Therefore just ignore entire map content.
            return null;
        }

        @SuppressWarnings("unchecked")
        MapUnmarshaller<T> unmarshaller = specialMapUnmarshallers.get(beanClass);
        if (xnode instanceof MapXNode && unmarshaller != null) { // TODO: what about special unmarshaller + hetero list?
            return unmarshaller.unmarshal((MapXNode) xnode, beanClass, pc);
        }
        return unmarshalFromMapOrHeteroList(xnode, beanClass, pc);
    }
}

From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java

private QName generateSchemaTypeforNameCommon(XmlSchemaSequence sequence, String partName, boolean isArrayType,
        Class<?> type, String classTypeName) throws Exception {
    QName schemaTypeName = typeTable.getSimpleSchemaTypeName(classTypeName);
    if (schemaTypeName == null) {
        schemaTypeName = generateSchema(type);
        if (isGenerateWrappedArrayTypes && isArrayType) {

            XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
            xmlSchemaElement.setName(partName + "Wrapper");
            xmlSchemaElement.setNillable(true);
            sequence.getItems().add(xmlSchemaElement);

            String complexTypeName = schemaTypeName.getLocalPart() + "Wrapper";
            XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);

            XmlSchemaComplexType xmlSchemaComplexType = null;
            if (xmlSchema.getTypeByName(complexTypeName) == null) {
                xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                xmlSchemaComplexType.setName(complexTypeName);

                xmlSchema.getItems().add(xmlSchemaComplexType);
                xmlSchema.getSchemaTypes().add(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                        xmlSchemaComplexType);
                addContentToMethodSchemaType(xmlSchemaSequence, schemaTypeName, "array", isArrayType);
            } else {
                xmlSchemaComplexType = (XmlSchemaComplexType) xmlSchema.getTypeByName(complexTypeName);
            }//from  w ww  . j  ava2 s.  c om

            xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
            xmlSchemaElement
                    .setSchemaTypeName(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()));

        } else {
            addContentToMethodSchemaType(sequence, schemaTypeName, partName, isArrayType);
        }

        String schemaNamespace;
        schemaNamespace = resolveSchemaNamespace(getQualifiedName(type.getPackage()));
        addImport(getXmlSchema(schemaNamespace), schemaTypeName);

    } else {
        if (isGenerateWrappedArrayTypes && isArrayType) {

            XmlSchemaElement xmlSchemaElement = new XmlSchemaElement();
            xmlSchemaElement.setName(partName + "Wrapper");
            xmlSchemaElement.setNillable(true);
            sequence.getItems().add(xmlSchemaElement);

            String complexTypeName = schemaTypeName.getLocalPart() + "Wrapper";
            XmlSchema xmlSchema = getXmlSchema(schemaTargetNameSpace);

            XmlSchemaComplexType xmlSchemaComplexType = null;
            if (xmlSchema.getTypeByName(complexTypeName) == null) {
                xmlSchemaComplexType = new XmlSchemaComplexType(xmlSchema);
                XmlSchemaSequence xmlSchemaSequence = new XmlSchemaSequence();
                xmlSchemaComplexType.setParticle(xmlSchemaSequence);
                xmlSchemaComplexType.setName(complexTypeName);

                xmlSchema.getItems().add(xmlSchemaComplexType);
                xmlSchema.getSchemaTypes().add(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()),
                        xmlSchemaComplexType);
                addContentToMethodSchemaType(xmlSchemaSequence, schemaTypeName, "array", isArrayType);
            } else {
                xmlSchemaComplexType = (XmlSchemaComplexType) xmlSchema.getTypeByName(complexTypeName);
            }

            xmlSchemaElement.setSchemaType(xmlSchemaComplexType);
            xmlSchemaElement
                    .setSchemaTypeName(new QName(schemaTargetNameSpace, xmlSchemaComplexType.getName()));

        } else {
            addContentToMethodSchemaType(sequence, schemaTypeName, partName, isArrayType);
        }

    }
    addImport(getXmlSchema(schemaTargetNameSpace), schemaTypeName);
    return schemaTypeName;
}

From source file:pcgen.io.PCGVer2Parser.java

private static String shortClassName(final Object o) {
    final Class<?> objClass = o.getClass();
    final String pckName = objClass.getPackage().getName();

    return objClass.getName().substring(pckName.length() + 1);
}

From source file:com.cloud.server.ManagementServerImpl.java

@Override
public String getVersion() {
    final Class<?> c = ManagementServer.class;
    String fullVersion = c.getPackage().getImplementationVersion();
    if (fullVersion != null && fullVersion.length() > 0) {
        return fullVersion;
    }//w  w  w. jav a2s. c  om

    return "unknown";
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Get the name of the application server [fleXive] is running on
 *
 * @return name of the application server [fleXive] is running on
 * @since 3.1//from w  ww . j  av  a 2  s . co  m
 */
public synchronized static String getApplicationServerName() {
    if (appserver != null)
        return appserver;
    if (System.getProperty("product.name") != null) {
        // Glassfish 2 / Sun AS
        String ver = System.getProperty("product.name");
        if (System.getProperty("com.sun.jbi.domain.name") != null)
            ver += " (Domain: " + System.getProperty("com.sun.jbi.domain.name") + ")";
        appserver = ver;
    } else if (System.getProperty("glassfish.version") != null) {
        // Glassfish 3+
        appserver = System.getProperty("glassfish.version");
    } else if (System.getProperty("jboss.home.dir") != null) {
        appserver = "JBoss (unknown version)";
        boolean found = false;
        try {
            final Class<?> cls = Class.forName("org.jboss.Version");
            Method m = cls.getMethod("getInstance");
            Object v = m.invoke(null);
            Method pr = cls.getMethod("getProperties");
            Map props = (Map) pr.invoke(v);
            String ver = inspectJBossVersionProperties(props);
            found = true;
            appserver = ver;
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        }
        if (!found) {
            // try JBoss 7 MBean lookup
            try {
                final ObjectName name = new ObjectName("jboss.as:management-root=server");
                final Object version = ManagementFactory.getPlatformMBeanServer().getAttribute(name,
                        "releaseVersion");
                if (version != null) {
                    appserver = "JBoss (" + version + ")";
                    found = true;
                }
            } catch (Exception e) {
                // ignore
            }
        }
        if (!found) {
            //try again with a JBoss 6.x specific locations
            try {
                final ClassLoader jbossCL = Class.forName("org.jboss.Main").getClassLoader();
                if (jbossCL.getResource(JBOSS6_VERSION_PROPERTIES) != null) {
                    Properties prop = new Properties();
                    prop.load(jbossCL.getResourceAsStream(JBOSS6_VERSION_PROPERTIES));
                    if (prop.containsKey("version.name")) {
                        appserver = inspectJBossVersionProperties(prop);
                        //noinspection UnusedAssignment
                        found = true;
                    }
                }
            } catch (ClassNotFoundException e) {
                //ignore
            } catch (IOException e) {
                //ignore
            }
        }
    } else if (System.getProperty("openejb.version") != null) {
        // try to get Jetty version
        String jettyVersion = "";
        try {
            final Class<?> cls = Class.forName("org.mortbay.jetty.Server");
            jettyVersion = " (Jetty " + cls.getPackage().getImplementationVersion() + ")";
        } catch (ClassNotFoundException e) {
            // no Jetty version...
        }
        appserver = "OpenEJB " + System.getProperty("openejb.version") + jettyVersion;
    } else if (System.getProperty("weblogic.home") != null) {
        String server = System.getProperty("weblogic.Name");
        String wlVersion = "";
        try {
            final Class<?> cls = Class.forName("weblogic.common.internal.VersionInfo");
            Method m = cls.getMethod("theOne");
            Object serverVersion = m.invoke(null);
            Method sv = m.invoke(null).getClass().getMethod("getImplementationVersion");
            wlVersion = " " + String.valueOf(sv.invoke(serverVersion));
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        if (StringUtils.isEmpty(server))
            appserver = "WebLogic" + wlVersion;
        else
            appserver = "WebLogic" + wlVersion + " (server: " + server + ")";
    } else if (System.getProperty("org.apache.geronimo.home.dir") != null) {
        String gVersion = "";
        try {
            final Class<?> cls = Class.forName("org.apache.geronimo.system.serverinfo.ServerConstants");
            Method m = cls.getMethod("getVersion");
            gVersion = " " + String.valueOf(m.invoke(null));
            m = cls.getMethod("getBuildDate");
            gVersion = gVersion + " (" + String.valueOf(m.invoke(null)) + ")";
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        appserver = "Apache Geronimo " + gVersion;
    } else {
        appserver = "unknown";
    }
    return appserver;
}

From source file:com.kodemore.utility.Kmu.java

/**
 * Return the package name of the class.
 *///  w w w.j  a  va2 s  .  c  o m
public static String getPackageName(Class<?> e) {
    if (e == null)
        return "null";

    return e.getPackage().getName();
}

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

public <T> T unmarshall(MapXNode xnode, Class<T> beanClass) throws SchemaException {

    if (PolyStringType.class.equals(beanClass)) {
        PolyString polyString = unmarshalPolyString(xnode);
        return (T) polyString; // violates the method interface but ... TODO fix it
    } else if (ProtectedStringType.class.equals(beanClass)) {
        ProtectedStringType protectedType = new ProtectedStringType();
        XNodeProcessorUtil.parseProtectedType(protectedType, xnode, prismContext);
        return (T) protectedType;
    } else if (ProtectedByteArrayType.class.equals(beanClass)) {
        ProtectedByteArrayType protectedType = new ProtectedByteArrayType();
        XNodeProcessorUtil.parseProtectedType(protectedType, xnode, prismContext);
        return (T) protectedType;
    } else if (SchemaDefinitionType.class.equals(beanClass)) {
        SchemaDefinitionType schemaDefType = unmarshalSchemaDefinitionType(xnode);
        return (T) schemaDefType;
    } else if (prismContext.getSchemaRegistry().determineDefinitionFromClass(beanClass) != null) {
        return (T) prismContext.getXnodeProcessor().parseObject(xnode).asObjectable();
    } else if (XmlAsStringType.class.equals(beanClass)) {
        // reading a string represented a XML-style content
        // used e.g. when reading report templates (embedded XML)
        // A necessary condition: there may be only one map entry.
        if (xnode.size() > 1) {
            throw new SchemaException("Map with more than one item cannot be parsed as a string: " + xnode);
        } else if (xnode.isEmpty()) {
            return (T) new XmlAsStringType();
        } else {//from  ww  w.jav  a 2 s.  c  o  m
            Map.Entry<QName, XNode> entry = xnode.entrySet().iterator().next();
            DomParser domParser = prismContext.getParserDom();
            String value = domParser.serializeToString(entry.getValue(), entry.getKey());
            return (T) new XmlAsStringType(value);
        }
    }
    T bean;
    Set<String> keysToParse; // only these keys will be parsed (null if all)
    if (SearchFilterType.class.isAssignableFrom(beanClass)) {
        keysToParse = Collections.singleton("condition"); // TODO fix this BRUTAL HACK - it is here because of c:ConditionalSearchFilterType
        bean = (T) unmarshalSearchFilterType(xnode, (Class<? extends SearchFilterType>) beanClass);
    } else {
        keysToParse = null;
        try {
            bean = beanClass.newInstance();
        } catch (InstantiationException e) {
            throw new SystemException("Cannot instantiate bean of type " + beanClass + ": " + e.getMessage(),
                    e);
        } catch (IllegalAccessException e) {
            throw new SystemException("Cannot instantiate bean of type " + beanClass + ": " + e.getMessage(),
                    e);
        }
    }

    if (ProtectedDataType.class.isAssignableFrom(beanClass)) {
        ProtectedDataType protectedDataType = null;
        if (bean instanceof ProtectedStringType) {
            protectedDataType = new ProtectedStringType();
        } else if (bean instanceof ProtectedByteArrayType) {
            protectedDataType = new ProtectedByteArrayType();
        } else {
            throw new SchemaException("Unexpected subtype of protected data type: " + bean.getClass());
        }
        XNodeProcessorUtil.parseProtectedType(protectedDataType, xnode, prismContext);
        return (T) protectedDataType;
    }

    for (Entry<QName, XNode> entry : xnode.entrySet()) {
        QName key = entry.getKey();
        if (keysToParse != null && !keysToParse.contains(key.getLocalPart())) {
            continue;
        }
        XNode xsubnode = entry.getValue();
        String propName = key.getLocalPart();
        Field field = inspector.findPropertyField(beanClass, propName);
        Method propertyGetter = null;
        if (field == null) {
            propertyGetter = inspector.findPropertyGetter(beanClass, propName);
        }

        Method elementMethod = null;
        Object objectFactory = null;
        if (field == null && propertyGetter == null) {
            // We have to try to find a more generic field, such as xsd:any or substitution element
            // check for global element definition first
            Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage());
            objectFactory = instantiateObjectFactory(objectFactoryClass);
            elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, propName);
            if (elementMethod == null) {
                // Check for "any" method
                elementMethod = inspector.findAnyMethod(beanClass);
                if (elementMethod == null) {
                    String m = "No field " + propName + " in class " + beanClass
                            + " (and no element method in object factory too)";
                    if (mode == XNodeProcessorEvaluationMode.COMPAT) {
                        LOGGER.warn("{}", m);
                        continue;
                    } else {
                        throw new SchemaException(m);
                    }
                }
                unmarshallToAny(bean, elementMethod, key, xsubnode);
                continue;

            }
            field = inspector.lookupSubstitution(beanClass, elementMethod);
            if (field == null) {
                // Check for "any" field
                field = inspector.findAnyField(beanClass);
                if (field == null) {
                    elementMethod = inspector.findAnyMethod(beanClass);
                    if (elementMethod == null) {
                        String m = "No field " + propName + " in class " + beanClass
                                + " (and no element method in object factory too)";
                        if (mode == XNodeProcessorEvaluationMode.COMPAT) {
                            LOGGER.warn("{}", m);
                            continue;
                        } else {
                            throw new SchemaException(m);
                        }
                    }
                    unmarshallToAny(bean, elementMethod, key, xsubnode);
                    continue;
                    //                  throw new SchemaException("No field "+propName+" in class "+beanClass+" (no suitable substitution and no 'any' field)");
                }
                unmarshallToAny(bean, field, key, xsubnode);
                continue;
            }
        }

        boolean storeAsRawType;
        if (elementMethod != null) {
            storeAsRawType = elementMethod.getAnnotation(Raw.class) != null;
        } else if (propertyGetter != null) {
            storeAsRawType = propertyGetter.getAnnotation(Raw.class) != null;
        } else {
            storeAsRawType = field.getAnnotation(Raw.class) != null;
        }

        String fieldName;
        if (field != null) {
            fieldName = field.getName();
        } else {
            fieldName = propName;
        }

        Method setter = inspector.findSetter(beanClass, fieldName);
        Method getter = null;
        boolean wrapInJaxbElement = false;
        Class<?> paramType = null;
        if (setter == null) {
            // No setter. But if the property is multi-value we need to look
            // for a getter that returns a collection (Collection<Whatever>)
            getter = inspector.findPropertyGetter(beanClass, fieldName);
            if (getter == null) {
                String m = "Cannot find setter or getter for field " + fieldName + " in " + beanClass;
                if (mode == XNodeProcessorEvaluationMode.COMPAT) {
                    LOGGER.warn("{}", m);
                    continue;
                } else {
                    throw new SchemaException(m);
                }
            }
            Class<?> getterReturnType = getter.getReturnType();
            if (!Collection.class.isAssignableFrom(getterReturnType)) {
                throw new SchemaException("Cannot find getter for field " + fieldName + " in " + beanClass
                        + " does not return collection, cannot use it to set value");
            }
            Type genericReturnType = getter.getGenericReturnType();
            Type typeArgument = getTypeArgument(genericReturnType,
                    "for field " + fieldName + " in " + beanClass + ", cannot determine collection type");
            //         System.out.println("type argument " + typeArgument);
            if (typeArgument instanceof Class) {
                paramType = (Class<?>) typeArgument;
            } else if (typeArgument instanceof ParameterizedType) {
                ParameterizedType paramTypeArgument = (ParameterizedType) typeArgument;
                Type rawTypeArgument = paramTypeArgument.getRawType();
                if (rawTypeArgument.equals(JAXBElement.class)) {
                    // This is the case of Collection<JAXBElement<....>>
                    wrapInJaxbElement = true;
                    Type innerTypeArgument = getTypeArgument(typeArgument, "for field " + fieldName + " in "
                            + beanClass + ", cannot determine collection type (inner type argument)");
                    if (innerTypeArgument instanceof Class) {
                        // This is the case of Collection<JAXBElement<Whatever>>
                        paramType = (Class<?>) innerTypeArgument;
                    } else if (innerTypeArgument instanceof WildcardType) {
                        // This is the case of Collection<JAXBElement<?>>
                        // we need to exctract the specific type from the factory method
                        if (elementMethod == null) {
                            // TODO: TEMPORARY CODE!!!!!!!!!! fix in 3.1 [med]
                            Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage());
                            objectFactory = instantiateObjectFactory(objectFactoryClass);
                            elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass,
                                    propName);
                            if (elementMethod == null) {
                                throw new IllegalArgumentException(
                                        "Wildcard type in JAXBElement field specification and no factory method found for field "
                                                + fieldName + " in " + beanClass
                                                + ", cannot determine collection type (inner type argument)");
                            }
                        }
                        Type factoryMethodGenericReturnType = elementMethod.getGenericReturnType();
                        Type factoryMethodTypeArgument = getTypeArgument(factoryMethodGenericReturnType,
                                "in factory method " + elementMethod + " return type for field " + fieldName
                                        + " in " + beanClass + ", cannot determine collection type");
                        if (factoryMethodTypeArgument instanceof Class) {
                            // This is the case of JAXBElement<Whatever>
                            paramType = (Class<?>) factoryMethodTypeArgument;
                            if (Object.class.equals(paramType) && !storeAsRawType) {
                                throw new IllegalArgumentException("Factory method " + elementMethod
                                        + " type argument is Object (and not @Raw) for field " + fieldName
                                        + " in " + beanClass + ", property " + propName);
                            }
                        } else {
                            throw new IllegalArgumentException(
                                    "Cannot determine factory method return type, got "
                                            + factoryMethodTypeArgument + " - for field " + fieldName + " in "
                                            + beanClass
                                            + ", cannot determine collection type (inner type argument)");
                        }
                    } else {
                        throw new IllegalArgumentException("Ejha! " + innerTypeArgument + " "
                                + innerTypeArgument.getClass() + " from " + getterReturnType + " from "
                                + fieldName + " in " + propName + " " + beanClass);
                    }
                } else {
                    // The case of Collection<Whatever<Something>>
                    if (rawTypeArgument instanceof Class) {
                        paramType = (Class<?>) rawTypeArgument;
                    } else {
                        throw new IllegalArgumentException("EH? Eh!? " + typeArgument + " "
                                + typeArgument.getClass() + " from " + getterReturnType + " from " + fieldName
                                + " in " + propName + " " + beanClass);
                    }
                }
            } else {
                throw new IllegalArgumentException(
                        "EH? " + typeArgument + " " + typeArgument.getClass() + " from " + getterReturnType
                                + " from " + fieldName + " in " + propName + " " + beanClass);
            }
        } else {
            Class<?> setterType = setter.getParameterTypes()[0];
            if (JAXBElement.class.equals(setterType)) {
                //               TODO some handling for the returned generic parameter types
                Type[] genericTypes = setter.getGenericParameterTypes();
                if (genericTypes.length != 1) {
                    throw new IllegalArgumentException("Too lazy to handle this.");
                }
                Type genericType = genericTypes[0];
                if (genericType instanceof ParameterizedType) {
                    Type actualType = getTypeArgument(genericType, "add some description");
                    if (actualType instanceof WildcardType) {
                        if (elementMethod == null) {
                            Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage());
                            objectFactory = instantiateObjectFactory(objectFactoryClass);
                            elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass,
                                    propName);
                        }
                        // This is the case of Collection<JAXBElement<?>>
                        // we need to exctract the specific type from the factory method
                        if (elementMethod == null) {
                            throw new IllegalArgumentException(
                                    "Wildcard type in JAXBElement field specification and no facotry method found for field "
                                            + fieldName + " in " + beanClass
                                            + ", cannot determine collection type (inner type argument)");
                        }
                        Type factoryMethodGenericReturnType = elementMethod.getGenericReturnType();
                        Type factoryMethodTypeArgument = getTypeArgument(factoryMethodGenericReturnType,
                                "in factory method " + elementMethod + " return type for field " + fieldName
                                        + " in " + beanClass + ", cannot determine collection type");
                        if (factoryMethodTypeArgument instanceof Class) {
                            // This is the case of JAXBElement<Whatever>
                            paramType = (Class<?>) factoryMethodTypeArgument;
                            if (Object.class.equals(paramType) && !storeAsRawType) {
                                throw new IllegalArgumentException("Factory method " + elementMethod
                                        + " type argument is Object (without @Raw) for field " + fieldName
                                        + " in " + beanClass + ", property " + propName);
                            }
                        } else {
                            throw new IllegalArgumentException(
                                    "Cannot determine factory method return type, got "
                                            + factoryMethodTypeArgument + " - for field " + fieldName + " in "
                                            + beanClass
                                            + ", cannot determine collection type (inner type argument)");
                        }
                    }
                }
                //               Class enclosing = paramType.getEnclosingClass();
                //               Class clazz = paramType.getClass();
                //               Class declaring = paramType.getDeclaringClass();
                wrapInJaxbElement = true;
            } else {
                paramType = setterType;
            }
        }

        if (Element.class.isAssignableFrom(paramType)) {
            // DOM!
            throw new IllegalArgumentException("DOM not supported in field " + fieldName + " in " + beanClass);
        }

        //check for subclasses???
        if (!storeAsRawType && xsubnode.getTypeQName() != null) {
            Class explicitParamType = getSchemaRegistry().determineCompileTimeClass(xsubnode.getTypeQName());
            if (explicitParamType == null) {
                explicitParamType = XsdTypeMapper.toJavaTypeIfKnown(xsubnode.getTypeQName());
            }

            if (explicitParamType != null) {
                paramType = explicitParamType;
            }
        }

        if (!(xsubnode instanceof ListXNode) && Object.class.equals(paramType) && !storeAsRawType) {
            throw new IllegalArgumentException(
                    "Object property (without @Raw) not supported in field " + fieldName + " in " + beanClass);
        }

        String paramNamespace = inspector.determineNamespace(paramType);

        boolean problem = false;
        Object propValue = null;
        Collection<Object> propValues = null;
        if (xsubnode instanceof ListXNode) {
            ListXNode xlist = (ListXNode) xsubnode;
            if (setter != null) {
                try {
                    propValue = convertSinglePropValue(xsubnode, fieldName, paramType, storeAsRawType,
                            beanClass, paramNamespace);
                } catch (SchemaException e) {
                    problem = processSchemaException(e, xsubnode);
                }
            } else {
                // No setter, we have to use collection getter
                propValues = new ArrayList<>(xlist.size());
                for (XNode xsubsubnode : xlist) {
                    try {
                        propValues.add(convertSinglePropValue(xsubsubnode, fieldName, paramType, storeAsRawType,
                                beanClass, paramNamespace));
                    } catch (SchemaException e) {
                        problem = processSchemaException(e, xsubsubnode);
                    }
                }
            }
        } else {
            try {
                propValue = convertSinglePropValue(xsubnode, fieldName, paramType, storeAsRawType, beanClass,
                        paramNamespace);
            } catch (SchemaException e) {
                problem = processSchemaException(e, xsubnode);
            }
        }

        if (setter != null) {
            try {
                setter.invoke(bean, prepareValueToBeStored(propValue, wrapInJaxbElement, objectFactory,
                        elementMethod, propName, beanClass));
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new SystemException("Cannot invoke setter " + setter + " on bean of type " + beanClass
                        + ": " + e.getMessage(), e);
            }
        } else if (getter != null) {
            Object getterReturn;
            Collection<Object> col;
            try {
                getterReturn = getter.invoke(bean);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new SystemException("Cannot invoke getter " + getter + " on bean of type " + beanClass
                        + ": " + e.getMessage(), e);
            }
            try {
                col = (Collection<Object>) getterReturn;
            } catch (ClassCastException e) {
                throw new SystemException("Getter " + getter + " on bean of type " + beanClass + " returned "
                        + getterReturn + " instead of collection");
            }
            if (propValue != null) {
                col.add(prepareValueToBeStored(propValue, wrapInJaxbElement, objectFactory, elementMethod,
                        propName, beanClass));
            } else if (propValues != null) {
                for (Object propVal : propValues) {
                    col.add(prepareValueToBeStored(propVal, wrapInJaxbElement, objectFactory, elementMethod,
                            propName, beanClass));
                }
            } else if (!problem) {
                throw new IllegalStateException("Strange. Multival property " + propName + " in " + beanClass
                        + " produced null values list, parsed from " + xnode);
            }
            checkJaxbElementConsistence(col);
        } else {
            throw new IllegalStateException("Uh? No setter nor getter.");
        }
    }

    if (prismContext != null && bean instanceof Revivable) {
        ((Revivable) bean).revive(prismContext);
    }

    return bean;
}