/**
   * Retrieves representation of an instance of org.azrul.epice.rest.service.RetrivePasswordResource
   *
   * @return an instance of java.lang.String
   */
  @POST
  @Produces("application/xml")
  public String getXml() {
    // TODO return proper representation object
    XStream writer = new XStream();
    writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
    writer.alias("RetrievePasswordResponse", RetrievePasswordResponse.class);

    XStream reader = new XStream();
    reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
    reader.alias("RetrievePasswordRequest", RetrievePasswordRequest.class);

    RetrievePasswordResponse errorResponse = new RetrievePasswordResponse();
    List<String> errors = new ArrayList<String>();
    errors.add("MODIFY PASSWORD ERROR");
    errorResponse.setErrors(errors);

    MultivaluedMap<String, String> params = context.getQueryParameters();

    try {
      String request = URLDecoder.decode(params.getFirst("REQUEST"), "UTF-8");
      RetrievePasswordRequest oRequest = (RetrievePasswordRequest) reader.fromXML(request);
      RetrievePasswordResponse oResponse = doService(oRequest);
      return URLEncoder.encode(writer.toXML(oResponse), "UTF-8");
    } catch (UnsupportedEncodingException ex) {
      Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      return writer.toXML(errorResponse);
    }
  }
Example #2
0
  public static void marshal(APIRequest request, Object responseRoot, Writer writer)
      throws FatalException, IOException {

    // get the javascript callback, if present
    String jsCallback = null;
    if (request != null) {
      try {
        jsCallback = request.getParameter(Constants.Request.JSCALLBACK, false);
      } catch (InvalidParameterException e) {
        // it's okay to not have one
      }
    }

    // get an xstream using a json dirver
    XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
    xstream.setMode(XStream.NO_REFERENCES);

    // alias top-level types
    xstream.alias("response", ResponseType.class);

    // first write out the jscallback method name
    if (!StringUtil.isNullOrEmpty(jsCallback)) {
      writer.write(jsCallback + "(");
    }

    // write the json to our writer
    // NOTE: all element names will be camel case and not cased as in JAXB
    xstream.marshal(responseRoot, new JsonWriter(writer));

    // close off the method if jscallback was given
    if (!StringUtil.isNullOrEmpty(jsCallback)) {
      writer.write(")");
    }
  }
  public XmlProjectDescriptorSerializer(boolean postProcess) {
    xstream = new XStream(new DomDriver());
    xstream.ignoreUnknownElements();
    xstream.omitField(ProjectDescriptor.class, "id"); // This field was deprecated
    xstream.omitField(ProjectDescriptor.class, "log");
    xstream.omitField(ProjectDescriptor.class, "classLoader");
    xstream.omitField(ProjectDescriptor.class, "projectFolder");
    xstream.omitField(Module.class, "properties"); // properties doesn't supported by rules.xml
    xstream.omitField(Module.class, "wildcardName"); // runtime properties
    xstream.omitField(Module.class, "wildcardRulesRootPath"); // runtime properties
    xstream.omitField(Module.class, "project"); // runtime properties

    xstream.setMode(XStream.NO_REFERENCES);

    xstream.aliasType(PROJECT_DESCRIPTOR_TAG, ProjectDescriptor.class);
    xstream.aliasType(MODULE_TAG, Module.class);
    xstream.aliasType(DEPENDENCY_TAG, ProjectDependencyDescriptor.class);
    xstream.aliasType(PATH_TAG, PathEntry.class);
    xstream.aliasType(PROPERTY_TAG, Property.class);
    xstream.aliasField(
        PROPERTIES_FILE_NAME_PATTERN, ProjectDescriptor.class, "propertiesFileNamePattern");
    xstream.aliasField(
        PROPERTIES_FILE_NAME_PROCESSOR, ProjectDescriptor.class, "propertiesFileNameProcessor");
    xstream.addDefaultImplementation(HashSet.class, Collection.class);
    xstream.alias("value", String.class);

    xstream.useAttributeFor(PathEntry.class, "path");
    xstream.aliasField("rules-root", Module.class, "rulesRootPath");
    xstream.aliasField(METHOD_FILTER_TAG, Module.class, "methodFilter");
    xstream.registerConverter(new StringValueConverter());

    this.postProcess = postProcess;
  }
