示例#1
1
 public void read(JarPackageData jarPackage) throws CoreException {
   try {
     readXML(jarPackage);
   } catch (IOException ex) {
     String message =
         (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             JavaPlugin.getPluginId(),
             IJavaStatusConstants.INTERNAL_ERROR,
             message,
             ex));
   } catch (SAXException ex) {
     String message =
         (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); // $NON-NLS-1$
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             JavaPlugin.getPluginId(),
             IJavaStatusConstants.INTERNAL_ERROR,
             message,
             ex));
   }
 }
 private CloudServersException parseCloudServersException(HttpResponse response) {
   CloudServersException cse = new CloudServersException();
   try {
     BasicResponseHandler responseHandler = new BasicResponseHandler();
     String body = responseHandler.handleResponse(response);
     CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser();
     SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
     XMLReader xmlReader = saxParser.getXMLReader();
     xmlReader.setContentHandler(parser);
     xmlReader.parse(new InputSource(new StringReader(body)));
     cse = parser.getException();
   } catch (ClientProtocolException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (IOException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (ParserConfigurationException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (SAXException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (FactoryConfigurationError e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   }
   return cse;
 }
  /**
   * Handles a next log entry producing corresponding xml.
   *
   * @param logEntry log entry
   * @throws SVNException
   */
  public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {

    if (logEntry.getChangedPaths() != null && relativePath != null) {
      // convert external path reference to local relative path
      Map<String, SVNLogEntryPath> changedPaths = new HashMap<String, SVNLogEntryPath>();
      for (SVNLogEntryPath entry : logEntry.getChangedPaths().values()) {
        String localPath = entry.getPath().substring(1); // path in svn log start with a '/'
        if (localPath.startsWith(relativeUrl)) {
          localPath = relativePath + localPath.substring(relativeUrl.length());
        }
        // can't use entry.setPath(localPath) as FSPathChange duplicate myPath attribute then
        // setPath().getPath() don't return same value
        changedPaths.put(
            localPath,
            new SVNLogEntryPath(
                localPath, entry.getType(), entry.getCopyPath(), entry.getCopyRevision()));
      }
      logEntry.getChangedPaths().clear();
      logEntry.getChangedPaths().putAll(changedPaths);
    }

    try {
      if (filter == null || !filter.hasExclusionRule() || filter.isIncluded(logEntry)) {
        sendToHandler(logEntry);
      }
    } catch (SAXException e) {
      SVNErrorMessage err =
          SVNErrorMessage.create(SVNErrorCode.XML_MALFORMED, e.getLocalizedMessage());
      SVNErrorManager.error(err, e, SVNLogType.DEFAULT);
    }
  }
  public static final boolean acceptsXmlNeptuneFile(File file, URL schemaURL) {

    if (schemaURL == null) {
      schemaURL = schemas.get(0);
    }

    try (FileInputStream in = new FileInputStream(file)) {
      Source xmlFile = new StreamSource(in);
      try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(schemaURL);
        Validator validator = schema.newValidator();
        validator.validate(xmlFile);
        Main.info(xmlFile.getSystemId() + " is valid");
        return true;
      } catch (SAXException e) {
        Main.error(xmlFile.getSystemId() + " is NOT valid");
        Main.error("Reason: " + e.getLocalizedMessage());
      } catch (IOException e) {
        Main.error(xmlFile.getSystemId() + " is NOT valid");
        Main.error("Reason: " + e.getLocalizedMessage());
      }
    } catch (IOException e) {
      Main.error(e.getMessage());
    }

    return false;
  }
示例#5
0
  public Book importDocbook(InputStream generatedXhtml) {
    HTMLParser handler = new HTMLParser();
    SAXParserFactory factory = SAXParserFactory.newInstance();

    // création d'un parseur SAX
    SAXParser parser;

    try {
      parser = factory.newSAXParser();
      parser.parse(new InputSource(generatedXhtml), handler);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
      logger.error(e.getLocalizedMessage());
      return null;
    } catch (SAXException e) {
      e.printStackTrace();
      logger.error(e.getLocalizedMessage());
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      logger.error(e.getLocalizedMessage());
      return null;
    }

    Book book = handler.getBook();
    Book toReturn = getBookManager().create(book.getTitle());
    return toReturn;
  }
示例#6
0
  public void retrieveNews() {

    try {

      //			HttpClient client = new DefaultHttpClient();
      //			HttpResponse response = client.execute(new
      // HttpGet("http://uaonline.ua.pt/xml/contents_xml.asp"));
      //			HttpEntity tmpEntity = response.getEntity();

      //			SAXParser xmlParser = SAXParserFactory.newInstance().newSAXParser();
      //			XMLReader xmlReader = xmlParser.getXMLReader();
      //			NewsHandler newsHandler = new NewsHandler();
      //			xmlReader.setContentHandler(newsHandler);
      //
      //			Reader test = new InputStreamReader(uaNewsURL.openStream());
      //			InputSource is = new InputSource(test);
      //			is.setEncoding("ISO-8859-1");
      //			xmlReader.parse(is);
      //			return newsHandler.getFeed();

      URL uaNewsURL = new URL("http://uaonline.ua.pt/xml/contents_xml.asp");
      DocumentBuilder xmlBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document xmlNews = xmlBuilder.parse(uaNewsURL.openStream());

      XPath query;
      NodeList newsItems;
      query = XPathFactory.newInstance().newXPath();
      Object result = query.compile("/rss/channel/item").evaluate(xmlNews, XPathConstants.NODESET);
      newsItems = (NodeList) result;

      NewsItem tempItem;
      Element tmpElem;
      for (int i = 0; i < newsItems.getLength(); i++) {
        tmpElem = (Element) newsItems.item(i);

        tempItem = parseInfo(tmpElem);
        this.addItem(tempItem);
      }

    } catch (MalformedURLException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println(
          "NewsFeed: retrieveNews: MalformedURLException " + e.getLocalizedMessage());
    } catch (ParserConfigurationException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println(
          "NewsFeed: retrieveNews: ParserConfigurationException " + e.getLocalizedMessage());
    } catch (IOException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println("NewsFeed: retrieveNews: IOException " + e.getLocalizedMessage());
    } catch (XPathExpressionException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println(
          "NewsFeed: retrieveNews: XPathExpressionException " + e.getLocalizedMessage());
    } catch (SAXException e) {
      System.out.println("NewsFeed: retrieveNews: " + e.getMessage());
      System.out.println("NewsFeed: retrieveNews: SAXException " + e.getLocalizedMessage());
    }
  }
  @Get("xml")
  /**
   * Method handling fetch requests through HTTP GET
   *
   * @return XML formatted as per RestDataSource of SmartGWT
   *     (http://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/data/RestDataSource.html)
   * @throws SAXException
   * @throws IOException
   */
  public String represent() {
    StringWriter xml = new StringWriter();
    XmlWriter xmlWriter = new XmlWriter(xml);

    ObjectOutputStream out;

    try {
      xmlWriter.startDocument();

      xmlWriter.setDataFormat(true);

      xmlWriter.startElement("response");

      String clinicId = (String) getRequest().getAttributes().get("clinicId");

      if (clinicId != null && clinicId != "") {
        xmlWriter.dataElement("status", "0");
        xmlConverter.alias("record", ClinicRequirements.class);
        try {
          out = xmlConverter.createObjectOutputStream(xmlWriter.getWriter(), "data");

          //					List<ClinicRequirements> connDetailsList = clinicRequirementsBean
          //							.findByClinicId(Integer.parseInt(clinicId));
          //
          //					for (ClinicRequirements connDetails : connDetailsList) {
          //						out.writeObject(connDetails);
          //					}
          out.close();
        } catch (IOException e) {
          System.out.println("Error: " + e.getLocalizedMessage());
          xmlWriter.dataElement("status", "-1");
          xmlWriter.dataElement("data", "Error with XML converter, please retry! ");
        }
      } else {
        xmlWriter.dataElement("status", "-1");
        xmlWriter.dataElement("data", "Clinic Id cannot be empty!");
      }

      xmlWriter.endElement("response");
      xmlWriter.endDocument();

      return xml.toString();

    } catch (SAXException s) {
      System.out.println("Error: " + s.getLocalizedMessage());
      return null;
    }
  }
  public void validate(String request, String xsd) throws SoapExceptionServer, SoapExceptionClient {
    try {
      SOAPBody soapBody = getSOAPBody(request);
      Source xmlSource = createSource(soapBody);
      Validator validator = createValidator(xsd);

      validator.validate(xmlSource);
    } catch (SAXException saxParseEx) {
      throw new SoapExceptionClient(saxParseEx.getLocalizedMessage(), saxParseEx);
    } catch (SoapExceptionClient clientEx) {
      throw clientEx;
    } catch (IOException | TransformerException ex) {
      throw new SoapExceptionServer("Error while validating soap-message.", ex.getMessage(), ex);
    }
  }
示例#9
0
 public static Map<String, String> validXML(URL urlSchema, File urlXSD)
     throws MalformedURLException, SAXException {
   Map<String, String> responseMap = new HashMap<String, String>();
   Source xmlFile = new StreamSource(urlXSD);
   SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
   Schema schema = schemaFactory.newSchema(urlSchema);
   Validator validator = schema.newValidator();
   try {
     validator.validate(xmlFile);
     log.debug(xmlFile.getSystemId() + " valido");
     responseMap.put("valid", "success");
   } catch (SAXException e) {
     log.error(xmlFile.getSystemId() + " no valido");
     log.error("Reason: " + e.getLocalizedMessage());
     responseMap.put("valid", "false");
     responseMap.put("razon", e.getLocalizedMessage());
   } catch (IOException e) {
     log.error(xmlFile.getSystemId() + " no valido");
     log.error("Reason: " + e.getLocalizedMessage());
     responseMap.put("valid", "false");
     responseMap.put("razon", e.getLocalizedMessage());
   }
   return responseMap;
 }
  public static List<Tournament> parseTournaments(InputStream inputStream) {

    List<Tournament> tournaments = new ArrayList<Tournament>();

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document document = docBuilder.parse(inputStream);

      document.getDocumentElement().normalize();
      NodeList noList = document.getElementsByTagName("tournament");

      for (int s = 0; s < noList.getLength(); s++) {
        Node tournament = noList.item(s);
        Tournament tournamentObj = new Tournament();
        tournaments.add(tournamentObj);

        if (tournament.getNodeType() == Node.ELEMENT_NODE) {
          Element tournamentElement = (Element) tournament;
          // tournamentElement.getAttribute("author");

          tournamentObj.setName(tournamentElement.getAttribute("name"));

          Subject subject = new Subject();
          tournamentObj.setSubject(subject);
          subject.setSubjectName(tournamentElement.getAttribute("subject"));

          Log.w("Dharma", "Executed till here");
          NodeList questions = tournamentElement.getElementsByTagName("question");
          for (int i = 0; i < questions.getLength(); i++) {
            Node question = questions.item(i);
            if (question.getNodeType() == Node.ELEMENT_NODE) {
              Element questionElement = (Element) question;
              tournamentObj.addQuestion(parseQuestion(questionElement));
            }
          }
        }
      }

    } catch (IOException io) {
      Log.w("Dharma", io.getLocalizedMessage());
    } catch (SAXException sax) {
      Log.w("Dharma", sax.getLocalizedMessage());
    } catch (ParserConfigurationException pce) {
      Log.w("Dharma", pce.getLocalizedMessage());
    }
    return tournaments;
  }
 private Element checkXML(WebSession s, String xml) {
   try {
     XMLReader reader = XMLReaderFactory.createXMLReader();
     PasswordChanger changer = new PasswordChanger();
     reader.setContentHandler(changer);
     reader.parse(new InputSource(new StringReader(xml)));
     if (!"101".equals(changer.getId())) {
       makeSuccess(s);
       return new B(
           HtmlEncoder.encode(
               "You have changed the passsword for userid "
                   + changer.getId()
                   + " to '"
                   + changer.getPassword()
                   + "'"));
     } else {
       return new StringElement("You changed the password for userid 101. Try again.");
     }
   } catch (SAXException saxe) {
     return new StringElement("The XML was not well formed: " + saxe.getLocalizedMessage());
   } catch (IOException ioe) {
     return new StringElement(ioe.getLocalizedMessage());
   }
 }
  /*
   * (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.");
  }
示例#13
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);
  }