Example #1
0
  /** Default constructor. */
  private Modelica() {
    final String schemaPath =
        ScilabConstants.SCI.getAbsolutePath() + XcosConstants.XCOS_ETC + SCHEMA_FILENAME;

    JAXBContext jaxbContext;
    try {
      jaxbContext = JAXBContext.newInstance(MODEL_CLASS_PACKAGE);
      marshaller = jaxbContext.createMarshaller();
      unmarshaller = jaxbContext.createUnmarshaller();

      Schema schema =
          SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
              .newSchema(new File(schemaPath));

      marshaller.setSchema(schema);
      unmarshaller.setSchema(schema);

      /*
       * Customize the file to be handled by the xml2modelica and
       * modelicat tool.
       */
      marshaller.setProperty(Marshaller.JAXB_ENCODING, LATIN1_ENCODING);

      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    } catch (JAXBException e) {
      throw new RuntimeException(e);
    } catch (SAXException e) {
      Logger.getLogger(Modelica.class.getName()).severe(e.toString());
    }
  }
Example #2
0
  /**
   * Serialize this instance to a steam.
   *
   * <p>Default deserialization is pretty-printed but not schema-validated.
   *
   * @param out the stream for writing
   * @param validate whether to perform schema validation
   * @throws JAXBException if the steam can't be written to
   */
  public void marshal(final OutputStream out, final Boolean validate) throws JAXBException {
    try {
      // Create an empty DOM
      DOMResult intermediateResult = new DOMResult();

      // Marshal from JAXB to DOM
      Marshaller marshaller = /*BPMN_CONTEXT*/ newContext().createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      if (validate) {
        marshaller.setSchema(getBpmnSchema() /*BPMN_SCHEMA*/);
      }
      marshaller.marshal(new BpmnObjectFactory().createDefinitions(this), intermediateResult);

      // Apply the XSLT transformation, from DOM to the output stream
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer =
          transformerFactory.newTransformer(
              new StreamSource(
                  new java.io.StringBufferInputStream(
                      fixNamespacesXslt[0] + getTargetNamespace() + fixNamespacesXslt[1])));
      DOMSource finalSource = new DOMSource(intermediateResult.getNode());
      StreamResult finalResult = new StreamResult(out);
      transformer.transform(finalSource, finalResult);
    } catch (TransformerException e) {
      throw new JAXBException("Dodgy wrapped exception", e);
    } // TODO - create transformer elsewhere
  }
  /**
   * Convert a Quakeml 1.2 to XML.
   *
   * @param message the message to serialize.
   * @param out the outputstream where xml is written.
   * @param validate whether to validate the message being serialized (true) or not (false).
   * @throws JAXBException
   * @throws SAXException
   */
  public static synchronized void serialize(
      final Quakeml message, final OutputStream out, final boolean validate)
      throws JAXBException, SAXException {
    // to be thread safe, must create marshaller per call
    Marshaller marshaller = CONTEXT.createMarshaller();

    // use #getPreferredPrefix to override default JAXB namespaces
    marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", NAMESPACE_MAPPER);

    // don't include <?xml?>
    marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false);

    // because of how the quakeml schema is written, we have to do this bs
    // to convince JAXB marshall that quakeml can be used as a root element
    XmlType quakemlXmlType = Quakeml.class.getAnnotation(XmlType.class);
    JAXBElement<Quakeml> element =
        new JAXBElement<Quakeml>(
            new QName(quakemlXmlType.namespace(), "quakeml"), Quakeml.class, message);

    if (validate) {
      marshaller.setSchema(getSchema());
    }

    marshaller.marshal(element, out);
  }
 /**
  * Cenverte o objeto informado para uma String que representa o XML do objeto.
  *
  * @param <T> Tipo generico que informa a classe
  * @param object O objeto a ser convertido. A classe deste objeto deve conter as anotações de
  *     JAXB.
  * @param schemaLocation {@link URL} do schema.
  * @return
  * @throws JAXBException
  */
 @SuppressWarnings("unchecked")
 public static <T> String marshal(T object, URL schemaLocation) throws JAXBException {
   Class<T> objClass = (Class<T>) object.getClass();
   JAXBContext context = JAXBContext.newInstance(objClass);
   Marshaller marshaller = context.createMarshaller();
   StringWriter sWriter = new StringWriter();
   XmlSchema xmlSchema = objClass.getPackage().getAnnotation(XmlSchema.class);
   if (xmlSchema != null && xmlSchema.namespace() != null) {
     XmlType xmlType = objClass.getAnnotation(XmlType.class);
     if (xmlType != null && xmlType.name() != null) {
       QName qName = new QName(xmlSchema.namespace(), xmlType.name());
       JAXBElement<T> elem = new JAXBElement<T>(qName, objClass, object);
       if (schemaLocation != null) {
         SchemaFactory schemaFactory =
             SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
         try {
           Schema schema = schemaFactory.newSchema(schemaLocation);
           marshaller.setSchema(schema);
         } catch (SAXException e) {
           e.printStackTrace();
         }
       }
       marshaller.marshal(elem, sWriter);
       return sWriter.toString();
     } else {
       throw new JAXBException("The xmlType could not be identified in class annotation");
     }
   } else {
     throw new JAXBException("The namespace could not be identified from package-info class");
   }
 }