Example #4
0
  private String statusList(Map<String, String> parameters) throws Exception {
    WorkflowStatus[] list =
        studioController.getWorkflowStatuses(sessionUid, Long.parseLong(parameters.get("uid")));
    WorkflowStatusDefinition[] results = new WorkflowStatusDefinition[list.length];
    int ind = 0;
    for (WorkflowStatus it : list) {
      WorkflowStatusDefinition n = new WorkflowStatusDefinition();
      n.setPosition(ind);
      n.setWorkflowStatus(it);
      WorkflowStatusManager[] mn =
          studioController.getWorkflowStatusManagers(sessionUid, it.getUid());
      n.setWorkflowStatusManagers(mn);
      results[ind] = n;
      ind++;
    }
    XStream xml = new XStream(new DomDriver());
    XStream xstream =
        new XStream(
            new JettisonMappedXmlDriver() {

              public HierarchicalStreamWriter createWriter(Writer writer) {
                return new JsonWriter(writer, "".toCharArray(), "", JsonWriter.DROP_ROOT_MODE);
              }
            });
    xstream.aliasField(
        "securityEntityName", WorkflowStatusManager.class, "localSecurityEntityName");
    xstream.aliasField(
        "securityEntitySource", WorkflowStatusManager.class, "localSecurityEntitySource");
    xstream.aliasField(
        "securityEntityType", WorkflowStatusManager.class, "localSecurityEntityType");
    xstream.aliasField("workflowStatusUid", WorkflowStatusManager.class, "localWorkflowStatusUid");
    xstream.setMode(XStream.NO_REFERENCES);
    String jsonResp = xstream.toXML(results);
    return jsonResp;
  }
 public XstreamSolutionDaoImpl() {
   // TODO From Xstream 1.3.3 that KeySorter will be the default. See
   // http://jira.codehaus.org/browse/XSTR-363
   xStream =
       new XStream(
           new PureJavaReflectionProvider(new FieldDictionary(new NativeFieldKeySorter())));
   xStream.setMode(XStream.ID_REFERENCES);
 }
Example #6
0
 public XmlSolverConfigurer() {
   // TODO From Xstream 1.3.3 that KeySorter will be the default. See
   // http://jira.codehaus.org/browse/XSTR-363
   xStream =
       new XStream(
           new PureJavaReflectionProvider(new FieldDictionary(new NativeFieldKeySorter())));
   xStream.setMode(XStream.ID_REFERENCES);
   Annotations.configureAliases(xStream, LocalSearchSolverConfig.class);
 }
Example #7
0
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");

    XStream xstream = new XStream(new JettisonMappedXmlDriver());
    xstream.setMode(XStream.NO_REFERENCES);
    xstream.alias("product", Product.class);
    resp.getWriter().write(xstream.toXML(new Product("Orange", 137, 10.5)));
    resp.getWriter().close();
  }
Example #8
0
  public static XStream getConfiguredXStream(XStream xs) {
    xs.setMode(XStream.NO_REFERENCES);

    xs.alias("gwcQuotaConfiguration", DiskQuotaConfig.class);
    xs.alias("layerQuotas", List.class);
    xs.alias("LayerQuota", LayerQuota.class);
    xs.alias("Quota", Quota.class);
    xs.registerConverter(new QuotaXSTreamConverter());
    return xs;
  }
