public synchronized Object fromXML(java.io.Reader input) throws XMLUtilityException { Object beanObject; org.exolab.castor.xml.Unmarshaller unmarshaller = null; try { log.debug("Creating unmarshaller"); unmarshaller = new org.exolab.castor.xml.Unmarshaller(this.getMapping()); } catch (MappingException e) { log.error("XML mapping file is invalid: ", e); throw new XMLUtilityException("XML mapping file invalid: ", e); } catch (Exception e) { log.error("General Exception caught trying to create unmarshaller: ", e); throw new XMLUtilityException("General Exception caught trying to create unmarshaller: ", e); } try { log.debug("About to unmarshal from input "); beanObject = unmarshaller.unmarshal(input); } catch (MarshalException e) { log.error("Error marshalling input: ", e); throw new XMLUtilityException("Error unmarshalling xml input: " + e.getMessage(), e); } catch (ValidationException e) { log.error("Error in xml validation when unmarshalling xml input: ", e); throw new XMLUtilityException("Error in xml validation when unmarshalling xml input: ", e); } return beanObject; }
public <T> T sendRequest(Class<T> cls, Object request) throws WasabiNetClientException { StringWriter sw = new StringWriter(); String convertida = null; String received = null; try { marshaller.setWriter(sw); marshaller.marshal(request); convertida = new String(sw.getBuffer().toString().getBytes("UTF8"), "UTF8"); System.out.println(convertida); received = getData(serviceUrl, convertida); System.out.println("---" + received + "---"); unmarshaller.setClass(cls); return (T) unmarshaller.unmarshal(new StringReader(received)); } catch (IOException e) { throw new WasabiNetClientException("Error de lectura/escritura:" + e.getMessage()); } catch (MarshalException e) { e.printStackTrace(); throw new WasabiNetClientException( "Error al armar la respuesta:" + e.getMessage(), convertida, received); } catch (ValidationException e) { throw new WasabiNetClientException( "Error en la validacion de la respuesta:" + e.getMessage(), convertida, received); } // catch WasabiNetClientException -> Esta directamente salta al metodo que ha llamado a // sendrequest }
public void testExceptionContainsFileNameUnmarshalResourceWithBadResource() throws MarshalException, ValidationException, FileNotFoundException, IOException { /* * We are going to attempt to unmarshal groups.xml with the wrong * class so we get a MarshalException and we can then test to see if the * file name is embedded in the exception. */ boolean gotException = false; File file = ConfigurationTestUtils.getFileForConfigFile("groups.xml"); try { CastorUtils.unmarshal(Userinfo.class, new FileSystemResource(file)); } catch (MarshalException e) { String matchString = file.getAbsolutePath().replace('\\', '/'); if (e.toString().contains(matchString)) { gotException = true; } else { AssertionFailedError ae = new AssertionFailedError( "Got an exception, but not one containing the message we were expecting ('" + matchString + "'): " + e); ae.initCause(e); throw ae; } } if (!gotException) { fail("Did not get a MarshalException, but we were expecting one."); } }
public List<EventReply> receive() throws IOException { byte[] buf = new byte[0xff]; DatagramPacket packet = new DatagramPacket(buf, 0, 0xff); m_dgSocket.receive(packet); byte[] data = packet.getData(); // System.out.println("receive data is : "+new String(data,"utf-8")); StringReader reader = new StringReader(new String(data, 0, packet.getLength(), "utf-8")); EventReceipt receipt = null; try { receipt = (EventReceipt) Unmarshaller.unmarshal(EventReceipt.class, reader); } catch (MarshalException e) { e.printStackTrace(); } catch (ValidationException e) { e.printStackTrace(); } InetAddress remoteAddr = packet.getAddress(); int port = packet.getPort(); List<EventReply> replys = new ArrayList<EventReply>(); if (receipt != null) { String[] uuids = receipt.getUuid(); for (String uuid : uuids) { EventReply reply = new EventReply(remoteAddr, port, uuid); replys.add(reply); } } return replys; }
private FileWriter handleLoadCastor(FileWriter writer, RulesPostImportContainer rpic) { try { // Create Mapping Mapping mapping = new Mapping(); mapping.loadMapping(SpringServletAccess.getPropertiesDir(context) + "mappingMarshaller.xml"); // Create XMLContext XMLContext xmlContext = new XMLContext(); xmlContext.addMapping(mapping); Marshaller marshaller = xmlContext.createMarshaller(); marshaller.setWriter(writer); marshaller.marshal(rpic); return writer; } catch (FileNotFoundException ex) { throw new OpenClinicaSystemException(ex.getMessage(), ex.getCause()); } catch (IOException ex) { throw new OpenClinicaSystemException(ex.getMessage(), ex.getCause()); } catch (MarshalException e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } catch (ValidationException e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } catch (MappingException e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } catch (Exception e) { throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); } }
private PollerConfiguration getPollerConfiguration() { PollerConfiguration pollconfig = null; try { PollerConfigFactory.init(); PollerConfigFactory.reload(); pollconfig = PollerConfigFactory.getInstance().getConfiguration(); } catch (MarshalException me) { me.printStackTrace(); } catch (ValidationException ve) { ve.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return pollconfig; }
private void setPollerConfiguration(PollerConfiguration pollconfig) { try { pollconfig.validate(); BufferedWriter bw = new BufferedWriter( new FileWriter( WTProperties.getValue("SNMPConfig.directory") + "poller-configuration.xml")); pollconfig.marshal(bw); bw.flush(); bw.close(); } catch (MarshalException me) { me.printStackTrace(); } catch (ValidationException ve) { ve.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
/** Escribe sobre el config.xml, la nueva configuración. */ public void marshalPlugins() { HashMap pc = Launcher.getPluginConfig(); Iterator iter = pc.keySet().iterator(); while (iter.hasNext()) { Object obj = iter.next(); PluginConfig pconfig = (PluginConfig) pc.get(obj); Writer writer; try { FileOutputStream fos = new FileOutputStream( Launcher.getAndamiConfig().getPluginsDirectory() + File.separator + (String) obj + File.separator + "config.xml"); // castor uses xerces, and xerces uses UTF-8 by default, so we should use // UTF-8 to create the writer, as long as we continue using castor+xerces writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")); try { pconfig.marshal(writer); } catch (MarshalException e1) { e1.printStackTrace(); } catch (ValidationException e1) { e1.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } // hay que refrescar la aplicación /// ((App)App.instance).run(); } }
/** * This method queries the Vmware vCenter server for sensor data. * * @param svc the monitored service * @param parameters the parameter map * @return the poll status for this system */ @Override public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) { OnmsNode onmsNode = m_nodeDao.get(svc.getNodeId()); // retrieve the assets and String vmwareManagementServer = onmsNode.getAssetRecord().getVmwareManagementServer(); String vmwareManagedEntityType = onmsNode.getAssetRecord().getVmwareManagedEntityType(); String vmwareManagedObjectId = onmsNode.getForeignId(); TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT); PollStatus serviceStatus = PollStatus.unknown(); for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) { VmwareViJavaAccess vmwareViJavaAccess = null; try { vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer); } catch (MarshalException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } catch (ValidationException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } catch (IOException e) { logger.warn( "Error initialising VMware connection to '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error initialising VMware connection to '" + vmwareManagementServer + "'"); } try { vmwareViJavaAccess.connect(); } catch (MalformedURLException e) { logger.warn( "Error connecting VMware management server '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error connecting VMware management server '" + vmwareManagementServer + "'"); } catch (RemoteException e) { logger.warn( "Error connecting VMware management server '{}': '{}'", vmwareManagementServer, e.getMessage()); return PollStatus.unavailable( "Error connecting VMware management server '" + vmwareManagementServer + "'"); } if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) { logger.warn( "Error setting connection timeout for VMware management server '{}'", vmwareManagementServer); } String powerState = "unknown"; if ("HostSystem".equals(vmwareManagedEntityType)) { HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId); if (hostSystem == null) { return PollStatus.unknown("hostSystem=null"); } else { HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime(); if (hostRuntimeInfo == null) { return PollStatus.unknown("hostRuntimeInfo=null"); } else { HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState(); if (hostSystemPowerState == null) { return PollStatus.unknown("hostSystemPowerState=null"); } else { powerState = hostSystemPowerState.toString(); } } } } else { if ("VirtualMachine".equals(vmwareManagedEntityType)) { VirtualMachine virtualMachine = vmwareViJavaAccess.getVirtualMachineByManagedObjectId(vmwareManagedObjectId); if (virtualMachine == null) { return PollStatus.unknown("virtualMachine=null"); } else { VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime(); if (virtualMachineRuntimeInfo == null) { return PollStatus.unknown("virtualMachineRuntimeInfo=null"); } else { VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState(); if (virtualMachinePowerState == null) { return PollStatus.unknown("virtualMachinePowerState=null"); } else { powerState = virtualMachinePowerState.toString(); } } } } else { logger.warn( "Error getting '{}' for '{}'", vmwareManagedEntityType, vmwareManagedObjectId); vmwareViJavaAccess.disconnect(); return serviceStatus; } } if ("poweredOn".equals(powerState)) { serviceStatus = PollStatus.available(); } else { serviceStatus = PollStatus.unavailable("The system's state is '" + powerState + "'"); } vmwareViJavaAccess.disconnect(); } return serviceStatus; }
/** {@inheritDoc} */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // the path info will be the category name we need String pathInfo = request.getPathInfo(); // send 400 Bad Request if they did not specify a category in the path // info if (pathInfo == null) { LOG.error("Request with no path info"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No Category name given in path"); return; } // remove the preceding slash if present if (pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1, pathInfo.length()); } // since these category names can contain spaces, etc, // we have to URL encode them in the URL String categoryName = Util.decode(pathInfo); org.opennms.netmgt.xml.rtc.Category category = null; try { ServletInputStream inStream = request.getInputStream(); // note the unmarshaller closes the input stream, so don't try to // close // it again or the servlet container will complain org.opennms.netmgt.xml.rtc.EuiLevel level = CastorUtils.unmarshal(org.opennms.netmgt.xml.rtc.EuiLevel.class, inStream); // for now we only deal with the first category, they're only sent // one // at a time anyway category = level.getCategory(0); } catch (MarshalException ex) { LOG.error("Failed to load configuration", ex); response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid XML input: MarshalException: " + ex.getMessage()); return; } catch (ValidationException ex) { LOG.error("Failed to load configuration", ex); response.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid XML input: ValidationException" + ex.getMessage()); return; } // make sure we got data for the category we are interested in // send 400 Bad Request if they did not supply category information // for the categoryname in the path info if (!categoryName.equals(category.getCatlabel())) { LOG.error("Request did not supply information for category specified in path info"); response.sendError( HttpServletResponse.SC_BAD_REQUEST, "No category info found for " + categoryName); return; } // update the category information in the CategoryModel this.model.updateCategory(category); // return a success message response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Category data parsed successfully."); out.close(); LOG.info("Successfully received information for {}", categoryName); }
/** {@inheritDoc} */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { reloadFiles(); String query = request.getQueryString(); if (query != null) { java.util.List<String> checkedList = new ArrayList<String>(); java.util.List<String> deleteList = new ArrayList<String>(); props.store( new FileOutputStream( ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONF_FILE_NAME)), null); StringTokenizer strTok = new StringTokenizer(query, "&"); while (strTok.hasMoreTokens()) { String token = strTok.nextToken(); if (token != null) { StringTokenizer keyTokens = new StringTokenizer(token, "="); String name = null; if (keyTokens.hasMoreTokens()) { name = (String) keyTokens.nextToken(); } if (keyTokens.hasMoreTokens()) { String checked = (String) keyTokens.nextToken(); if (name != null) { if (name.indexOf("delete") == -1) // Not to be // deleted { modifyPollerInfo(checked, name); checkedList.add(name); } else // Deleted { String deleteService = name.substring(0, name.indexOf("delete")); deleteList.add(deleteService); } } } } } adjustNonChecked(checkedList); deleteThese(deleteList); Writer poller_fileWriter = new OutputStreamWriter( new FileOutputStream( ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONFIG_FILE_NAME)), "UTF-8"); Writer capsd_fileWriter = new OutputStreamWriter( new FileOutputStream( ConfigFileConstants.getFile(ConfigFileConstants.CAPSD_CONFIG_FILE_NAME)), "UTF-8"); try { Marshaller.marshal(pollerConfig, poller_fileWriter); Marshaller.marshal(capsdConfig, capsd_fileWriter); } catch (MarshalException e) { e.printStackTrace(); throw new ServletException(e.getMessage()); } catch (ValidationException e) { e.printStackTrace(); throw new ServletException(e.getMessage()); } } response.sendRedirect(this.redirectSuccess); }