Example #5
0
 public static void marshal(
     JAXBContext jaxbContext, Schema schema, File xmlFile, Object jaxbElement)
     throws JAXBException, FileNotFoundException {
   Marshaller marshaller = jaxbContext.createMarshaller();
   marshaller.setSchema(schema);
   marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
   marshaller.marshal(jaxbElement, new FileOutputStream(xmlFile));
 }
Example #6
0
  /**
   * Marshalls a scenario object and writes into output XML file
   *
   * @throws JAXBException, SiriusException
   */
  public void marshallIntoXML(Scenario scenarioToWrite)
      throws JAXBException, FileNotFoundException, BeatsException {

    JAXBContext jaxbContext = JAXBContext.newInstance("edu.berkeley.path.beats.jaxb");
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setSchema(this.getSchema());
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    jaxbMarshaller.marshal(scenarioToWrite, new File(this.outputFileName));
  }
Example #7
0
 public static void export(long id, String filename)
     throws SiriusException, JAXBException, SAXException {
   com.relteq.sirius.simulator.Scenario scenario = ScenarioRestorer.getScenario(id);
   scenario.setSchemaVersion(com.relteq.sirius.Version.get().getSchemaVersion());
   JAXBContext jaxbc = JAXBContext.newInstance("com.relteq.sirius.jaxb");
   Marshaller mrsh = jaxbc.createMarshaller();
   SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
   mrsh.setSchema(sf.newSchema(ScenarioRestorer.class.getClassLoader().getResource("sirius.xsd")));
   mrsh.marshal(scenario, new File(filename));
 }
  /**
   * writes the MATSim4UrbanSim confing at the specified place using JAXB
   *
   * @param matsimConfigType config in MATSim4UrbanSim format
   * @throws UncheckedIOException
   */
  String writeConfigFileV2(MatsimConfigType matsimConfigType) throws UncheckedIOException {
    try {
      String destination = this.dummyPath + "/test_config.xml";
      BufferedWriter bw = IOUtils.getBufferedWriter(destination);

      String xsdPath = TempDirectoryUtil.createCustomTempDirectory("xsd");
      // init loadFile object: it downloads a xsd from matsim.org into a temp directory
      LoadFile loadFile =
          new LoadFile(
              InternalConstants.V2_MATSIM_4_URBANSIM_XSD_MATSIMORG,
              xsdPath,
              InternalConstants.V2_XSD_FILE_NAME);
      File file2XSD = loadFile.loadMATSim4UrbanSimXSD(); // trigger loadFile
      if (file2XSD == null || !file2XSD.exists()) {
        log.error("Did not find xml schema!");
        System.exit(1);
      }
      log.info("Using following xsd schema: " + file2XSD.getCanonicalPath());

      // crate a schema factory ...
      SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      // create a schema object via the given xsd to validate the MATSim xml config.
      Schema schema = schemaFactory.newSchema(file2XSD);

      JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
      Marshaller m = jaxbContext.createMarshaller();
      m.setSchema(schema);
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
      JAXBElement elem =
          new JAXBElement(new QName("", "matsim_config"), MatsimConfigType.class, matsimConfigType);
      // (this is because there is no XMLRootElemet annotation)
      m.marshal(elem, bw);

      return destination;

    } catch (JAXBException e) {
      e.printStackTrace();
      Assert.assertFalse(
          true); // otherwise the test neither returns "good" nor "bad" when there is an exception.
                 // kai, apr'13
    } catch (SAXException e) {
      e.printStackTrace();
      Assert.assertFalse(
          true); // otherwise the test neither returns "good" nor "bad" when there is an exception.
                 // kai, apr'13
    } catch (IOException e) {
      e.printStackTrace();
      Assert.assertFalse(
          true); // otherwise the test neither returns "good" nor "bad" when there is an exception.
                 // kai, apr'13
    }
    return null;
  }
