public static TagConfigImpl fromXml(final String xml) throws Exception { TagConfigImpl conf = null; StringReader sr = null; Serializer serializer = new Persister(new AnnotationStrategy()); try { sr = new StringReader(xml); conf = serializer.read(TagConfigImpl.class, new StringReader(xml), false); } finally { if (sr != null) { sr.close(); } } return conf; }
public static AlarmValueImpl fromXml(final String xml) throws Exception { AlarmValueImpl alarmVal = null; StringReader sr = null; Serializer serializer = new Persister(new AnnotationStrategy()); try { sr = new StringReader(xml); alarmVal = serializer.read(AlarmValueImpl.class, new StringReader(xml), false); } finally { if (sr != null) { sr.close(); } } return alarmVal; }
public static CommandTagImpl fromXml(final String xml) throws Exception { CommandTagImpl commandTag = null; StringReader sr = null; Serializer serializer = new Persister(new AnnotationStrategy()); try { sr = new StringReader(xml); commandTag = serializer.read(CommandTagImpl.class, new StringReader(xml), false); } finally { if (sr != null) { sr.close(); } } return commandTag; }
@Nonnull public static <T> T testSerialization(@Nonnull Class<T> type, @Nonnull T in) throws Exception { Persister persister = new Persister(new AnnotationStrategy(), newRegistryMatcher()); LOG.info("In: " + in); ByteArrayOutputStream os = new ByteArrayOutputStream(); persister.write(in, os); byte[] data = os.toByteArray(); LOG.info("Xml: " + new String(data, Charsets.UTF_8)); ByteArrayInputStream is = new ByteArrayInputStream(data); T out = persister.read(type, is); LOG.info("Out: " + out); return out; }
public void testMap() throws Exception { Strategy strategy = new AnnotationStrategy(); Serializer serializer = new Persister(strategy); MapHolder holder = new MapHolder(); holder.put("a", "A"); holder.put("b", "B"); holder.put("c", "C"); holder.put("d", "D"); holder.put("e", "E"); holder.put("f", "F"); serializer.write(holder, System.out); validate(holder, serializer); }
public void testConverter() throws Exception { Style style = new CamelCaseStyle(); Format format = new Format(style); Strategy cycle = new CycleStrategy(); Strategy strategy = new AnnotationStrategy(cycle); Persister persister = new Persister(strategy, format); List<ConverterDecorationExample> list = new ArrayList<ConverterDecorationExample>(); List<NormalExample> normal = new ArrayList<NormalExample>(); ConverterDecoration example = new ConverterDecoration(list, normal); ConverterDecorationExample duplicate = new ConverterDecorationExample("duplicate"); NormalExample normalDuplicate = new NormalExample("duplicate"); list.add(duplicate); list.add(new ConverterDecorationExample("a")); list.add(new ConverterDecorationExample("b")); list.add(new ConverterDecorationExample("c")); list.add(duplicate); list.add(new ConverterDecorationExample("d")); list.add(duplicate); normal.add(normalDuplicate); normal.add(new NormalExample("1")); normal.add(new NormalExample("2")); normal.add(normalDuplicate); persister.write(example, System.err); }
public void testConverterWithPathInHyphenStyle() throws Exception { Style style = new HyphenStyle(); Format format = new Format(style); Strategy strategy = new AnnotationStrategy(); Persister persister = new Persister(strategy, format); ServerDetails primary = new ServerDetails("host1.blah.com", 4567, "PRIMARY"); ServerDetails secondary = new ServerDetails("host2.foo.com", 4567, "SECONDARY"); ServerDetailsReference reference = new ServerDetailsReference(primary, secondary); StringWriter writer = new StringWriter(); persister.write(reference, writer); System.out.println(writer); ServerDetailsReference recovered = persister.read(ServerDetailsReference.class, writer.toString()); assertEquals(recovered.getPrimary().getHost(), reference.getPrimary().getHost()); assertEquals(recovered.getPrimary().getPort(), reference.getPrimary().getPort()); assertEquals(recovered.getPrimary().getName(), reference.getPrimary().getName()); assertEquals(recovered.getSecondary().getHost(), reference.getSecondary().getHost()); assertEquals(recovered.getSecondary().getPort(), reference.getSecondary().getPort()); assertEquals(recovered.getSecondary().getName(), reference.getSecondary().getName()); }
public void testConverterWithPathInCamelStyle() throws Exception { Style style = new CamelCaseStyle(); Format format = new Format(style); Strategy strategy = new AnnotationStrategy(); Persister persister = new Persister(strategy, format); ServerDetails primary = new ServerDetails("host1.blah.com", 4567, "PRIMARY"); ServerDetails secondary = new ServerDetails("host2.foo.com", 4567, "SECONDARY"); ServerDetailsReference reference = new ServerDetailsReference(primary, secondary); StringWriter writer = new StringWriter(); persister.write(reference, writer); System.out.println(writer); ServerDetailsReference recovered = persister.read(ServerDetailsReference.class, writer.toString()); assertEquals(recovered.getPrimary().getHost(), reference.getPrimary().getHost()); assertEquals(recovered.getPrimary().getPort(), reference.getPrimary().getPort()); assertEquals(recovered.getPrimary().getName(), reference.getPrimary().getName()); assertEquals(recovered.getSecondary().getHost(), reference.getSecondary().getHost()); assertEquals(recovered.getSecondary().getPort(), reference.getSecondary().getPort()); assertEquals(recovered.getSecondary().getName(), reference.getSecondary().getName()); }
public void parse() throws Exception { beforeParse(); for (SnippetContainer snippetContainer : getSnippetProject().getSnippetContainers()) { for (Snippet snippet : snippetContainer.getSnippets().values()) { File inputsXmlFile = RunnerProjectUtils.getSnippetInputsFile( getRunnerProjectSettings(), snippet); Serializer serializer = new Persister(new AnnotationStrategy()); SnippetInputsXml inputsXml = serializer.read(SnippetInputsXml.class, inputsXmlFile); inputsXml.validate(); if (inputsXml.getResultType() == ResultType.NA || inputsXml.getResultType() == ResultType.EX || inputsXml.getResultType() == ResultType.TM) { log.info("Skipping {}: {}", snippet.getId(), inputsXml.getResultType()); return; } parseOne(snippet); } } }
@Override public Object convert(String propertyName, String propertyValue, TypeDescriptor targetType) { Class<?> targetClass = targetType.getType(); Serializer serializer = new Persister(new AnnotationStrategy()); try { return serializer.read(targetClass, propertyValue, false); } catch (Exception e) { LOGGER.error("Convert xml to " + targetClass + " error", e); } return null; }
/** * Static method for creating a Process object * from a XML String by making use of the simpleframework XML library. * @param xml The XML representation of a <code>processConnectionResponse</code> object * @param processType The process type to call the proper object cast * @return Object Object created from the given XML String * @throws Exception In case of a parsing error or a wrong XML definition */ private final Object fromXml(final String xml, final ProcessMessageType processType) throws Exception { StringReader sr = null; Serializer serializer = new Persister(new AnnotationStrategy()); try { sr = new StringReader(xml); switch(processType) { case CONNECT_REQUEST: LOGGER.trace("fromXml() : converting from XML to ProcessConnectionRequest."); return serializer.read(ProcessConnectionRequest.class, sr, false); case CONNECT_RESPONSE: LOGGER.trace("fromXml() : converting from XML to ProcessConnectionResponse."); return serializer.read(ProcessConnectionResponse.class, sr, false); case CONFIG_REQUEST: LOGGER.trace("fromXml() : converting from XML to ProcessConfigurationRequest."); return serializer.read(ProcessConfigurationRequest.class, sr, false); case CONFIG_RESPONSE: LOGGER.trace("fromXml() : converting from XML to ProcessConfigurationResponse."); return serializer.read(ProcessConfigurationResponse.class, sr, false); case DISCONNETION_REQUEST: LOGGER.trace("fromXml() : converting from XML to ProcessDisconnectionRequest."); return serializer.read(ProcessDisconnectionRequest.class, sr, false); default: LOGGER.error("fromXml() : Process type not found: " + processType); throw new MessageFormatException("fromXml(): Process type not found: " + processType); } } finally { if (sr != null) { sr.close(); } } }
/** * Retrieve a {@link Serializer} instance suitable for deserialising a * {@link ConfigurationReport}. * * @return a new {@link Serializer} instance */ private Serializer getSerializer() { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); RegistryMatcher matcher = new RegistryMatcher(); matcher.bind(Timestamp.class, new DateFormatConverter(format)); Strategy strategy = new AnnotationStrategy(); Serializer serializer = new Persister(strategy, matcher); return serializer; }
@Provides @Singleton public UsStatesApi providesApi(){ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); Strategy strategy = new AnnotationStrategy(); Serializer serializer = new Persister(strategy); OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(interceptor) .connectTimeout(2, TimeUnit.MINUTES) .writeTimeout(2, TimeUnit.MINUTES) .readTimeout(2, TimeUnit.MINUTES) .build(); Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(SimpleXmlConverterFactory.create(serializer)) .baseUrl("http://www.webservicex.net/") .client(okHttpClient) .build(); return retrofit.create( UsStatesApi.class); }
/** * Utility to get a simple framework persister * @return a persister * @throws Exception when things get tough */ private static Serializer getSerializer() throws Exception { Registry registry = new Registry(); registry.bind(String.class, EmptyStringConverter.class); Strategy strategy = new AnnotationStrategy(new RegistryStrategy(registry)); return new Persister(strategy); }
public <T> T loadXmlFile(File file, Class<T> c) throws FileManagerException { Strategy strategy = new AnnotationStrategy(); Serializer serializer = new Persister(strategy, new TransformMatcher()); T instance; try { instance = serializer.read(c, file); } catch (Exception e) { throw new FileManagerException(String.format("couldn't decode XML of file '%s'", file.getPath()), e); } return instance; }
public <T> void storeXmlFile(File file, T instance) throws FileManagerException { Strategy strategy = new AnnotationStrategy(); Serializer serializer = new Persister(strategy, new TransformMatcher()); try { serializer.write(instance, file); } catch (Exception e) { throw new FileManagerException(String.format("couldn't encode object into file '%s'", file.getPath()), e); } }
@Provides Persister getPersister() { RegistryMatcher matchers = new RegistryMatcher(); matchers.bind(org.joda.time.DateTime.class, JodaTimeDateTimeTransform.class); Strategy strategy = new AnnotationStrategy(); return new Persister(strategy, matchers); }
public static void main(String[] args) throws Exception { SnippetResultXml resultXml = new SnippetResultXml(); resultXml.setToolName("MyTool"); resultXml.setSnippetProjectElement(new SnippetProjectElement()); resultXml.getSnippetProjectElement() .setBaseDirPath("/data/workspace/dev/SETTE-Snippets"); resultXml.setSnippetElement(new SnippetElement()); resultXml.getSnippetElement().setContainerName("hu.bme.mit.sette.snippets.MyContainer"); resultXml.getSnippetElement().setName("mySnippet"); // resultXml.setStatementCoverage(95.6); resultXml.setResultType(ResultType.C); try { resultXml.validate(); } catch (ValidationException ex) { System.err.println(ex.getMessage()); throw new RuntimeException(ex); } Serializer serializer = new Persister(new AnnotationStrategy()); StringWriter s = new StringWriter(); serializer.write(resultXml, s); System.out.println(s); resultXml = serializer.read(SnippetResultXml.class, s.getBuffer().toString()); s = new StringWriter(); serializer.write(resultXml, s); }
public IstatServiceImpl(ServerConfiguration sc) { Format format = new Format(0, PROLOG); serializer = new Persister(new AnnotationStrategy(), format); sc.validate(); this.sc = sc; }
public Converter.Factory create() { return new XmlRpcConverterFactory(new Persister(new AnnotationStrategy()), context); }
private static RSS read(String url) throws Exception { Serializer serializer = new Persister(new AnnotationStrategy()); return serializer.read(RSS.class, new URL(url).openStream(), false); }
private TalkClient() { restAdapter = new RestAdapter.Builder() .setEndpoint(ApiConfig.BASE_URL) .setClient(new OkClient()) .setRequestInterceptor(requestInterceptor) .setConverter(new GsonConverter(gson)) .setErrorHandler(authFailedErrorHandler) .setLogLevel(REST_LOG_LEVEL) .build(); uploadAdapter = new RestAdapter.Builder() .setEndpoint(ApiConfig.UPLOAD_URL) .setClient(new OkClient()) .setRequestInterceptor(strikerInterceptor) .setLogLevel(REST_LOG_LEVEL) .build(); accountAdapter = new RestAdapter.Builder() .setEndpoint(ApiConfig.ACCOUNT_URL) .setClient(new OkClient()) .setRequestInterceptor(requestInterceptor) .setLogLevel(REST_LOG_LEVEL) .build(); callAdapter = new RestAdapter.Builder() .setClient(new OkClient()) .setEndpoint(ApiConfig.CALL_URL) .setConverter(new SimpleXMLConverter(new Persister(new AnnotationStrategy()))) .setRequestInterceptor(callInterceptor) .setLogLevel(REST_LOG_LEVEL) .build(); spiderAdapter = new RestAdapter.Builder() .setEndpoint(ApiConfig.SPIDER_URL) .setClient(new OkClient()) .setRequestInterceptor(requestInterceptor) .setConverter(new GsonConverter(gson)) .build(); tpsAdapter = new RestAdapter.Builder() .setClient(new OkClient()) .setEndpoint(ApiConfig.TPS_API) .setRequestInterceptor(requestInterceptor) .setLogLevel(REST_LOG_LEVEL) .build(); tbAuthAdapter = new RestAdapter.Builder() .setEndpoint(ApiConfig.AUTH_SERVICE_URL) .setClient(new OkClient()) .setRequestInterceptor(requestInterceptor) .setConverter(new GsonConverter(gson)) .setLogLevel(REST_LOG_LEVEL) .build(); deviceId = DeviceUtil.getDeviceId(MainApp.CONTEXT); }
public NFPersister() { super(new AnnotationStrategy(), new NFRegistryMatcher(), new Format(0)); }
private String createRow(Snippet snippet) throws Exception { // parse data File infoFile = RunnerProjectUtils.getSnippetInfoFile(getRunnerProjectSettings(), snippet); File inputsXmlFile = RunnerProjectUtils.getSnippetInputsFile(getRunnerProjectSettings(), snippet); File resultXmlFile = RunnerProjectUtils.getSnippetResultFile(getRunnerProjectSettings(), snippet); Serializer serializer = new Persister(new AnnotationStrategy()); SnippetInputsXml inputsXml = serializer.read(SnippetInputsXml.class, inputsXmlFile); inputsXml.validate(); SnippetResultXml resultXml = serializer.read(SnippetResultXml.class, resultXmlFile); resultXml.validate(); // example: Elapsed time: 2002 ms String elapsedTime; if (infoFile.exists()) { elapsedTime = PathUtils.lines(infoFile.toPath()) .filter(line -> !StringUtils.isBlank(line) && line.trim().startsWith("Elapsed time:")) .map(line -> line.replaceAll("Elapsed time:", "").trim()).findAny().get() .replaceAll("ms", "").trim(); } else { elapsedTime = ""; } String testCaseCount; switch (resultXml.getResultType()) { case NC: case C: testCaseCount = String.valueOf(inputsXml.getGeneratedInputCount()); break; default: testCaseCount = ""; break; } // create fields List<String> fields = new ArrayList<>(); String snippetShortName = getShortSnippetName(snippet); fields.add(snippetShortName.split("_")[0]); // category fields.add(snippetShortName); // snippet fields.add(getTool().getName()); // tool fields.add(StringUtils.defaultIfEmpty(resultXml.getAchievedCoverage(), "").replace('%', ' ') .trim()); // coverage fields.add(resultXml.getResultType().toString()); // Status = ResultType fields.add(testCaseCount); // Size = TestCaseCount fields.add(getRunnerProjectSettings().getTag()); // Run = TAG fields.add(elapsedTime); // Duration: 43243 ms if (getTool().getName().startsWith("SnippetInputChecker")) { fields.add(String.format("%.2f", snippet.getRequiredStatementCoverage())); // coverage Validate.isTrue(fields.size() == HEADER_COLUMNS.length + 1); } else { Validate.isTrue(fields.size() == HEADER_COLUMNS.length); } // assemble and return return String.join(FIELD_SEP, fields); }
private SnippetCoverageXml createAndWriteCoverageXmlAndHtml(Snippet snippet, CoverageInfo coverageInfo) throws Exception { // decide result type Pair<ResultType, Double> resultTypeAndCoverage = decideResultType(snippet, coverageInfo); ResultType resultType = resultTypeAndCoverage.getLeft(); double coverage = resultTypeAndCoverage.getRight(); // FIXME hook to check snippets, but should be elsewhere if (getTool().getClass().getSimpleName().equals("SnippetInputCheckerTool")) { if (resultType != ResultType.C) { System.err.println("FAILURE for Checker, not C: " + snippet.getId()); throw new RuntimeException(); } } // create coverage XML SnippetCoverageXml coverageXml = new SnippetCoverageXml(); coverageXml.setToolName(getTool().getName()); coverageXml.setSnippetProjectElement(new SnippetProjectElement( getSnippetProject().getBaseDir().toFile().getCanonicalPath())); coverageXml.setSnippetElement(new SnippetElement( snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName())); coverageXml.setResultType(resultType); coverageXml.setAchievedCoverage(coverage); for (Entry<String, Triple<SortedSet<Integer>, SortedSet<Integer>, SortedSet<Integer>>> entry : coverageInfo.data .entrySet()) { SortedSet<Integer> full = entry.getValue().getLeft(); SortedSet<Integer> partial = entry.getValue().getMiddle(); SortedSet<Integer> not = entry.getValue().getRight(); FileCoverageElement fce = new FileCoverageElement(); fce.setName(entry.getKey()); fce.setFullyCoveredLines(StringUtils.join(full, ' ')); fce.setPartiallyCoveredLines(StringUtils.join(partial, ' ')); fce.setNotCoveredLines(StringUtils.join(not, ' ')); coverageXml.getCoverage().add(fce); } coverageXml.validate(); // TODO needs more documentation File coverageFile = RunnerProjectUtils.getSnippetCoverageFile(getRunnerProjectSettings(), snippet); Serializer serializer = new Persister(new AnnotationStrategy(), new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>")); serializer.write(coverageXml, coverageFile); // generate html new HtmlGenerator(this).generate(snippet, coverageXml); return coverageXml; }
public IstatServiceImpl() { Format format = new Format(0, PROLOG); serializer = new Persister(new AnnotationStrategy(), format); }
public DFPersister() { super(new AnnotationStrategy(), new DFRegistryMatcher(), new Format(0)); }