Here are the examples of the java api com.eclipsesource.json.JsonObject taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
224 Examples
19
Source : CaliperResultsPreprocessor_Test.java
with MIT License
from zcash-community
with MIT License
from zcash-community
public clreplaced CaliperResultsPreprocessor_Test {
private static JsonObject caliperJson;
@BeforeClreplaced
public static void loadCaliperJson() throws IOException {
caliperJson = JsonObject.readFrom(Resources.readResource("input/caliper.json"));
}
@Test
public void results_structure() {
CaliperResultsPreprocessor preprocessor = new CaliperResultsPreprocessor(caliperJson);
JsonObject results = preprocessor.getResults();
replacedertEquals(asList("name", "details", "measurements"), results.names());
replacedertTrue(results.get("name").isString());
replacedertTrue(results.get("details").isObject());
replacedertTrue(results.get("measurements").isArray());
}
@Test
public void name_isSimpleName() {
CaliperResultsPreprocessor preprocessor = new CaliperResultsPreprocessor(caliperJson);
JsonObject results = preprocessor.getResults();
String name = results.get("name").replacedtring();
replacedertTrue(name.contains("Benchmark"));
replacedertFalse(name.contains("."));
}
@Test
public void details_containsEnvironmentVariables() {
CaliperResultsPreprocessor preprocessor = new CaliperResultsPreprocessor(caliperJson);
JsonObject results = preprocessor.getResults();
replacedertTrue(results.get("details").asObject().names().contains("os.version"));
}
@Test
public void details_containsBenchmarkNameAndTime() {
CaliperResultsPreprocessor preprocessor = new CaliperResultsPreprocessor(caliperJson);
JsonObject results = preprocessor.getResults();
String name = results.get("details").asObject().get("benchmark.clreplacedname").replacedtring();
replacedertTrue(name.contains("."));
String time = results.get("details").asObject().get("benchmark.executionTime").replacedtring();
replacedertTrue(time.matches("[\\d-]+T[\\d:]+UTC"));
}
@Test
public void measurements_structure() {
CaliperResultsPreprocessor preprocessor = new CaliperResultsPreprocessor(caliperJson);
JsonObject results = preprocessor.getResults();
replacedertFalse(results.get("measurements").asArray().isEmpty());
JsonObject measurement = results.get("measurements").asArray().get(0).asObject();
replacedertEquals(asList("variables", "units", "values"), measurement.names());
replacedertTrue(measurement.get("variables").asObject().names().contains("vm"));
replacedertTrue(measurement.get("units").asObject().names().contains("ns"));
replacedertTrue(measurement.get("values").asArray().get(0).isNumber());
}
}
19
Source : CaliperRunner.java
with MIT License
from zcash-community
with MIT License
from zcash-community
private void createJsonFile() throws IOException {
JsonObject caliperJson = JsonObject.readFrom(readFromFile(resultsFile));
String resultsJson = new CaliperResultsPreprocessor(caliperJson).getResults().toString();
writeToFile(resultsJson, resultsFile);
}
19
Source : CaliperResultsPreprocessor.java
with MIT License
from zcash-community
with MIT License
from zcash-community
/**
* Transforms caliper v0.5 results JSON files into a small, generic data structure.
*/
clreplaced CaliperResultsPreprocessor {
// Caliper JSON structure example:
// -------------------------------
// {}
// run: {}
// benchmarkName: "com.eclipsesource.json.performancetest.ReadWriteBenchmark"
// executedTimestamp: "2013-08-29T15:17:27UTC"
// measurements: []
// {}
// k: {}
// variables: {}
// vm: "java"
// trial: "0"
// benchmark: "ReadFromString"
// input: "long-string"
// parser: "org-json"
// v: {}
// measurementSetMap: {}
// TIME: {}
// measurements: []
// {}
// raw: 5640.85597996243
// processed: 5640.85597996243
// unitNames: {}
// ns: 1
// s: 1000000000
// ms: 1000000
// us: 1000
// ...
// unitNames: {}
// ns: 1
// s: 1000000000
// ms: 1000000
// us: 1000
// systemOutCharCount: 0
// systemErrCharCount: 0
// eventLogMap: {}
// TIME: "starting Scenario{vm=java, trial=0, benchmark=ReadFromString, input=...
// ...
// environment: {}
// propertyMap: {}
// jre.vmname: "Java HotSpot(TM) 64-Bit Server VM"
// host.cpu.names: "[Intel(R) Core(TM) i5-3320M CPU @ 2.60GHz x 4]"
// jre.version: "1.6.0_32-ea-b03"
// host.cpu.cores: "[2 x 4]"
// jre.availableProcessors: "4"
// os.name: "Linux"
// jre.vmversion: "20.7-b02"
// host.memory.swap: "[6183932 kB]"
// os.version: "3.5.0-25-generic"
// host.cpu.cachesize: "[3072 KB x 4]"
// host.cpus: "4"
// host.name: "kelvin"
// os.arch: "amd64"
// host.memory.physical: "[7871592 kB]"
//
// Corresponding output:
// ---------------------
// {}
// name: "ReadWriteBenchmark"
// details: {}
// benchmark.clreplacedname: "com.eclipsesource.json.performancetest.ReadWriteBenchmark"
// benchmark.executionTime: "2013-08-29T15:17:27UTC"
// jre.vmname: "Java HotSpot(TM) 64-Bit Server VM"
// host.cpu.names: "[Intel(R) Core(TM) i5-3320M CPU @ 2.60GHz x 4]"
// jre.version: "1.6.0_32-ea-b03"
// host.cpu.cores: "[2 x 4]"
// jre.availableProcessors: "4"
// os.name: "Linux"
// jre.vmversion: "20.7-b02"
// host.memory.swap: "[6183932 kB]"
// os.version: "3.5.0-25-generic"
// host.cpu.cachesize: "[3072 KB x 4]"
// host.cpus: "4"
// host.name: "kelvin"
// os.arch: "amd64"
// host.memory.physical: "[7871592 kB]"
// measurements: []
// {}
// variables: {}
// vm: "java"
// trial: "0"
// benchmark: "ReadFromString"
// input: "long-string"
// parser: "org-json"
// units: {}
// ns: 1
// s: 1000000000
// ms: 1000000
// us: 1000
// values: []
// 5640.85597996243
// ...
// ...
private final JsonObject results;
CaliperResultsPreprocessor(JsonObject results) {
this.results = transformResults(results);
}
JsonObject getResults() {
return new JsonObject(results);
}
private static JsonObject transformResults(JsonObject caliperResults) {
return new JsonObject().add("name", extractSimpleName(caliperResults)).add("details", extractEnvironment(caliperResults)).add("measurements", extractMeasurements(caliperResults));
}
private static JsonValue extractBenchmarkName(JsonObject caliperResults) {
return caliperResults.get("run").asObject().get("benchmarkName");
}
private static JsonValue extractSimpleName(JsonObject caliperResults) {
String name = caliperResults.get("run").asObject().get("benchmarkName").replacedtring();
return Json.value(name.replaceFirst(".*\\.", ""));
}
private static JsonValue extractTimestamp(JsonObject caliperResults) {
return caliperResults.get("run").asObject().get("executedTimestamp");
}
private static JsonValue extractEnvironment(JsonObject caliperResults) {
JsonObject details = caliperResults.get("environment").asObject().get("propertyMap").asObject();
details.add("benchmark.clreplacedname", extractBenchmarkName(caliperResults));
details.add("benchmark.executionTime", extractTimestamp(caliperResults));
return details;
}
private static JsonArray extractMeasurements(JsonObject caliperResults) {
JsonArray result = new JsonArray();
JsonArray measurements = caliperResults.get("run").asObject().get("measurements").asArray();
for (JsonValue measurement : measurements) {
result.add(extractMeasurement(measurement.asObject()));
}
return result;
}
private static JsonObject extractMeasurement(JsonObject measurement) {
JsonObject times = measurement.get("v").asObject().get("measurementSetMap").asObject().get("TIME").asObject();
return new JsonObject().add("variables", measurement.get("k").asObject().get("variables")).add("units", times.get("unitNames")).add("values", extractTimes(times.get("measurements").asArray()));
}
private static JsonValue extractTimes(JsonArray measurements) {
JsonArray result = new JsonArray();
for (JsonValue measurement : measurements) {
result.add(measurement.asObject().get("processed"));
}
return result;
}
}
19
Source : CaliperResultsPreprocessor.java
with MIT License
from zcash-community
with MIT License
from zcash-community
private static JsonObject transformResults(JsonObject caliperResults) {
return new JsonObject().add("name", extractSimpleName(caliperResults)).add("details", extractEnvironment(caliperResults)).add("measurements", extractMeasurements(caliperResults));
}
19
Source : Body.java
with GNU General Public License v3.0
from wallarm
with GNU General Public License v3.0
from wallarm
private KeyValuePair getJWTFromBodyWithJson() {
JsonObject obj;
try {
if (body.length() < 2) {
return null;
}
obj = Json.parse(body).asObject();
} catch (Exception e) {
return null;
}
return lookForJwtInJsonObject(obj);
}
19
Source : Lang.java
with Apache License 2.0
from Ph1Lou
with Apache License 2.0
from Ph1Lou
public Map<String, String> loadTranslations(final String file) {
final JsonObject jsonObject = Json.parse(file).asObject();
return this.loadTranslationsRec("", jsonObject, new HashMap<>());
}
19
Source : ConversationNodeBuilder.java
with MIT License
from pdtyreus
with MIT License
from pdtyreus
@Override
public ConversationNode nodeFromJson(Integer id, String type, JsonObject metadata) throws IOException {
ConversationNode conversationNode = new ConversationNode(id, metadata);
return conversationNode;
}
19
Source : TrntChkActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void start(JsonObject jso) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
final TrntChkMode mode = TrntChkMode.valueOf(session.getUser().getSettings().getProperty(SettingsEnum.trntchk_mode, "FILENAME"));
final boolean removeUnknownFiles = session.getUser().getSettings().getProperty(SettingsEnum.trntchk_remove_unknown_files, false);
final boolean removeWrongSizedFiles = session.getUser().getSettings().getProperty(SettingsEnum.trntchk_remove_wrong_sized_files, false);
final boolean detectArchivedFolders = session.getUser().getSettings().getProperty(SettingsEnum.trntchk_detect_archived_folders, true);
session.getWorker().progress = new ProgressActions(ws);
try {
SDRList sdrl = SrcDstResult.fromJSON(session.getUser().getSettings().getProperty(SettingsEnum.trntchk_sdr, "[]"));
try {
new TorrentChecker(session, session.getWorker().progress, sdrl, mode, new ResultColUpdater() {
@Override
public void updateResult(int row, String result) {
sdrl.get(row).result = result;
session.getUser().getSettings().setProperty(SettingsEnum.trntchk_sdr, SrcDstResult.toJSON(sdrl));
session.getUser().getSettings().saveSettings();
TrntChkActions.this.updateResult(row, result);
}
@Override
public void clearResults() {
sdrl.forEach(sdr -> sdr.result = "");
session.getUser().getSettings().setProperty(SettingsEnum.trntchk_sdr, SrcDstResult.toJSON(sdrl));
session.getUser().getSettings().saveSettings();
TrntChkActions.this.clearResults();
}
}, removeUnknownFiles, removeWrongSizedFiles, detectArchivedFolders);
} catch (IOException e) {
Log.err(e.getMessage(), e);
}
} catch (BreakException e) {
} finally {
TrntChkActions.this.end();
session.getWorker().progress.close();
session.getWorker().progress = null;
session.setLastAction(new Date());
}
}))).start();
}
19
Source : ProfileActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void fix(JsonObject jso) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
session.getWorker().progress = new ProgressActions(ws);
try {
if (session.curr_profile.hasPropsChanged()) {
session.curr_scan = new Scan(session.curr_profile, session.getWorker().progress);
boolean needfix = session.curr_scan.actions.stream().mapToInt(Collection::size).sum() > 0;
if (!needfix)
return;
}
final Fix fix = new Fix(session.curr_profile, session.curr_scan, session.getWorker().progress);
fixed(fix);
} finally {
ScanAutomation automation = ScanAutomation.valueOf(session.curr_profile.settings.getProperty(SettingsEnum.automation_scan, ScanAutomation.SCAN.toString()));
if (automation.hreplacedcanAgain())
scan(jso, false);
session.getWorker().progress.close();
session.getWorker().progress = null;
session.setLastAction(new Date());
}
}))).start();
}
19
Source : ProfileActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void load(JsonObject jso) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
if (session.curr_profile != null)
session.curr_profile.saveSettings();
session.getWorker().progress = new ProgressActions(ws);
try {
JsonObject jsobj = jso.get("params").asObject();
val file = getAbsolutePath(jsobj.getString("parent", null)).resolve(jsobj.getString("file", null));
session.curr_profile = jrm.profile.Profile.load(session, file.toFile(), session.getWorker().progress);
if (session.curr_profile != null) {
session.curr_profile.nfo.save(session);
session.report.setProfile(session.curr_profile);
loaded(session.curr_profile);
new CatVerActions(ws).loaded(session.curr_profile);
new NPlayersActions(ws).loaded(session.curr_profile);
}
} catch (BreakException ex) {
} finally {
session.getWorker().progress.close();
session.getWorker().progress = null;
session.setLastAction(new Date());
}
}))).start();
}
19
Source : ProfileActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void imprt(JsonObject jso) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
session.getWorker().progress = new ProgressActions(ws);
session.getWorker().progress.canCancel(false);
// $NON-NLS-1$
session.getWorker().progress.setProgress(session.msgs.getString("MainFrame.ImportingFromMame"), -1);
try {
JsonObject jsobj = jso.get("params").asObject();
String filename = FindCmd.findMame();
if (filename != null) {
final boolean sl = jsobj.getBoolean("sl", false);
final Import imprt = new Import(session, new File(filename), sl, session.getWorker().progress);
if (imprt.file != null) {
final File parent = getAbsolutePath(Optional.ofNullable(jsobj.get("parent")).filter(JsonValue::isString).map(JsonValue::replacedtring).orElse(session.getUser().getSettings().getWorkPath().toString())).toFile();
final File file = new File(parent, imprt.file.getName());
FileUtils.copyFile(imprt.file, file);
final ProfileNFO pnfo = ProfileNFO.load(session, file);
pnfo.mame.set(imprt.org_file, sl);
if (imprt.roms_file != null) {
FileUtils.copyFileToDirectory(imprt.roms_file, parent);
pnfo.mame.fileroms = new File(parent, imprt.roms_file.getName());
if (sl) {
if (imprt.sl_file != null) {
FileUtils.copyFileToDirectory(imprt.sl_file, parent);
pnfo.mame.filesl = new File(parent, imprt.sl_file.getName());
} else
new GlobalActions(ws).warn("Could not import softwares list");
}
pnfo.save(session);
imported(pnfo.file);
} else {
new GlobalActions(ws).warn("Could not import roms list");
file.delete();
}
} else
new GlobalActions(ws).warn("Could not import anything from Mame");
} else
new GlobalActions(ws).warn("Mame not found in system's search path");
} catch (BreakException ex) {
} catch (IOException e) {
Log.err(e.getMessage(), e);
new GlobalActions(ws).warn(e.getMessage());
} finally {
session.getWorker().progress.close();
session.getWorker().progress = null;
session.setLastAction(new Date());
}
}))).start();
}
19
Source : ProfileActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void scan(JsonObject jso, final boolean automate) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
session.getWorker().progress = new ProgressActions(ws);
try {
session.curr_scan = new Scan(session.curr_profile, session.getWorker().progress);
} catch (BreakException ex) {
}
session.getWorker().progress.close();
session.getWorker().progress = null;
session.setLastAction(new Date());
ScanAutomation automation = ScanAutomation.valueOf(session.curr_profile.settings.getProperty(SettingsEnum.automation_scan, ScanAutomation.SCAN.toString()));
scanned(session.curr_scan, automation.hasReport());
if (automate) {
if (session.curr_scan != null && session.curr_scan.actions.stream().mapToInt(Collection::size).sum() > 0 && automation.hasFix()) {
fix(jso);
}
}
}))).start();
}
19
Source : GlobalActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
@SuppressWarnings("serial")
public void setMemory(JsonObject jso) {
try {
if (ws.isOpen()) {
final Runtime rt = Runtime.getRuntime();
// $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
String msg = (String.format(ws.getSession().getMsgs().getString("MainFrame.MemoryUsage"), String.format("%.2f MiB", rt.totalMemory() / 1048576.0), String.format("%.2f MiB", (rt.totalMemory() - rt.freeMemory()) / 1048576.0), String.format("%.2f MiB", rt.freeMemory() / 1048576.0), String.format("%.2f MiB", rt.maxMemory() / 1048576.0)));
ws.send(new JsonObject() {
{
add("cmd", "Global.setMemory");
add("params", new JsonObject() {
{
add("msg", msg);
}
});
}
}.toString());
}
} catch (IOException e) {
Log.err(e.getMessage(), e);
}
}
19
Source : GlobalActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void gc(JsonObject jso) {
System.gc();
setMemory(jso);
}
19
Source : Dir2DatActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void start(JsonObject jso) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
session.getWorker().progress = new ProgressActions(ws);
try {
String srcdir = session.getUser().getSettings().getProperty(jrm.misc.SettingsEnum.dir2dat_src_dir, null);
String dstdat = session.getUser().getSettings().getProperty(jrm.misc.SettingsEnum.dir2dat_dst_file, null);
String format = session.getUser().getSettings().getProperty(jrm.misc.SettingsEnum.dir2dat_format, "MAME");
JsonObject opts = jso.get("params").asObject().get("options").asObject();
EnumSet<DirScan.Options> options = EnumSet.of(Options.USE_PARALLELISM, Options.MD5_DISKS, Options.SHA1_DISKS);
if (// $NON-NLS-1$
opts.getBoolean("dir2dat.scan_subfolders", true))
options.add(Options.RECURSE);
if (// $NON-NLS-1$
!opts.getBoolean("dir2dat.deep_scan", false))
options.add(Options.IS_DEST);
if (// $NON-NLS-1$
opts.getBoolean("dir2dat.add_md5", false))
options.add(Options.NEED_MD5);
if (// $NON-NLS-1$
opts.getBoolean("dir2dat.add_sha1", false))
options.add(Options.NEED_SHA1);
if (// $NON-NLS-1$
opts.getBoolean("dir2dat.junk_folders", false))
options.add(Options.JUNK_SUBFOLDERS);
if (// $NON-NLS-1$
opts.getBoolean("dir2dat.do_not_scan_archives", false))
options.add(Options.ARCHIVES_AND_CHD_AS_ROMS);
if (// $NON-NLS-1$
opts.getBoolean("dir2dat.match_profile", false))
options.add(Options.MATCH_PROFILE);
if (// $NON-NLS-1$
opts.getBoolean("dir2dat.include_empty_dirs", false))
options.add(Options.EMPTY_DIRS);
HashMap<String, String> headers = new HashMap<>();
JsonObject hdrs = jso.get("params").asObject().get("headers").asObject();
hdrs.forEach(m -> {
if (!m.getValue().isNull())
headers.put(m.getName(), m.getValue().replacedtring());
});
if (srcdir != null && dstdat != null)
new Dir2Dat(ws.getSession(), new File(srcdir), new File(dstdat), session.getWorker().progress, options, ExportType.valueOf(format), headers);
} catch (BreakException e) {
} finally {
Dir2DatActions.this.end();
session.curr_profile = null;
session.curr_scan = null;
session.getWorker().progress.close();
session.getWorker().progress = null;
session.setLastAction(new Date());
}
}))).start();
}
19
Source : Dat2DirActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void start(JsonObject jso) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
boolean dryrun = session.getUser().getSettings().getProperty(SettingsEnum.dat2dir_dry_run, true);
session.getWorker().progress = new ProgressActions(ws);
try {
String[] srcdirs = StringUtils.split(session.getUser().getSettings().getProperty(SettingsEnum.dat2dir_srcdirs, ""), '|');
if (srcdirs.length > 0) {
SDRList sdrl = SrcDstResult.fromJSON(session.getUser().getSettings().getProperty(SettingsEnum.dat2dir_sdr, "[]"));
if (sdrl.stream().filter((sdr) -> !session.getUser().getSettings().getProfileSettingsFile(PathAbstractor.getAbsolutePath(session, sdr.src).toFile()).exists()).count() > 0)
// $NON-NLS-1$
new GlobalActions(ws).warn(ws.getSession().getMsgs().getString("MainFrame.AllDatsPresetsreplacedigned"));
else {
new DirUpdater(session, sdrl, session.getWorker().progress, Stream.of(srcdirs).map(s -> PathAbstractor.getAbsolutePath(session, s).toFile()).collect(Collectors.toList()), new ResultColUpdater() {
@Override
public void updateResult(int row, String result) {
sdrl.get(row).result = result;
session.getUser().getSettings().setProperty(SettingsEnum.dat2dir_sdr, SrcDstResult.toJSON(sdrl));
session.getUser().getSettings().saveSettings();
Dat2DirActions.this.updateResult(row, result);
}
@Override
public void clearResults() {
sdrl.forEach(sdr -> sdr.result = "");
session.getUser().getSettings().setProperty(SettingsEnum.dat2dir_sdr, SrcDstResult.toJSON(sdrl));
session.getUser().getSettings().saveSettings();
Dat2DirActions.this.clearResults();
}
}, dryrun);
}
} else
new GlobalActions(ws).warn(ws.getSession().getMsgs().getString("MainFrame.AtLeastOneSrcDir"));
} catch (BreakException e) {
} finally {
Dat2DirActions.this.end();
session.curr_profile = null;
session.curr_scan = null;
session.getWorker().progress.close();
session.getWorker().progress = null;
session.setLastAction(new Date());
}
}))).start();
}
19
Source : CompressorActions.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public void start(JsonObject jso) {
(ws.getSession().setWorker(new Worker(() -> {
WebSession session = ws.getSession();
final CompressorFormat format = CompressorFormat.valueOf(session.getUser().getSettings().getProperty(SettingsEnum.compressor_format, "TZIP"));
final boolean force = session.getUser().getSettings().getProperty(SettingsEnum.compressor_force, false);
final var use_parallelism = true;
final var nThreads = use_parallelism ? session.getUser().getSettings().getProperty(SettingsEnum.thread_count, -1) : 1;
session.getWorker().progress = new ProgressActions(ws);
session.getWorker().progress.setInfos(Math.min(Runtime.getRuntime().availableProcessors(), ws.getSession().getCachedCompressorList().size()), true);
try {
clearResults();
final AtomicInteger cnt = new AtomicInteger();
final Compressor compressor = new Compressor(session, cnt, ws.getSession().getCachedCompressorList().size(), session.getWorker().progress);
List<FileResult> values = new ArrayList<>(ws.getSession().getCachedCompressorList().values());
new Mulreplacedhreading<Compressor.FileResult>(nThreads, fr -> {
if (session.getWorker().progress.isCancel())
return;
try {
final int i = values.indexOf(fr);
File file = PathAbstractor.getAbsolutePath(session, fr.file.toString()).toFile();
Compressor.UpdResultCallBack cb = txt -> updateResult(i, fr.result = txt);
Compressor.UpdSrcCallBack scb = src -> updateFile(i, fr.file = PathAbstractor.getRelativePath(session, src.toPath()));
switch(format) {
case SEVENZIP:
{
switch(FilenameUtils.getExtension(file.getName())) {
case "zip":
compressor.zip2SevenZip(file, cb, scb);
break;
case "7z":
if (force)
compressor.sevenZip2SevenZip(file, cb, scb);
else
cb.apply("Skipped");
break;
default:
compressor.sevenZip2SevenZip(file, cb, scb);
break;
}
break;
}
case ZIP:
{
switch(FilenameUtils.getExtension(file.getName())) {
case "zip":
if (force)
compressor.zip2Zip(file, cb, scb);
else
cb.apply("Skipped");
break;
default:
compressor.sevenZip2Zip(file, false, cb, scb);
break;
}
break;
}
case TZIP:
{
switch(FilenameUtils.getExtension(file.getName())) {
case "zip":
compressor.zip2TZip(file, force, cb);
break;
default:
file = compressor.sevenZip2Zip(file, true, cb, scb);
if (file != null && file.exists())
compressor.zip2TZip(file, force, cb);
break;
}
break;
}
}
} catch (BreakException e) {
session.getWorker().progress.cancel();
;
} catch (final Throwable e) {
// oups! something unexpected happened
Log.err(e.getMessage(), e);
} finally {
cnt.incrementAndGet();
}
return;
}).start(ws.getSession().getCachedCompressorList().values().stream());
} catch (BreakException e) {
session.getWorker().progress.cancel();
;
} finally {
session.getWorker().progress.close();
CompressorActions.this.end();
}
}))).start();
}
19
Source : SrcDstResult.java
with GNU General Public License v2.0
from optyfr
with GNU General Public License v2.0
from optyfr
public JsonObject toJSONObject() {
JsonObject jso = Json.object();
// $NON-NLS-1$
jso.add("id", id != null ? id : UUID.randomUUID().toString());
// $NON-NLS-1$
jso.add("src", src != null ? src.toString() : null);
// $NON-NLS-1$
jso.add("dst", dst != null ? dst.toString() : null);
// $NON-NLS-1$
jso.add("result", result);
// $NON-NLS-1$
jso.add("selected", selected);
return jso;
}
19
Source : SyncSalesPersons.java
with MIT License
from Marketo
with MIT License
from Marketo
// the Java sample code on dev.marketo.com uses the minimal-json package
// minimal-json provides easy and fast representations of JSON
// for more information check out https://github.com/ralfstx/minimal-json
public clreplaced UpsertSalesPersons {
// Replace this with the host from Admin Web Services
public String marketoInstance = "CHANGE ME";
public String marketoIdURL = marketoInstance + "/idenreplacedy";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientId = "CHANGE ME";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientSecret = "CHANGE ME";
public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
// an array of salespersons to use for input. Each must have a member "externalsalespersonid".
public JsonObject[] input;
// specify the action to be undertaken, createOnly, updateOnly, createOrUpdate
public String action;
// select mode of Deduplication, dedupeFields for all dedupe parameters, idField for marketoId
public String dedupeBy;
public static void main(String[] args) {
UpsertSalesPersons upsert = new UpsertSalesPersons();
JsonObject salesperson = new JsonObject().add("name", "salesperson1").add("externalsalespersonid", "Opportunity1Test");
upsert.input = new JsonObject[] { salesperson };
String result = upsert.postData();
System.out.println(result);
}
public String postData() {
String result = null;
try {
// builds the Json Request Body
JsonObject requestBody = buildRequest();
// takes the endpoint URL and appends the access_token parameter to authenticate
String endpoint = marketoInstance + "/rest/v1/salespersons.json?access_token=" + getToken();
URL url = new URL(endpoint);
// Return a URL connection and cast to HttpsURLConnection
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-type", "application/json");
urlConn.setRequestProperty("accept", "text/json");
urlConn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
wr.write(requestBody.toString());
wr.flush();
// get the inputStream from the URL connection
InputStream inStream = urlConn.getInputStream();
result = convertStreamToString(inStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private JsonObject buildRequest() {
// Create a new JsonObject for the Request Body
JsonObject requestBody = new JsonObject();
// Create a JsonArray for the "input" member to hold Opp records
JsonArray in = new JsonArray();
for (JsonObject jo : input) {
// add our Opportunity records to the input array
in.add(jo);
}
requestBody.add("input", in);
if (this.action != null) {
// add the action member if available
requestBody.add("action", action);
}
if (this.dedupeBy != null) {
// add the dedupeBy member if available
requestBody.add("dedupeBy", dedupeBy);
}
return requestBody;
}
public String getToken() {
String token = null;
try {
URL url = new URL(idEndpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "application/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
Reader reader = new InputStreamReader(inStream);
JsonObject jsonObject = JsonObject.readFrom(reader);
token = jsonObject.get("access_token").replacedtring();
} else {
throw new IOException("Status: " + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String convertStreamToString(InputStream inputStream) {
try {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
return "";
}
}
}
19
Source : SyncSalesPersons.java
with MIT License
from Marketo
with MIT License
from Marketo
public static void main(String[] args) {
UpsertSalesPersons upsert = new UpsertSalesPersons();
JsonObject salesperson = new JsonObject().add("name", "salesperson1").add("externalsalespersonid", "Opportunity1Test");
upsert.input = new JsonObject[] { salesperson };
String result = upsert.postData();
System.out.println(result);
}
19
Source : SyncCompanies.java
with MIT License
from Marketo
with MIT License
from Marketo
// the Java sample code on dev.marketo.com uses the minimal-json package
// minimal-json provides easy and fast representations of JSON
// for more information check out https://github.com/ralfstx/minimal-json
public clreplaced UpsertCompanies {
// Replace this with the host from Admin Web Services
public String marketoInstance = "CHANGE ME";
public String marketoIdURL = marketoInstance + "/idenreplacedy";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientId = "CHANGE ME";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientSecret = "CHANGE ME";
public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
// an array of companies to use for input. Each must have a member "externalcompanyid".
public JsonObject[] input;
// specify the action to be undertaken, createOnly, updateOnly, createOrUpdate
public String action;
// select mode of Deduplication, dedupeFields for all dedupe parameters, idField for marketoId
public String dedupeBy;
public static void main(String[] args) {
UpsertCompanies upsert = new UpsertCompanies();
JsonObject company = new JsonObject().add("name", "company1").add("externalcompanyid", "Opportunity1Test");
upsert.input = new JsonObject[] { company };
String result = upsert.postData();
System.out.println(result);
}
public String postData() {
String result = null;
try {
// builds the Json Request Body
JsonObject requestBody = buildRequest();
// takes the endpoint URL and appends the access_token parameter to authenticate
String endpoint = marketoInstance + "/rest/v1/companies.json?access_token=" + getToken();
URL url = new URL(endpoint);
// Return a URL connection and cast to HttpsURLConnection
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-type", "application/json");
urlConn.setRequestProperty("accept", "text/json");
urlConn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
wr.write(requestBody.toString());
wr.flush();
// get the inputStream from the URL connection
InputStream inStream = urlConn.getInputStream();
result = convertStreamToString(inStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private JsonObject buildRequest() {
// Create a new JsonObject for the Request Body
JsonObject requestBody = new JsonObject();
// Create a JsonArray for the "input" member to hold Opp records
JsonArray in = new JsonArray();
for (JsonObject jo : input) {
// add our Opportunity records to the input array
in.add(jo);
}
requestBody.add("input", in);
if (this.action != null) {
// add the action member if available
requestBody.add("action", action);
}
if (this.dedupeBy != null) {
// add the dedupeBy member if available
requestBody.add("dedupeBy", dedupeBy);
}
return requestBody;
}
public String getToken() {
String token = null;
try {
URL url = new URL(idEndpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "application/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
Reader reader = new InputStreamReader(inStream);
JsonObject jsonObject = JsonObject.readFrom(reader);
token = jsonObject.get("access_token").replacedtring();
} else {
throw new IOException("Status: " + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String convertStreamToString(InputStream inputStream) {
try {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
return "";
}
}
}
19
Source : SyncCompanies.java
with MIT License
from Marketo
with MIT License
from Marketo
public static void main(String[] args) {
UpsertCompanies upsert = new UpsertCompanies();
JsonObject company = new JsonObject().add("name", "company1").add("externalcompanyid", "Opportunity1Test");
upsert.input = new JsonObject[] { company };
String result = upsert.postData();
System.out.println(result);
}
19
Source : CreateSnippet.java
with MIT License
from Marketo
with MIT License
from Marketo
public clreplaced CreateSnippet {
// Replace this with the host from Admin Web Services
public String marketoInstance = "CHANGE ME";
public String marketoIdURL = marketoInstance + "/idenreplacedy";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientId = "CHANGE ME";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientSecret = "CHANGE ME";
public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
// name of new snippet, required
public String name;
// Json of folder with two members, id and type(Folder or Program), required
public JsonObject folder;
// description of snippet
public String description;
public static void main(String[] args) {
CreateSnippet snippet = new CreateSnippet();
snippet.name = "New Snipppet 2";
snippet.folder = new JsonObject().add("id", 5566).add("type", "Folder");
String result = snippet.postData();
System.out.println(result);
}
public String postData() {
String result = null;
try {
String requestBody = buildRequest();
String endpoint = marketoInstance + "/rest/replacedet/v1/snippets.json?access_token=" + getToken();
URL url = new URL(endpoint.toString());
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("accept", "text/json");
urlConn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
wr.write(requestBody);
wr.flush();
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
result = convertStreamToString(inStream);
} else {
result = "Status Code: " + responseCode;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String getToken() {
String token = null;
try {
URL url = new URL(idEndpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "application/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
Reader reader = new InputStreamReader(inStream);
JsonObject jsonObject = JsonObject.readFrom(reader);
token = jsonObject.get("access_token").replacedtring();
} else {
throw new IOException("Status: " + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String buildRequest() {
StringBuilder sb = new StringBuilder();
sb.append("&name=" + name);
sb.append("&folder=" + folder.toString());
if (description != null) {
sb.append("&description=" + description);
}
System.out.println(sb);
return sb.toString();
}
private String convertStreamToString(InputStream inputStream) {
try {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
return "";
}
}
}
19
Source : CloneSnippet.java
with MIT License
from Marketo
with MIT License
from Marketo
// the Java sample code on dev.marketo.com uses the minimal-json package
// minimal-json provides easy and fast representations of JSON
// for more information check out https://github.com/ralfstx/minimal-json
public clreplaced CloneSnippet {
// Replace this with the host from Admin Web Services
public String marketoInstance = "CHANGE ME";
public String marketoIdURL = marketoInstance + "/idenreplacedy";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientId = "CHANGE ME";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientSecret = "CHANGE ME";
public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
// id of snippet to clone from
public int id;
// name of new snippet
public String name;
// Json of new parent folder with two members, id and type(Folder or Program)
public JsonObject folder;
// new description
public String description;
public static void main(String[] args) {
CloneSnippet email = new CloneSnippet();
email.id = 7;
email.name = "clone";
email.folder = new JsonObject().add("id", 5566).add("type", "Folder");
String result = email.postData();
System.out.println(result);
}
private String postData() {
String data = null;
try {
// replacedemble the URL
StringBuilder endpoint = new StringBuilder(marketoInstance + "/rest/replacedet/v1/snippet/" + id + "/clone.json?access_token=" + getToken() + "&name=" + name + "&folder=" + folder);
// append optional parameters
if (description != null) {
endpoint.append("&description" + description);
}
URL url = new URL(endpoint.toString());
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("accept", "text/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
data = convertStreamToString(inStream);
} else {
data = "Status:" + responseCode;
}
} catch (MalformedURLException e) {
System.out.println("URL not valid.");
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
e.printStackTrace();
}
return data;
}
public String getToken() {
String token = null;
try {
URL url = new URL(idEndpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "application/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
Reader reader = new InputStreamReader(inStream);
JsonObject jsonObject = JsonObject.readFrom(reader);
token = jsonObject.get("access_token").replacedtring();
} else {
throw new IOException("Status: " + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String convertStreamToString(InputStream inputStream) {
try {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
return "";
}
}
}
19
Source : DeleteProgram.java
with MIT License
from Marketo
with MIT License
from Marketo
public String bodyBuilder() {
JsonObject body = new JsonObject();
return body.toString();
}
19
Source : CloneProgram.java
with MIT License
from Marketo
with MIT License
from Marketo
// the Java sample code on dev.marketo.com uses the minimal-json package
// minimal-json provides easy and fast representations of JSON
// for more information check out https://github.com/ralfstx/minimal-json
public clreplaced CloneProgram {
// Replace this with the host from Admin Web Services
public String marketoInstance = "https://299-BYM-827.mktorest.com";
public String marketoIdURL = marketoInstance + "/idenreplacedy";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientId = "b417d98f-9289-47d1-a61f-db141bf0267f";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientSecret = "0DipOvz4h2wP1ANeVjlfwMvECJpo0ZYc";
public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
// id of source program to clone
public int id;
// name of resulting program
public String name;
// parent folder with id and type
public JsonObject folders;
// description of resulting program
public String programDescription;
public static void main(String[] args) {
CloneProgram program = new CloneProgram();
program.id = 1056;
program.name = "Cloned Program";
program.folders = new JsonObject().add("id", 1001).add("type", "Folder");
String result = program.postData();
System.out.println(result);
}
// Make Request
public String postData() {
String result = null;
try {
String endpoint = marketoInstance + "/rest/replacedet/v1/program/" + id + "/clone.json";
String body = bodyBuilder();
URL url = new URL(endpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("accept", "text/json");
urlConn.setRequestProperty("Content-Type", "application/x-www-url-formencoded");
urlConn.setRequestProperty("Authorization", "Bearer " + getToken());
urlConn.setDoOutput(true);
Writer wr = new OutputStreamWriter(urlConn.getOutputStream());
wr.write(body);
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
result = convertStreamToString(inStream);
} else {
result = "Status Code: " + responseCode;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public String bodyBuilder() {
StringBuilder body = new StringBuilder();
body.append("name=" + name + "&folders=" + folders.toString());
if (programDescription != null) {
body.append("&programDescription=" + programDescription);
}
return body.toString();
}
public String getToken() {
String token = null;
try {
URL url = new URL(idEndpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "application/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
Reader reader = new InputStreamReader(inStream);
JsonObject jsonObject = JsonObject.readFrom(reader);
token = jsonObject.get("access_token").replacedtring();
} else {
throw new IOException("Status: " + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String convertStreamToString(InputStream inputStream) {
try {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
return "";
}
}
}
19
Source : GetLandingPageTemplates.java
with MIT License
from Marketo
with MIT License
from Marketo
// the Java sample code on dev.marketo.com uses the minimal-json package
// minimal-json provides easy and fast representations of JSON
// for more information check out https://github.com/ralfstx/minimal-json
public clreplaced MultipleLandingPageTemplates {
// Replace this with the host from Admin Web Services
public String marketoInstance = "CHANGE ME";
public String marketoIdURL = marketoInstance + "/idenreplacedy";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientId = "CHANGE ME";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientSecret = "CHANGE ME";
public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
// optional status filter
public String status;
// offset returned from previous call
public String offset;
// max number of templates to return
public Integer maxreturn;
// folder with two members, id and type(Folder or Program), optional
public JsonObject folder;
public static void main(String[] args) {
MultipleLandingPageTemplates templates = new MultipleLandingPageTemplates();
templates.maxreturn = 20;
String result = templates.getData();
System.out.println(result);
}
private String getData() {
String data = null;
try {
// replacedemble the URL
StringBuilder endpoint = new StringBuilder(marketoInstance + "/rest/replacedet/v1/landingPageTemplates.json?access_token=" + getToken());
// append optional params
if (offset != null) {
endpoint.append("&offset=" + offset);
}
if (maxreturn != null) {
endpoint.append("&maxreturn=" + maxreturn);
}
if (status != null) {
endpoint.append("&status=" + status);
}
if (folder != null) {
endpoint.append("&folder=" + folder.toString());
}
URL url = new URL(endpoint.toString());
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "text/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
data = convertStreamToString(inStream);
} else {
data = "Status:" + responseCode;
}
} catch (MalformedURLException e) {
System.out.println("URL not valid.");
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
e.printStackTrace();
}
return data;
}
public String getToken() {
String token = null;
try {
URL url = new URL(idEndpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "application/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
Reader reader = new InputStreamReader(inStream);
JsonObject jsonObject = JsonObject.readFrom(reader);
token = jsonObject.get("access_token").replacedtring();
} else {
throw new IOException("Status: " + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String convertStreamToString(InputStream inputStream) {
try {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
return "";
}
}
}
19
Source : CreateLandingPageTemplate.java
with MIT License
from Marketo
with MIT License
from Marketo
// the Java sample code on dev.marketo.com uses the minimal-json package
// minimal-json provides easy and fast representations of JSON
// for more information check out https://github.com/ralfstx/minimal-json
public clreplaced CreateLandingPageTemplate {
// Replace this with the host from Admin Web Services
public String marketoInstance = "CHANGE ME";
public String marketoIdURL = marketoInstance + "/idenreplacedy";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientId = "CHANGE ME";
// Obtain from your Custom Service in Admin>Launchpoint
public String clientSecret = "CHANGE ME";
public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;
// path of the file to retrieve content from
public String file;
// folder with id and type(Folder or Program)
public JsonObject folder;
// name of new template
public String name;
public static void main(String[] args) {
CreateLandingPageTemplate create = new CreateLandingPageTemplate();
create.folder = new JsonObject();
create.folder.add("id", 12);
create.folder.add("type", "Folder");
create.name = "New LP Template";
create.file = "C:\\LandingPageContent\\template.html";
String result = create.postData();
System.out.println(result);
}
// Make Request
public String postData() {
String result = null;
String boundary = "mktoBoundary" + String.valueOf(System.currentTimeMillis());
try {
// Read target file
String requestBody = readFile(file);
// replacedemble the URL
String endpoint = marketoInstance + "/rest/replacedet/v1/landingPageTemplates.json?access_token=" + getToken();
System.out.println(endpoint);
URL url = new URL(endpoint.toString());
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConn.setRequestProperty("accept", "text/json");
urlConn.setDoOutput(true);
PrintWriter wr = new PrintWriter(new OutputStreamWriter(urlConn.getOutputStream()));
// format content as multpart and insert into output stream
addMultipart(boundary, requestBody, wr, "content", "text/html");
addMultipart(boundary, folder.toString(), wr, "folder");
addMultipart(boundary, name, wr, "name");
closeMultipart(boundary, wr);
wr.flush();
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
result = convertStreamToString(inStream);
} else {
result = "Status Code: " + responseCode;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
// Add content as multipart form-data
private void addMultipart(String boundary, String requestBody, PrintWriter wr, String paramName, String contentType) {
wr.append("--" + boundary + "\r\n");
wr.append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + file + "\"");
wr.append("\r\n");
wr.append("Content-type: " + contentType + "; charset=\"utf-8\"\r\n");
wr.append("\r\n");
wr.append(requestBody);
wr.append("\r\n");
}
private void addMultipart(String boundary, String requestBody, PrintWriter wr, String paramName) {
wr.append("--" + boundary + "\r\n");
wr.append("Content-Disposition: form-data; name=\"" + paramName + "\"");
wr.append("\r\n");
wr.append("Content-type: text/plain; charset=\"utf-8\"\r\n");
wr.append("\r\n");
wr.append(requestBody);
wr.append("\r\n");
}
// close multipart content
private void closeMultipart(String boundary, PrintWriter wr) {
wr.append("--" + boundary);
}
private String readFile(String filePath) {
String fileOutPut = null;
try {
FileReader fr = new FileReader(filePath);
BufferedReader br = new BufferedReader(fr);
char[] arr = new char[8 * 4096];
StringBuilder buffer = new StringBuilder();
int numCharsRead;
while ((numCharsRead = br.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, numCharsRead);
}
fileOutPut = buffer.toString();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileOutPut;
}
public String getToken() {
String token = null;
try {
URL url = new URL(idEndpoint);
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setRequestProperty("accept", "application/json");
int responseCode = urlConn.getResponseCode();
if (responseCode == 200) {
InputStream inStream = urlConn.getInputStream();
Reader reader = new InputStreamReader(inStream);
JsonObject jsonObject = JsonObject.readFrom(reader);
token = jsonObject.get("access_token").replacedtring();
} else {
throw new IOException("Status: " + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
private String convertStreamToString(InputStream inputStream) {
try {
return new Scanner(inputStream).useDelimiter("\\A").next();
} catch (NoSuchElementException e) {
return "";
}
}
}
19
Source : LinkedInErrorMessageException.java
with Apache License 2.0
from ebx
with Apache License 2.0
from ebx
/**
* Abstract clreplaced to provide access to the JSON LinkedIn provides in case of an error
*
* @author Joanna
*/
public abstract clreplaced LinkedInErrorMessageException extends LinkedInException {
/**
* Default serial version UID
*/
private static final long serialVersionUID = 1L;
private JsonObject rawErrorJson;
/**
* Initialise the LinkedIn error message exception
* @param message message
*/
public LinkedInErrorMessageException(String message) {
super(message);
}
/**
* Initialise the LinkedIn error message exception
* @param message The message
* @param cause The cause
*/
public LinkedInErrorMessageException(String message, Throwable cause) {
super(message, cause);
}
/**
* Return the raw error as JSON, may be <code>null</code>
*
* @return raw error
*/
public JsonObject getRawErrorJson() {
return rawErrorJson;
}
/**
* Sets the raw error as JSON.
*
* @param rawError the raw error
*/
protected void setRawErrorJson(JsonObject rawError) {
rawErrorJson = rawError;
}
}
19
Source : LinkedInErrorMessageException.java
with Apache License 2.0
from ebx
with Apache License 2.0
from ebx
/**
* Sets the raw error as JSON.
*
* @param rawError the raw error
*/
protected void setRawErrorJson(JsonObject rawError) {
rawErrorJson = rawError;
}
19
Source : DefaultLinkedInClient.java
with Apache License 2.0
from ebx
with Apache License 2.0
from ebx
/**
* Throws an exception if LinkedIn returned an error response.
* This method extracts relevant information from the error JSON and throws an exception which
* encapsulates it for end-user consumption.
* For API errors:
* If the {@code error} JSON field is present, we've got a response status error for this API
* call.
*
* @param json
* The JSON returned by LinkedIn in response to an API call.
* @param httpStatusCode
* The HTTP status code returned by the server, e.g. 500.
* @throws LinkedInJsonMappingException
* If an error occurs while processing the JSON.
*/
protected void throwLinkedInResponseStatusExceptionIfNecessary(String json, Integer httpStatusCode) {
try {
skipResponseStatusExceptionParsing(json);
JsonObject errorObject = Json.parse(json).asObject();
// If there's an Integer error code, pluck it out.
Integer errorCode = errorObject.get(ERROR_CODE_ATTRIBUTE_NAME) != null ? Integer.parseInt(errorObject.get(ERROR_CODE_ATTRIBUTE_NAME).toString()) : null;
if (linkedinExceptionMapper != null) {
throw linkedinExceptionMapper.exceptionForTypeAndMessage(errorCode, httpStatusCode, errorObject.getString(ERROR_MESSAGE_ATTRIBUTE_NAME, ""), false, errorObject);
}
} catch (ParseException e) {
throw new LinkedInJsonMappingException("Unable to process the LinkedIn API response", e);
} catch (ResponseErrorJsonParsingException ex) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("caught ResponseErrorJsonParsingException - ignoring", ex);
}
}
}
19
Source : ProxyJSONConfigParser.java
with Apache License 2.0
from dragonite-network
with Apache License 2.0
from dragonite-network
public clreplaced ProxyJSONConfigParser {
private final JsonObject jsonObject;
public ProxyJSONConfigParser(final JsonObject jsonObject) {
this.jsonObject = jsonObject;
}
public ProxyJSONConfigParser(final String file) throws IOException, JSONConfigException {
final String content = new String(Files.readAllBytes(Paths.get(file)));
try {
this.jsonObject = Json.parse(content).asObject();
} catch (final ParseException | UnsupportedOperationException e) {
throw new JSONConfigException("JSON Syntax Error");
}
}
public boolean isServerConfig() {
return jsonObject.getBoolean("server", false);
}
public ProxyServerConfig getServerConfig() throws JSONConfigException {
final String addr = jsonObject.getString("addr", null);
final int port = jsonObject.getInt("port", ProxyGlobalConstants.DEFAULT_SERVER_PORT);
final String preplacedword = jsonObject.getString("preplacedword", null);
if (preplacedword == null)
throw new JSONConfigException("Field \"preplacedword\" invalid or not found");
// that's all required
try {
final ProxyServerConfig config = new ProxyServerConfig(new InetSocketAddress(addr == null ? null : InetAddress.getByName(addr), port), preplacedword);
final int limit = jsonObject.getInt("limit", 0);
if (limit != 0)
config.setMbpsLimit(limit);
final String welcome = jsonObject.getString("welcome", null);
if (welcome != null)
config.setWelcomeMessage(welcome);
final boolean loopback = jsonObject.getBoolean("loopback", false);
if (loopback)
config.setAllowLoopback(true);
final int mtu = jsonObject.getInt("mtu", 0);
if (mtu != 0)
config.setMTU(mtu);
final int wndmlt = jsonObject.getInt("multiplier", 0);
if (wndmlt != 0)
config.setWindowMultiplier(wndmlt);
final int dscp = jsonObject.getInt("dscp", 0);
if (dscp != 0)
config.setTrafficClreplaced(UnitConverter.DSCPtoTrafficClreplaced(dscp));
final boolean enablePanel = jsonObject.getBoolean("webpanel", false);
if (enablePanel) {
config.setWebPanelEnabled(true);
final String panelAddr = jsonObject.getString("paneladdr", null);
final int panelPort = jsonObject.getInt("panelport", DragoniteGlobalConstants.WEB_PANEL_PORT);
if (panelAddr == null) {
config.setWebPanelBind(new InetSocketAddress(InetAddress.getLoopbackAddress(), panelPort));
} else {
config.setWebPanelBind(new InetSocketAddress(panelAddr, panelPort));
}
}
return config;
} catch (final IllegalArgumentException | UnknownHostException | EncryptionException e) {
throw new JSONConfigException("Failed to create configuration: " + e.getMessage());
}
}
public ProxyClientConfig getClientConfig() throws JSONConfigException {
final String addr = jsonObject.getString("addr", null);
if (addr == null)
throw new JSONConfigException("Field \"addr\" invalid or not found");
final int port = jsonObject.getInt("port", ProxyGlobalConstants.DEFAULT_SERVER_PORT);
final int socks5port = jsonObject.getInt("socks5port", ProxyGlobalConstants.SOCKS5_PORT);
final String preplacedword = jsonObject.getString("preplacedword", null);
if (preplacedword == null)
throw new JSONConfigException("Field \"preplacedword\" invalid or not found");
final int up = jsonObject.getInt("up", 0);
if (up == 0)
throw new JSONConfigException("Field \"up\" invalid or not found");
final int down = jsonObject.getInt("down", 0);
if (down == 0)
throw new JSONConfigException("Field \"down\" invalid or not found");
// that's all required
try {
final ProxyClientConfig config = new ProxyClientConfig(new InetSocketAddress(InetAddress.getByName(addr), port), socks5port, preplacedword, down, up);
final String aclPath = jsonObject.getString("acl", null);
final ParsedACL parsedACL;
if (aclPath != null) {
try {
parsedACL = ACLFileParser.parse(FileUtils.pathToReader(aclPath));
config.setAcl(parsedACL);
} catch (final IOException | ACLException e) {
throw new JSONConfigException(e.getMessage());
}
}
final int mtu = jsonObject.getInt("mtu", 0);
if (mtu != 0)
config.setMTU(mtu);
final int wndmlt = jsonObject.getInt("multiplier", 0);
if (wndmlt != 0)
config.setWindowMultiplier(wndmlt);
final int dscp = jsonObject.getInt("dscp", 0);
if (dscp != 0)
config.setTrafficClreplaced(UnitConverter.DSCPtoTrafficClreplaced(dscp));
final boolean enablePanel = jsonObject.getBoolean("webpanel", false);
if (enablePanel) {
config.setWebPanelEnabled(true);
final String panelAddr = jsonObject.getString("paneladdr", null);
final int panelPort = jsonObject.getInt("panelport", DragoniteGlobalConstants.WEB_PANEL_PORT);
if (panelAddr == null) {
config.setWebPanelBind(new InetSocketAddress(InetAddress.getLoopbackAddress(), panelPort));
} else {
config.setWebPanelBind(new InetSocketAddress(panelAddr, panelPort));
}
}
return config;
} catch (final IllegalArgumentException | UnknownHostException | EncryptionException e) {
throw new JSONConfigException("Failed to create configuration: " + e.getMessage());
}
}
}
19
Source : ObservationTest.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
private JsonObject awaitObservation(String observationId) {
// experimental. 20 seconds to process LRPT
int maxRetries = 40;
int curRetry = 0;
while (!Thread.currentThread().isInterrupted() && curRetry < maxRetries) {
JsonObject observation = client.getObservation(METEOR_ID, observationId);
if (observation != null && observation.get("numberOfDecodedPackets") != null) {
return observation;
}
try {
Thread.sleep(1000);
curRetry++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
return null;
}
19
Source : ObservationTest.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
private static void replacedertObservation(JsonObject observation) {
replacedertNotNull(observation);
replacedertEquals(144000, observation.getInt("sampleRate", 0));
replacedertEquals(288000, observation.getInt("inputSampleRate", 0));
replacedertEquals(137100000, observation.getInt("frequency", 0));
replacedertEquals(137100000, observation.getInt("actualFrequency", 0));
// do not replacedert numberOfDecodedPackets as file contains valid data
// there is no control on when test executed, so doppler correction might
// generate valid freq offset and numberOfDecodedPackets might NOT be 0
// replacedertEquals(0, observation.getInt("numberOfDecodedPackets", -1));
replacedertEquals("LRPT", observation.getString("decoder", null));
replacedertEquals(METEOR_ID, observation.getString("satellite", null));
}
19
Source : ValidationResult.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
public String toJson() {
JsonObject result = Json.object();
if (!isEmpty()) {
JsonObject errors = Json.object();
if (general != null) {
errors.add("general", general);
}
for (Entry<String, String> cur : entrySet()) {
errors.add(cur.getKey(), cur.getValue());
}
result.add("errors", errors);
}
return result.toString();
}
19
Source : Tle.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
public static Tle fromJson(JsonObject json) {
String[] raw = new String[3];
raw[0] = json.getString("line1", null);
raw[1] = json.getString("line2", null);
raw[2] = json.getString("line3", null);
return new Tle(raw);
}
19
Source : Tle.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
public JsonObject toJson() {
JsonObject json = new JsonObject();
if (raw.length > 0) {
json.add("line1", raw[0]);
}
if (raw.length > 1) {
json.add("line2", raw[1]);
}
if (raw.length > 2) {
json.add("line3", raw[2]);
}
return json;
}
19
Source : Observation.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
private static void addNullable(String name, String url, SignedURL signed, JsonObject json) {
if (url == null) {
return;
}
if (signed != null) {
json.add(name, signed.sign(url));
} else {
json.add(name, url);
}
}
19
Source : Observation.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
public JsonObject toJson(SignedURL signed) {
JsonObject json = new JsonObject();
json.add("id", getId());
json.add("start", getStartTimeMillis());
json.add("end", getEndTimeMillis());
json.add("sampleRate", getOutputSampleRate());
json.add("inputSampleRate", getInputSampleRate());
json.add("frequency", getSatelliteFrequency());
json.add("actualFrequency", getActualFrequency());
json.add("decoder", getSource().name());
json.add("satellite", getSatelliteId());
json.add("bandwidth", getBandwidth());
if (getTle() != null) {
json.add("tle", getTle().toJson());
}
if (getGroundStation() != null) {
json.add("groundStation", toJson(getGroundStation()));
}
if (getGain() != null) {
json.add("gain", getGain());
}
if (getChannelA() != null) {
json.add("channelA", getChannelA());
}
if (getChannelB() != null) {
json.add("channelB", getChannelB());
}
if (getNumberOfDecodedPackets() != null) {
json.add("numberOfDecodedPackets", getNumberOfDecodedPackets());
}
addNullable("aURL", getaURL(), signed, json);
addNullable("data", getDataURL(), signed, json);
addNullable("spectogramURL", getSpectogramURL(), signed, json);
addNullable("rawURL", getRawURL(), signed, json);
ObservationStatus statusToSave = getStatus();
if (statusToSave == null) {
// this would avoid double upload/decode of old observations
statusToSave = ObservationStatus.UPLOADED;
}
json.add("status", statusToSave.name());
json.add("biast", isBiast());
json.add("sdrType", sdrType.name());
json.add("centerBandFrequency", centerBandFrequency);
return json;
}
19
Source : Observation.java
with Apache License 2.0
from dernasherbrezon
with Apache License 2.0
from dernasherbrezon
private static GeodeticPoint groundStationFromJson(JsonObject json) {
double lat = json.getDouble("lat", Double.NaN);
double lon = json.getDouble("lon", Double.NaN);
return new GeodeticPoint(FastMath.toRadians(lat), FastMath.toRadians(lon), 0.0);
}
19
Source : Server.java
with Apache License 2.0
from datathings
with Apache License 2.0
from datathings
public clreplaced Server implements HttpHandler {
public static void main(String[] args) {
File dataDir;
if (System.getProperty("data") != null) {
dataDir = new File(System.getProperty("data"));
} else {
dataDir = new File("/Users/duke/dev/mwDB/plugins/benchmark/data");
}
final Server srv = new Server();
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
JsonArray runs = new JsonArray();
File[] files = dataDir.listFiles();
for (int i = 0; i < files.length; i++) {
try {
FileReader read = new FileReader(files[i]);
JsonObject run = (JsonObject) Json.parse(read);
runs.add(run);
} catch (Exception e) {
e.printStackTrace();
}
}
srv.root.set("runs", runs);
JsonObject charts = new JsonObject();
for (int i = 0; i < runs.size(); i++) {
JsonObject run = (JsonObject) runs.get(i);
JsonArray benchmarks = (JsonArray) run.get("benchmarks");
for (int j = 0; j < benchmarks.size(); j++) {
JsonObject benchmark = (JsonObject) benchmarks.get(j);
String benchmarkName = benchmark.getString("benchmark", "defaultBenchmark");
JsonObject chart = (JsonObject) charts.get(benchmarkName);
if (chart == null) {
chart = new JsonObject();
charts.set(benchmarkName, chart);
}
JsonArray metrics = (JsonArray) benchmark.get("metrics");
for (int k = 0; k < metrics.size(); k++) {
JsonObject metric = (JsonObject) metrics.get(k);
String metricName = metric.getString("name", "defaultMetric");
JsonArray chartLine = (JsonArray) chart.get(metricName);
if (chartLine == null) {
chartLine = new JsonArray();
chart.set(metricName, chartLine);
}
chartLine.add(new JsonObject().set("time", run.get("time")).set("value", metric.get("value")));
}
}
}
srv.root.set("charts", charts);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, 5, TimeUnit.MINUTES);
}
final int port = 9077;
final JsonObject root = new JsonObject();
public Server() {
Undertow server = Undertow.builder().addHttpListener(port, "0.0.0.0", Handlers.path().addPrefixPath("rpc", this).addPrefixPath("/", new ResourceHandler(new ClreplacedPathResourceManager(Server.clreplaced.getClreplacedLoader(), "static")).addWelcomeFiles("index.html").setDirectoryListingEnabled(false))).build();
server.start();
System.out.println("Server running at : 9077");
}
@Override
public void handleRequest(HttpServerExchange httpServerExchange) throws Exception {
if (httpServerExchange.getRequestPath().equals("/rpc/charts")) {
httpServerExchange.getResponseHeaders().add(new HttpString("Access-Control-Allow-Origin"), "*");
httpServerExchange.setStatusCode(StatusCodes.OK);
httpServerExchange.getResponseSender().send(root.get("charts").toString());
}
}
}
19
Source : WeatherDarkSkyAdapter.java
with Apache License 2.0
from AmyAssist
with Apache License 2.0
from AmyAssist
private WeatherReportDay convertDay(JsonObject toConvert, String timezone) {
String summary = toConvert.getString(JSON_NAME_SUMMARY, "null");
double precipProbability = toConvert.getDouble(JSON_NAME_PERCIP_PROB, Double.NaN);
String precipType = toConvert.getString(JSON_NAME_PERCIP_TYPE, "null");
double temperatureMin = toConvert.getDouble(JSON_NAME_TEMPERATUR_MIN, Double.NaN);
double temperatureMax = toConvert.getDouble(JSON_NAME_TEMPERATUR_MAX, Double.NaN);
long timestamp = toConvert.getLong(JSON_NAME_TIME, 0);
long sunrise = toConvert.getLong(JSON_NAME_SUNRISE, 0);
long sunset = toConvert.getLong(JSON_NAME_SUNSET, 0);
double windSpeed = toConvert.getDouble(JSON_NAME_WIND_SPEED, Double.NaN);
String iconType = toConvert.getString(JSON_NAME_ICON_TYPE, "null");
return new WeatherReportDay(trimQuotes(summary), precipProbability, trimQuotes(precipType), temperatureMin, temperatureMax, timestamp, sunrise, sunset, windSpeed, trimQuotes(iconType), timezone);
}
19
Source : WeatherDarkSkyAdapter.java
with Apache License 2.0
from AmyAssist
with Apache License 2.0
from AmyAssist
private WeatherReportInstant convertInstant(JsonObject toConvert) {
String summary = toConvert.getString(JSON_NAME_SUMMARY, "null");
double precipProbability = toConvert.getDouble(JSON_NAME_PERCIP_PROB, Double.NaN);
String precipType = toConvert.getString(JSON_NAME_PERCIP_TYPE, "null");
double temperature = toConvert.getDouble(JSON_NAME_TEMPERATUR, Double.NaN);
long timestamp = toConvert.getLong(JSON_NAME_TIME, 0);
double windSpeed = toConvert.getDouble(JSON_NAME_WIND_SPEED, Double.NaN);
String iconType = toConvert.getString(JSON_NAME_ICON_TYPE, "null");
return new WeatherReportInstant(trimQuotes(summary), precipProbability, trimQuotes(precipType), temperature, timestamp, windSpeed, trimQuotes(iconType));
}
19
Source : JsonStackTraceElementProcessor.java
with GNU General Public License v3.0
from actoron
with GNU General Public License v3.0
from actoron
/**
* Process an object.
* @param object The object.
* @param targetcl If not null, the traverser should make sure that the result object is compatible with the clreplaced loader,
* e.g. by cloning the object using the clreplaced loaded from the target clreplaced loader.
* @return The processed object.
*/
protected Object readObject(Object object, Type type, Traverser traverser, List<ITraverseProcessor> conversionprocessors, List<ITraverseProcessor> processors, MODE mode, ClreplacedLoader targetcl, JsonReadContext context) {
JsonObject obj = (JsonObject) object;
String clreplacedloadername = obj.getString("clreplacedloadername", null);
String modulename = obj.getString("modulename", null);
String moduleversion = obj.getString("moduleversion", null);
String clreplacedname = obj.getString("clreplacedname", null);
String methodname = obj.getString("methodname", null);
String filename = obj.getString("filename", null);
int linenumber = obj.getInt("linenumber", 0);
StackTraceElement ret = SStackTraceElementHelper.newInstance(clreplacedloadername, modulename, moduleversion, clreplacedname, methodname, filename, linenumber);
// StackTraceElement ret = new StackTraceElement(clreplacedname, methodname, filename, linenumber);
// traversed.put(object, ret);
// ((JsonReadContext)context).addKnownObject(ret);
JsonValue idx = (JsonValue) obj.get(JsonTraverser.ID_MARKER);
if (idx != null)
((JsonReadContext) context).addKnownObject(ret, idx.asInt());
return ret;
}
19
Source : JsonSimpleDateFormatProcessor.java
with GNU General Public License v3.0
from actoron
with GNU General Public License v3.0
from actoron
/**
* Process an object.
* @param object The object.
* @param targetcl If not null, the traverser should make sure that the result object is compatible with the clreplaced loader,
* e.g. by cloning the object using the clreplaced loaded from the target clreplaced loader.
* @return The processed object.
*/
protected Object readObject(Object object, Type type, Traverser traverser, List<ITraverseProcessor> conversionprocessors, List<ITraverseProcessor> processors, MODE mode, ClreplacedLoader targetcl, JsonReadContext context) {
Clreplaced<?> clazz = JsonPrimitiveObjectProcessor.getClazz(object, targetcl);
SimpleDateFormat ret = (SimpleDateFormat) getReturnObject(object, clazz, targetcl);
JsonObject obj = (JsonObject) object;
String pattern = obj.getString("pattern", null);
ret.applyPattern(pattern);
JsonValue idx = (JsonValue) obj.get(JsonTraverser.ID_MARKER);
if (idx != null)
((JsonReadContext) context).addKnownObject(ret, idx.asInt());
// Include bean properties of superclreplaced DateFormat
readProperties(object, clazz, conversionprocessors, processors, mode, traverser, targetcl, ret, context, intro);
return ret;
}
19
Source : JsonLogRecordProcessor.java
with GNU General Public License v3.0
from actoron
with GNU General Public License v3.0
from actoron
/**
* Process an object.
* @param object The object.
* @param targetcl If not null, the traverser should make sure that the result object is compatible with the clreplaced loader,
* e.g. by cloning the object using the clreplaced loaded from the target clreplaced loader.
* @return The processed object.
*/
protected Object readObject(Object object, Type type, Traverser traverser, List<ITraverseProcessor> conversionprocessors, List<ITraverseProcessor> processors, MODE mode, ClreplacedLoader targetcl, JsonReadContext context) {
JsonObject obj = (JsonObject) object;
Level level = (Level) traverser.doTraverse(obj.get("level"), Level.clreplaced, conversionprocessors, processors, mode, targetcl, context);
String msg = obj.getString("msg", null);
long millis = obj.getLong("millis", 0);
LogRecord ret = new LogRecord(level, msg);
ret.setMillis(millis);
// traversed.put(object, ret);
// ((JsonReadContext)context).addKnownObject(ret);
JsonValue idx = (JsonValue) obj.get(JsonTraverser.ID_MARKER);
if (idx != null)
((JsonReadContext) context).addKnownObject(ret, idx.asInt());
return ret;
}
19
Source : JsonTraverser.java
with GNU General Public License v3.0
from actoron
with GNU General Public License v3.0
from actoron
/**
* Find the clreplaced of an object.
* @param object The object.
* @return The objects clreplaced.
*/
public static Clreplaced<?> findClazzOfJsonObject(JsonObject object, ClreplacedLoader targetcl) {
Clreplaced<?> ret = null;
String clname = object.getString(CLreplacedNAME_MARKER, null);
clname = STransformation.getClreplacedname(clname);
if (clname != null)
ret = SReflect.clreplacedForName0(clname, targetcl);
return ret;
}
18
Source : JsonRunner_Test.java
with MIT License
from zcash-community
with MIT License
from zcash-community
private boolean equalsIgnoreOrder(JsonObject object1, JsonValue value2) {
if (!value2.isObject()) {
return false;
}
JsonObject object2 = value2.asObject();
List<String> names1 = object1.names();
List<String> names2 = object2.names();
if (!names1.containsAll(names2) || !names2.containsAll(names1)) {
return false;
}
for (String name : names1) {
if (!equalsIgnoreOrder(object1.get(name), object2.get(name))) {
return false;
}
}
return true;
}
18
Source : JsonObjectIterationBenchmark.java
with MIT License
from zcash-community
with MIT License
from zcash-community
public clreplaced JsonObjecreplacederationBenchmark extends SimpleBenchmark {
@Param
int size;
private JsonObject jsonObject;
@Override
protected void setUp() throws IOException {
jsonObject = new JsonObject();
for (int index = 0; index < size; index++) {
String name = Integer.toHexString(index);
jsonObject.add(name, index);
}
}
public void timeIterateMembers(int reps) {
for (int r = 0; r < reps; r++) {
for (Member member : jsonObject) {
String name = member.getName();
JsonValue value = member.getValue();
checkResult(name, value);
}
}
}
public void timeIterateNames(int reps) {
for (int r = 0; r < reps; r++) {
for (String name : jsonObject.names()) {
JsonValue value = jsonObject.get(name);
checkResult(name, value);
}
}
}
void checkResult(String name, JsonValue value) {
if (name == null || value == null) {
throw new NullPointerException();
}
}
public static void main(String[] args) throws IOException {
CaliperRunner runner = new CaliperRunner(JsonObjecreplacederationBenchmark.clreplaced);
runner.addParameterDefault("size", "4", "16", "64");
runner.exec(args);
}
}
18
Source : CaliperResultsPreprocessor.java
with MIT License
from zcash-community
with MIT License
from zcash-community
private static JsonValue extractEnvironment(JsonObject caliperResults) {
JsonObject details = caliperResults.get("environment").asObject().get("propertyMap").asObject();
details.add("benchmark.clreplacedname", extractBenchmarkName(caliperResults));
details.add("benchmark.executionTime", extractTimestamp(caliperResults));
return details;
}
See More Examples