Example #9
0
    Context(Class clazz) {
      try {
        jaxbContext = JAXBContext.newInstance(clazz);

        marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setSchema(null);

        unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setSchema(null);
      } catch (JAXBException e) {
        e.printStackTrace();
      }
    }
 /** marshall */
 public void marshall(T t, OutputStream outputStream) throws Exception {
   try {
     final JAXBContext jaxbContext = JAXBContext.newInstance(persistentClass);
     final Marshaller marshaller = jaxbContext.createMarshaller();
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
     marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
     if (this.schema != null) {
       marshaller.setSchema(this.schema);
     }
     marshaller.marshal(t, outputStream);
   } catch (final Exception e) {
     throw new Exception("Error marshalling", e);
   }
 }
  @Override
  protected void setUp() throws Exception {
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    InputStream schemaStream =
        Thread.currentThread().getContextClassLoader().getResourceAsStream(XSD_RESOURCE);
    Schema s = sf.newSchema(new StreamSource(schemaStream));

    marshaller = JAXBContextFactory.createContext(getClasses(), null).createMarshaller();
    marshaller.setSchema(s);

    child = new Child();
    child.setName("123456789");

    root = setupRootObject();
  }
 public static synchronized void marshal(Object jaxbElement, Object dst, Schema schema)
     throws CdsException {
   try {
     if (marshaller == null) {
       marshaller = getJAXBContext().createMarshaller();
       marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
     }
     marshaller.setSchema(schema);
     if (dst instanceof ContentHandler) {
       marshaller.marshal(jaxbElement, (ContentHandler) dst);
     } else if (dst instanceof OutputStream) {
       marshaller.marshal(jaxbElement, (OutputStream) dst);
     } else {
       throw new CdsException("Unsupported dst type: " + dst);
     }
   } catch (JAXBException e) {
     logger.error(e);
     throw new CdsException(e.getMessage());
   }
 }