Example #9
0
 private static XStream getJsonXstream() {
   XStream xstream = new XStream(new JettisonMappedXmlDriver());
   xstream.setMode(XStream.NO_REFERENCES);
   xstream.alias("config", ConfigurationHolder.class);
   xstream.addImplicitCollection(ConfigurationHolder.class, "messageParameters");
   xstream.alias("messages", MessageParameters.class);
   xstream.addImplicitCollection(MessageParameters.class, "plurals");
   xstream.alias("plurals", PluralDefinitions.class);
   return xstream;
 }
  protected String marshallAdvisory(final DataStructure ds, String transformation) {

    StringWriter buffer = new StringWriter();
    HierarchicalStreamWriter out;
    if (transformation.toLowerCase(Locale.ENGLISH).endsWith("json")) {
      out = new JettisonMappedXmlDriver().createWriter(buffer);
    } else {
      out = new PrettyPrintWriter(buffer);
    }

    XStream xstream = getXStream();
    xstream.setMode(XStream.NO_REFERENCES);
    xstream.aliasPackage("", "org.apache.activemq.command");
    xstream.marshal(ds, out);
    return buffer.toString();
  }
Example #11
0
  public void readUsers() {
    XStream xstream = new XStream();
    xstream.setMode(XStream.NO_REFERENCES);

    users = (ArrayList<User>) xstream.fromXML(new File("files/xml/user.xml"));
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String datasetId = req.getParameter("DatasetId");
    String format = req.getParameter("format");
    String fileName = (System.getProperty("java.io.tmpdir") + datasetId + ".csv");
    OutputStream out = resp.getOutputStream();

    switch (DownloadFormats.valueOf(format)) {
      case CSV:
        {
          resp.addHeader("Content-Disposition", "attachment;filename=" + datasetId + ".csv");

          List<ArrayList<String>> csvLines = getCSVFormat(datasetId);
          String separator = ",";
          StringBuilder fileString = new StringBuilder();
          String newline = System.getProperty("line.separator");
          for (int i = 0; i < csvLines.size(); i++) {
            ArrayList<String> row = csvLines.get(i);
            String rowString = concatValuesWithSeparator(row, separator);
            fileString = fileString.append(rowString).append(newline);
          }

          out.write(fileString.toString().getBytes());
        }

        break;
      case XML:
        {
          resp.addHeader("Content-Disposition", "attachment;filename=" + datasetId + ".xml");
          List<ArrayList<String>> entries = getCSVFormat(datasetId);

          XStream xStream = new XStream();

          String xml = xStream.toXML(entries);

          out.write(xml.getBytes());
        }
        break;
      case JSON:
        {
          resp.addHeader("Content-Disposition", "attachment;filename=" + datasetId + ".json");

          List<ArrayList<String>> entries = getCSVFormat(datasetId);

          XStream xstream = new XStream(new JettisonMappedXmlDriver());
          xstream.setMode(XStream.NO_REFERENCES);

          String json = xstream.toXML(entries);

          out.write(json.getBytes());
        }
        break;

      default:
        break;
    }

    out.flush();
  }
Example #13
0
 /**
  * Just creates a fresh XStream instance.
  *
  * @return
  */
 public XStream createForXml() {
   final XStream xstream = new XStream(new XppDriver());
   xstream.setMode(XStream.NO_REFERENCES);
   xstream.autodetectAnnotations(false);
   return xstream;
 }
Example #14
0
 static {
   XSTREAM.autodetectAnnotations(true);
   XSTREAM.setMode(XStream.NO_REFERENCES);
 }