Example #13
0
  @Override
  public String marshal(IxsiMessageType ixsi) {
    log.trace("Entered marshal...");

    try {
      JAXBElement<IxsiMessageType> outgoing = OBJECT_FACTORY.createIxsi(ixsi);
      Marshaller m = jaxbContext.createMarshaller();
      // Validate against the schema
      m.setSchema(schema);
      // Pretty print?
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
      // Drop the XML declaration?
      m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

      StringWriter stringWriter = new StringWriter();
      m.marshal(outgoing, stringWriter);
      return stringWriter.toString();

    } catch (JAXBException e) {
      throw new IxsiProcessingException(
          "Could not marshal outgoing message: " + ixsi.toString(), e);
    }
  }
  /**
   * @return A marshaller for converting document to XML. Never <code>null</code>.
   * @throws JAXBException In case of an error.
   */
  @Nonnull
  private Marshaller _createMarshaller() throws JAXBException {
    final Package aPackage = m_aType.getPackage();
    final JAXBContext aJAXBContext =
        useJAXBContextCache()
            ? JAXBContextCache.getInstance().getFromCache(aPackage)
            : JAXBContext.newInstance(aPackage.getName());

    // create an Unmarshaller
    final Marshaller aMarshaller = aJAXBContext.createMarshaller();
    if (m_aVEHFactory != null) {
      // Create and set the event handler
      m_aLastEventHandler = m_aVEHFactory.create(aMarshaller.getEventHandler());
      aMarshaller.setEventHandler(m_aLastEventHandler);
    } else m_aLastEventHandler = null;

    JAXBMarshallerUtils.setFormattedOutput(aMarshaller, m_bWriteFormatted);

    // Set XSD (if any)
    final Schema aValidationSchema = createValidationSchema();
    if (aValidationSchema != null) aMarshaller.setSchema(aValidationSchema);

    return aMarshaller;
  }
  /*
   * (non-Javadoc)
   *
   * @see com.atcloud.model.ModelService#start()
   */
  @Override
  public void start() throws ATCloudDataModelException {

    LOG.debug("Starting model service...");

    try {

      schema =
          SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
              .newSchema(
                  new Source[] {
                    new StreamSource(schemaFactorySourceLocator.getURL("common-types.xsd")),
                    new StreamSource(schemaFactorySourceLocator.getURL("configuration.xsd")),
                    new StreamSource(schemaFactorySourceLocator.getURL("flight.xsd")),
                    new StreamSource(schemaFactorySourceLocator.getURL("scenario.xsd")),
                    new StreamSource(schemaFactorySourceLocator.getURL("airport.xsd")),
                    new StreamSource(schemaFactorySourceLocator.getURL("airspace.xsd")),
                    new StreamSource(schemaFactorySourceLocator.getURL("user.xsd"))
                  });

      // schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
      // .newSchema(
      // new Source[] {
      // new StreamSource(xsdLocation + "/common-types.xsd"),
      // new StreamSource(xsdLocation + "/configuration.xsd"),
      // new StreamSource(xsdLocation + "/flight.xsd"),
      // new StreamSource(xsdLocation + "/scenario.xsd"),
      // new StreamSource(xsdLocation + "/airport.xsd"),
      // new StreamSource(xsdLocation + "/airspace.xsd"),
      // new StreamSource(xsdLocation + "/user.xsd") });

      // schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
      // .newSchema(
      // new Source[] {
      // new StreamSource(cl.getResource("/common-types.xsd").toURI()
      // .toString()),
      // new StreamSource(cl.getResource("/configuration.xsd").toURI()
      // .toString()),
      // new StreamSource(cl.getResource("/flight.xsd").toURI()
      // .toString()),
      // new StreamSource(cl.getResource("/scenario.xsd").toURI()
      // .toString()),
      // new StreamSource(cl.getResource("/airport.xsd").toURI()
      // .toString()),
      // new StreamSource(cl.getResource("/airspace.xsd").toURI()
      // .toString()),
      // new StreamSource(cl.getResource("/user.xsd").toURI()
      // .toString()) });

      ctx = JAXBContext.newInstance("com.atcloud.model", cl);

      marshaller = ctx.createMarshaller();

      marshaller.setSchema(schema);

      unmarshaller = ctx.createUnmarshaller();

      unmarshaller.setSchema(schema);

    } catch (SAXException e) {
      throw new ATCloudDataModelException(e.getLocalizedMessage(), e);

    } catch (JAXBException e) {
      throw new ATCloudDataModelException(e.getLocalizedMessage(), e);
    }

    LOG.info("Started model service.");
  }
Example #16
0
  public ResponseEntity<?> mint(Samples samples, boolean test, Principal user) {

    boolean isXMLValid = true;

    Schema schema = null;

    // 2. VALIDATE XML ====================================================

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
      URL schemaUrl = new URL(this.IGSN_CSIRO_XSD_URL);
      schema = sf.newSchema(schemaUrl);
    } catch (SAXException e) {
      e.printStackTrace();
      return new ResponseEntity<String>(
          "Failure retriving schema : " + e.getLocalizedMessage(), HttpStatus.BAD_REQUEST);
    } catch (MalformedURLException e) {
      log.error("URL malformed for schema location. Recheck config.properties file again.");
      return new ResponseEntity<String>(
          "Failure retriving schema : " + e.getLocalizedMessage(), HttpStatus.BAD_REQUEST);
    }

    try {
      JAXBContext jc = JAXBContext.newInstance(Samples.class);
      Marshaller marshaller = jc.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
      marshaller.setSchema(schema);
      marshaller.marshal(samples, new DefaultHandler());
    } catch (JAXBException e) {
      e.printStackTrace();
      isXMLValid = false;
      return new ResponseEntity<String>(
          "XML validation failed : " + e.getLocalizedMessage(), HttpStatus.BAD_REQUEST);
    }

    // 3. VALIDATE SUBNAMESPACE BASED ON USER NAME
    // =============================
    String usr = null;
    List<MintEventLog> mintEventLogs = new ArrayList<MintEventLog>();

    if (isXMLValid) {
      usr = user.getName();
      Set<Prefix> allowedPrefix = prefixEntityService.searchByUser(usr);

      for (Sample s : samples.getSample()) {
        MintEventLog mintEventLog = new MintEventLog(s.getSampleNumber().getValue());
        if (sampleStartsWithAllowedPrefix(allowedPrefix, s)) {
          if (s.getLogElement().getEvent().equals(EventType.SUBMITTED)
              || s.getLogElement().getEvent().equals(EventType.UPDATED)) {
            try {
              SimpleDateFormat metadataDateFormat =
                  new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssXXX");
              String igsn =
                  this.mintService.createRegistryXML(
                      s.getSampleNumber().getValue(),
                      s.getLandingPage(),
                      metadataDateFormat.format(new Date()),
                      test,
                      s.getLogElement().getEvent().value());
              mintEventLog.setMintLog(MintErrorCode.MINT_SUCCESS, null);
              mintEventLog.setHandle("http://hdl.handle.net/" + igsn);
            } catch (Exception e) {
              mintEventLog.setMintLog(MintErrorCode.MINT_FAILURE, e.getMessage());
              mintEventLog.setDatabaseLog(DatabaseErrorCode.NOT_ATTEMPTED, "");
              mintEventLogs.add(mintEventLog);
              continue;
            }
          }

          try {
            if (test) {
              sampleEntityService.testInsertSample(s, usr);
            } else if (s.getLogElement().getEvent().equals(EventType.SUBMITTED)) {
              sampleEntityService.insertSample(s, usr);
            } else if (s.getLogElement().getEvent().equals(EventType.DESTROYED)) {
              sampleEntityService.destroySample(s);
            } else if (s.getLogElement().getEvent().equals(EventType.DEPRECATED)) {
              sampleEntityService.deprecateSample(s);
            } else if (s.getLogElement().getEvent().equals(EventType.UPDATED)) {
              sampleEntityService.updateSample(s, usr);
            }
            mintEventLog.setDatabaseLog(DatabaseErrorCode.UPDATE_SUCCESS, null);
            mintEventLogs.add(mintEventLog);
          } catch (Exception e) {
            if (e instanceof javax.persistence.PersistenceException
                && e.getCause().getCause().getMessage().contains("duplicate key value")) {
              mintEventLog.setDatabaseLog(DatabaseErrorCode.DUPLICATE_KEY, e.getMessage());
              mintEventLogs.add(mintEventLog);

            } else {
              mintEventLog.setDatabaseLog(DatabaseErrorCode.UPDATE_ERROR, e.getMessage());
              mintEventLogs.add(mintEventLog);
            }
          }

        } else {
          mintEventLog.setMintLog(
              MintErrorCode.PREFIX_UNREGISTERED,
              "The prefix is not registered to the user:"******"");
          mintEventLogs.add(mintEventLog);
        }
      }
    }

    return new ResponseEntity<List<MintEventLog>>(mintEventLogs, HttpStatus.OK);
  }
  @Override
  public void executeCommand(Player admin, String[] params) {
    String usage = "syntax; //ring <add (c|p1|p2)>|<save>|<next>";

    if (admin.getAccessLevel() < AdminConfig.COMMAND_RING) {
      PacketSendUtility.sendMessage(admin, "<You don't have the right to execute this command>");
    }

    if (params.length == 0) {
      PacketSendUtility.sendMessage(admin, usage);
      return;
    }

    if (params[0].equalsIgnoreCase("add")) {
      if (params.length < 2) {
        PacketSendUtility.sendMessage(admin, usage);
        return;
      }

      if (params[1].equalsIgnoreCase("c")) {
        if (params.length == 3 && params[2].equalsIgnoreCase("new")) {
          String newZoneName = admin.getZoneInstance().getTemplate().getName().name();
          if (zoneName != null && !zoneName.equalsIgnoreCase(newZoneName)) {
            zoneName = newZoneName;
          }
        }

        if (zoneName == null) {
          zoneName = admin.getZoneInstance().getTemplate().getName().name();
        }

        center = new Point3D(admin.getX(), admin.getY(), admin.getZ());
        ringId = nextIdForRegion(zoneName);
        ringName = zoneName + "_" + ringId;
        PacketSendUtility.sendMessage(admin, "Center for " + ringName + " added");
      }

      if (params[1].equalsIgnoreCase("p1")) {
        p1 = new Point3D(admin.getX(), admin.getY(), admin.getZ());
        PacketSendUtility.sendMessage(admin, "Point p1 for " + ringName + " added");
      }

      if (params[1].equalsIgnoreCase("p2")) {
        p2 = new Point3D(admin.getX(), admin.getY(), admin.getZ());
        PacketSendUtility.sendMessage(admin, "Point p2 for " + ringName + " added");
      }

      if (center != null && p1 != null && p2 != null) {
        rings
            .get(zoneName)
            .put(ringId, new FlyRingTemplate(ringName, admin.getWorldId(), center, p1, p2));
        center = null;
        p1 = null;
        p2 = null;
        PacketSendUtility.sendMessage(admin, "Added fly ring " + ringName + " !");
      }
      return;
    }

    if (params[0].equalsIgnoreCase("save")) {
      Schema schema = null;
      SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      Logger log = Logger.getLogger(Ring.class);

      try {
        schema = sf.newSchema(new File("./data/static_data/fly_rings/fly_rings.xsd"));
      } catch (SAXException e1) {
        log.error("Error while saving data: " + e1.getMessage(), e1.getCause());
        PacketSendUtility.sendMessage(admin, "Unexpected error occured during saving");
        return;
      }

      File xml = new File("./data/static_data/fly_rings/generated_fly_rings.xml");
      JAXBContext jc;
      Marshaller marshaller;
      FlyRingData data = new FlyRingData();
      for (Map<Integer, FlyRingTemplate> e : rings.values()) {
        data.addAll(e.values());
      }
      try {
        jc = JAXBContext.newInstance(FlyRingData.class);
        marshaller = jc.createMarshaller();
        marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(data, xml);
      } catch (JAXBException e) {
        log.error("Error while saving data: " + e.getMessage(), e.getCause());
        PacketSendUtility.sendMessage(admin, "Unexpected error occured during saving");
        return;
      }

      PacketSendUtility.sendMessage(admin, "Saved successfully new fly_rings !");
    }

    if (params[0].equalsIgnoreCase("next")) {
      float x = (float) ringPositions[i].x;
      float y = (float) ringPositions[i].y;
      float z = (float) ringPositions[i].z;

      TeleportService.teleportTo(admin, admin.getWorldId(), x, y, z, 0);
      PacketSendUtility.sendMessage(
          admin, "Teleported to ring " + (i + 1) + "/" + ringPositions.length);

      i = (i + 1) % ringPositions.length;
    }
  }
  /** This method as the all procedure for extract the features. */
  public static final Boolean start(MP3Info mp3) throws SongFeatureException {

    GetHttpPage getHttp = GetHttpPage.getInstance();
    String content = "";
    File output = null;
    NodeList nodeList = null;
    SongType song = null;
    ObjectFactory obf = null;
    Document songDoc = null;

    Logger log;
    try {
      log = SongLogger.getInstance().getLog();
    } catch (LogException e) {
      throw new SongFeatureException("LogException " + e.getMessage(), e);
    }

    try {

      obf = new ObjectFactory();
      song = obf.createSongType();

      String title = mp3.getTitle();
      if (title == null || title.equals("")) {
        log.info("The title is null for file: " + mp3.getAudioFile().getName());
        return false;
      }

      String artistName = mp3.getArtist();
      String albumName = mp3.getAlbum();

      // try all parameters, the function will use the most it can
      content =
          getHttp.getWebPageAsString(
              MusicbrainzUrl.getMbRecordingUrl(artistName, title, albumName));
      if (content.equals("")) {
        log.info("Could not get Song from musicbrainz for file: " + mp3.getAudioFile().getName());
        return false;
      }

      songDoc = CreateDoc.create(content);

      // if the count is zero, no song was found.
      Element recordingListNode = (Element) songDoc.getElementsByTagName("recording-list").item(0);
      Integer count =
          Integer.valueOf(recordingListNode.getAttributes().getNamedItem("count").getNodeValue());
      if (count.intValue() == 0) {

        // some tags were not correct, performing a more generic query to find the right one
        FindAlbumArtist finder = new FindAlbumArtist(artistName, albumName, title);
        artistName = finder.getArtistName();
        albumName = finder.getAlbumName();
      }

      // try the query with the new parameters
      content =
          getHttp.getWebPageAsString(
              MusicbrainzUrl.getMbRecordingUrl(artistName, title, albumName));
      if (content.equals("")) {
        log.info("Could not get Song from musicbrainz for file: " + mp3.getAudioFile().getName());
        return false;
      }

      songDoc = CreateDoc.create(content);

      recordingListNode = (Element) songDoc.getElementsByTagName("recording-list").item(0);
      count =
          Integer.valueOf(recordingListNode.getAttributes().getNamedItem("count").getNodeValue());

      if (count.intValue() == 0) {
        log.info("Could not get Song from musicbrainz for file: " + mp3.getAudioFile().getName());
        return false;
      }

      Element recordingNode = (Element) recordingListNode.getElementsByTagName("recording").item(0);

      // set song id
      song.setMbSongID(recordingNode.getAttribute("id"));
      // set song title

      song.setTitle(recordingNode.getElementsByTagName("title").item(0).getTextContent());

      // set artist
      ArtistType artist = obf.createArtistType();
      Element artistNode = (Element) recordingNode.getElementsByTagName("artist").item(0);
      artist.setMbArtistID(artistNode.getAttribute("id"));
      artist.setName(artistNode.getElementsByTagName("name").item(0).getTextContent());
      nodeList = artistNode.getElementsByTagName("disambiguation");
      if (nodeList.getLength() != 0) artist.setDisambiguation(nodeList.item(0).getTextContent());
      song.setArtist(artist);

      // set albums for this song
      nodeList = recordingNode.getElementsByTagName("release");
      AlbumListType albumList = obf.createAlbumListType();
      for (int i = 0; i < nodeList.getLength(); ++i) {
        Element releaseNode = (Element) nodeList.item(i);
        AlbumType album = obf.createAlbumType();

        // set album ID
        album.setMbAlbumID(releaseNode.getAttribute("id"));

        // set album title
        album.setTitle(releaseNode.getElementsByTagName("title").item(0).getTextContent());

        // set album status
        NodeList valueList = releaseNode.getElementsByTagName("status");
        if (valueList.getLength() != 0) album.setStatus(valueList.item(0).getTextContent());

        // set album date
        valueList = releaseNode.getElementsByTagName("date");
        if (valueList.getLength() != 0) album.setDate(valueList.item(0).getTextContent());

        // set album country
        valueList = releaseNode.getElementsByTagName("country");
        if (valueList.getLength() != 0) album.setCountry(valueList.item(0).getTextContent());

        // set album track count
        valueList = releaseNode.getElementsByTagName("track-count");
        if (valueList.getLength() != 0)
          album.setTrackCount(new BigInteger(valueList.item(0).getTextContent()));

        albumList.getAlbum().add(album);
      }

      if (albumList.getAlbum().isEmpty() == false) song.setAlbumList(albumList);

      AudioFile afile = mp3.getAudioFile();

      // set file length (seconds)
      song.setLength(BigInteger.valueOf(afile.getLength()));

      // set file name
      song.setFileName(afile.getName());

      // set bitrate
      song.setBitrate(BigInteger.valueOf(afile.getBitrate()));

      // set channels
      song.setChannelsNum(BigInteger.valueOf(afile.getChannelNumber()));

      // set frequency
      song.setFrequency(BigInteger.valueOf(afile.getSamplingRate()));

      // set encoding
      String encoding = afile.getEncodingType();
      if (encoding != null && !encoding.equals("")) song.setEncoding(encoding);

      // set the creation date
      song.setXMLFileCreation(DateConverter.CurrentDateToXMLGregorianCalendar());

      // marshall this JaxbElement
      JAXBContext jc = JAXBContext.newInstance("songArtifacts.highLevel");
      JAXBElement<SongType> je = obf.createSongMetadata(song);
      Marshaller m = jc.createMarshaller();
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
      InputStream is =
          LowLevelSongFeature.class
              .getClassLoader()
              .getResourceAsStream("MetadataSchema/songHighLevel.xsd");
      Schema schema = sf.newSchema(new StreamSource(is));
      m.setSchema(schema);
      m.setEventHandler(
          new ValidationEventHandler() {

            @Override
            public boolean handleEvent(ValidationEvent event) {
              return false;
            }
          });

      output = new File("SONG_HL_" + song.getTitle() + ".xml");
      m.marshal(je, output);

    } catch (JAXBException e) {
      if (output != null) output.delete();
      log.warning("Marshalling validation error for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException("JAXBException " + e.getMessage(), e);
    } catch (FindAlbumArtistException e) {
      log.warning("Error finding artist for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException("FindAlbumArtistException " + e.getMessage(), e);
    } catch (DateConverterException e) {
      log.warning("Error converting date for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException("DateConverterException " + e.getMessage(), e);
    } catch (NullPointerException e) {
      log.warning("NullPointerException for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException("NullPointerException " + e.getMessage(), e);
    } catch (MusicbrainzUrlException e) {
      log.warning("Error musicbrainz url generation for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException("MusicbrainzUrlException " + e.getMessage(), e);
    } catch (GetHttpException e) {
      log.warning("Error getting html page for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException("GetHttpException " + e.getMessage(), e);
    } catch (CreateDocException e) {
      log.warning("Error creating document DOM for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException(
          "MusicbrainzDocException doc creation problem " + e.getMessage(), e);
    } catch (Exception e) {
      log.warning("Error " + e.getMessage() + " for file: " + mp3.getAudioFile().getName());
      throw new SongFeatureException("Exception " + e.getMessage(), e);
    }

    return true;
  }