Example #15
0
  protected XStream createXStream(ClassResolver resolver, ClassLoader classLoader) {
    if (xstreamDriver != null) {
      xstream = new XStream(xstreamDriver);
    } else {
      xstream = new XStream();
    }

    if (mode != null) {
      xstream.setMode(getModeFromString(mode));
    }

    ClassLoader xstreamLoader = xstream.getClassLoader();
    if (classLoader != null && xstreamLoader instanceof CompositeClassLoader) {
      ((CompositeClassLoader) xstreamLoader).add(classLoader);
    }

    try {
      if (this.implicitCollections != null) {
        for (Entry<String, String[]> entry : this.implicitCollections.entrySet()) {
          for (String name : entry.getValue()) {
            xstream.addImplicitCollection(resolver.resolveMandatoryClass(entry.getKey()), name);
          }
        }
      }

      if (this.aliases != null) {
        for (Entry<String, String> entry : this.aliases.entrySet()) {
          xstream.alias(entry.getKey(), resolver.resolveMandatoryClass(entry.getValue()));
          // It can turn the auto-detection mode off
          xstream.processAnnotations(resolver.resolveMandatoryClass(entry.getValue()));
        }
      }

      if (this.omitFields != null) {
        for (Entry<String, String[]> entry : this.omitFields.entrySet()) {
          for (String name : entry.getValue()) {
            xstream.omitField(resolver.resolveMandatoryClass(entry.getKey()), name);
          }
        }
      }

      if (this.converters != null) {
        for (String name : this.converters) {
          Class<Converter> converterClass = resolver.resolveMandatoryClass(name, Converter.class);
          Converter converter;

          Constructor<Converter> con = null;
          try {
            con = converterClass.getDeclaredConstructor(new Class[] {XStream.class});
          } catch (Exception e) {
            // swallow as we null check in a moment.
          }
          if (con != null) {
            converter = con.newInstance(xstream);
          } else {
            converter = converterClass.newInstance();
            try {
              Method method = converterClass.getMethod("setXStream", new Class[] {XStream.class});
              if (method != null) {
                ObjectHelper.invokeMethod(method, converter, xstream);
              }
            } catch (Throwable e) {
              // swallow, as it just means the user never add an XStream setter, which is optional
            }
          }

          xstream.registerConverter(converter);
        }
      }

      addDefaultPermissions(xstream);
      if (this.permissions != null) {
        // permissions ::= pterm (',' pterm)*   # consits of one or more terms
        // pterm       ::= aod? wterm           # each term preceded by an optional sign
        // aod         ::= '+' | '-'            # indicates allow or deny where allow if omitted
        // wterm       ::= a class name with optional wildcard characters
        addPermissions(xstream, permissions);
      }
    } catch (Exception e) {
      throw new RuntimeException("Unable to build XStream instance", e);
    }

    return xstream;
  }
 public XStreamSolutionFileIO() {
   xStream = new XStream();
   xStream.setMode(XStream.ID_REFERENCES);
 }
  /**
   * Configure the XStream instance with this marshaller's bean properties.
   *
   * @param xstream the {@code XStream} instance
   */
  protected void configureXStream(XStream xstream) {
    if (this.converters != null) {
      for (int i = 0; i < this.converters.length; i++) {
        if (this.converters[i] instanceof Converter) {
          xstream.registerConverter((Converter) this.converters[i], i);
        } else if (this.converters[i] instanceof SingleValueConverter) {
          xstream.registerConverter((SingleValueConverter) this.converters[i], i);
        } else {
          throw new IllegalArgumentException(
              "Invalid ConverterMatcher [" + this.converters[i] + "]");
        }
      }
    }

    if (this.marshallingStrategy != null) {
      xstream.setMarshallingStrategy(this.marshallingStrategy);
    }
    if (this.mode != null) {
      xstream.setMode(this.mode);
    }

    try {
      if (this.aliases != null) {
        Map<String, Class<?>> classMap = toClassMap(this.aliases);
        for (Map.Entry<String, Class<?>> entry : classMap.entrySet()) {
          xstream.alias(entry.getKey(), entry.getValue());
        }
      }
      if (this.aliasesByType != null) {
        Map<String, Class<?>> classMap = toClassMap(this.aliasesByType);
        for (Map.Entry<String, Class<?>> entry : classMap.entrySet()) {
          xstream.aliasType(entry.getKey(), entry.getValue());
        }
      }
      if (this.fieldAliases != null) {
        for (Map.Entry<String, String> entry : this.fieldAliases.entrySet()) {
          String alias = entry.getValue();
          String field = entry.getKey();
          int idx = field.lastIndexOf('.');
          if (idx != -1) {
            String className = field.substring(0, idx);
            Class<?> clazz = ClassUtils.forName(className, this.beanClassLoader);
            String fieldName = field.substring(idx + 1);
            xstream.aliasField(alias, clazz, fieldName);
          } else {
            throw new IllegalArgumentException("Field name [" + field + "] does not contain '.'");
          }
        }
      }
    } catch (ClassNotFoundException ex) {
      throw new IllegalStateException("Failed to load specified alias class", ex);
    }

    if (this.useAttributeForTypes != null) {
      for (Class<?> type : this.useAttributeForTypes) {
        xstream.useAttributeFor(type);
      }
    }
    if (this.useAttributeFor != null) {
      for (Map.Entry<?, ?> entry : this.useAttributeFor.entrySet()) {
        if (entry.getKey() instanceof String) {
          if (entry.getValue() instanceof Class) {
            xstream.useAttributeFor((String) entry.getKey(), (Class<?>) entry.getValue());
          } else {
            throw new IllegalArgumentException(
                "'useAttributesFor' takes Map<String, Class> when using a map key of type String");
          }
        } else if (entry.getKey() instanceof Class) {
          Class<?> key = (Class<?>) entry.getKey();
          if (entry.getValue() instanceof String) {
            xstream.useAttributeFor(key, (String) entry.getValue());
          } else if (entry.getValue() instanceof List) {
            @SuppressWarnings("unchecked")
            List<Object> listValue = (List<Object>) entry.getValue();
            for (Object element : listValue) {
              if (element instanceof String) {
                xstream.useAttributeFor(key, (String) element);
              }
            }
          } else {
            throw new IllegalArgumentException(
                "'useAttributesFor' property takes either Map<Class, String> "
                    + "or Map<Class, List<String>> when using a map key of type Class");
          }
        } else {
          throw new IllegalArgumentException(
              "'useAttributesFor' property takes either a map key of type String or Class");
        }
      }
    }

    if (this.implicitCollections != null) {
      for (Map.Entry<Class<?>, String> entry : this.implicitCollections.entrySet()) {
        String[] collectionFields = StringUtils.commaDelimitedListToStringArray(entry.getValue());
        for (String collectionField : collectionFields) {
          xstream.addImplicitCollection(entry.getKey(), collectionField);
        }
      }
    }
    if (this.omittedFields != null) {
      for (Map.Entry<Class<?>, String> entry : this.omittedFields.entrySet()) {
        String[] fields = StringUtils.commaDelimitedListToStringArray(entry.getValue());
        for (String field : fields) {
          xstream.omitField(entry.getKey(), field);
        }
      }
    }

    if (this.annotatedClasses != null) {
      xstream.processAnnotations(this.annotatedClasses);
    }
    if (this.autodetectAnnotations) {
      xstream.autodetectAnnotations(true);
    }
  }
 public static XMLConfig parse(File input) {
   XStream stream = new XStream();
   stream.setMode(XStream.NO_REFERENCES);
   stream.processAnnotations(XMLConfig.class);
   return (XMLConfig) stream.fromXML(input);
 }
  /**
   * Get configured xstream object.
   *
   * @return {@link XStream}
   */
  private static XStream getXStream() {

    final XStream xStream = new XStream(new DomDriver());

    xStream.alias("customer", CustomerEntity.class);
    xStream.omitField(CustomerEntity.class, "orders");
    xStream.omitField(CustomerEntity.class, "address");
    xStream.omitField(CustomerEntity.class, "shops");
    xStream.omitField(CustomerEntity.class, "coupons");
    xStream.alias("wishlist", CustomerWishListEntity.class);
    xStream.alias("customerAv", AttrValueEntityCustomer.class);
    xStream.omitField(AttrValueEntityCustomer.class, "customer");
    xStream.alias("attribute", AttributeEntity.class);
    xStream.omitField(AttributeEntity.class, "etype");
    xStream.omitField(AttributeEntity.class, "attributeGroup");
    xStream.alias("address", AddressEntity.class);
    xStream.alias("customerShop", CustomerShopEntity.class);

    xStream.alias("payment", CustomerOrderPaymentEntity.class);

    xStream.alias("carrier", CarrierEntity.class);
    xStream.omitField(CarrierEntity.class, "carrierSla");
    xStream.omitField(CarrierEntity.class, "shops");
    xStream.alias("carrierSla", CarrierSlaEntity.class);

    xStream.alias("order", CustomerOrderEntity.class);
    xStream.omitField(CustomerOrderEntity.class, "shop");
    xStream.alias("orderLine", CustomerOrderDetEntity.class);
    xStream.omitField(CustomerOrderDetEntity.class, "customerOrder");
    xStream.alias("orderDelivery", CustomerOrderDeliveryEntity.class);
    xStream.omitField(CustomerOrderDeliveryEntity.class, "customerOrder");
    xStream.alias("deliveryLine", CustomerOrderDeliveryDetEntity.class);
    xStream.omitField(CustomerOrderDeliveryDetEntity.class, "delivery");

    xStream.alias("shop", ShopEntity.class);
    xStream.alias("shopurl", ShopUrlEntity.class);

    xStream.alias("pair", Pair.class);
    xStream.alias("orderDto", CustomerOrderDTOImpl.class);
    xStream.alias("orderDeliveryDto", CustomerOrderDeliveryDTOImpl.class);
    xStream.alias("orderLineDto", CustomerOrderDeliveryDetailDTOImpl.class);

    xStream.alias("shopDto", ShopDTOImpl.class);
    xStream.alias("shopAvDto", AttrValueShopDTOImpl.class);

    xStream.alias("inventoryDto", InventoryDTOImpl.class);

    xStream.registerConverter(
        new Converter() {

          @Override
          public void marshal(
              final Object source,
              final HierarchicalStreamWriter writer,
              final MarshallingContext context) {
            if (source == null) {
              writer.setValue("");
            } else {
              GregorianCalendar calendar = new GregorianCalendar();
              calendar.setTime((Date) source);
              try {
                writer.setValue(
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar).toXMLFormat());
              } catch (DatatypeConfigurationException e) {
                writer.setValue("");
              }
            }
          }

          @Override
          public Object unmarshal(
              final HierarchicalStreamReader reader, final UnmarshallingContext context) {
            return null; // not needed
          }

          @Override
          public boolean canConvert(final Class type) {
            return Date.class.isAssignableFrom(type);
          }
        });

    xStream.registerConverter(
        new Converter() {
          @Override
          public void marshal(
              final Object source,
              final HierarchicalStreamWriter writer,
              final MarshallingContext context) {
            if (((AbstractPersistentCollection) source).wasInitialized()) {
              context.convertAnother(new ArrayList((Collection) source));
            }
          }

          @Override
          public Object unmarshal(
              final HierarchicalStreamReader reader, final UnmarshallingContext context) {
            return null; // not needed
          }

          @Override
          public boolean canConvert(final Class type) {
            return PersistentBag.class == type
                || PersistentList.class == type
                || PersistentSet.class == type;
          }
        });

    xStream.setMode(XStream.NO_REFERENCES);

    return xStream;
  }
 /**
  * Return an Advisory message as a JSON formatted string
  *
  * @param ds the DataStructure instance that is being marshaled.
  * @return the JSON marshaled form of the given DataStructure instance.
  */
 protected String marshallAdvisory(final DataStructure ds) {
   XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
   xstream.setMode(XStream.NO_REFERENCES);
   xstream.aliasPackage("", "org.apache.activemq.command");
   return xstream.toXML(ds);
 }