hexsha
stringlengths 40
40
| repo
stringlengths 4
114
| path
stringlengths 6
369
| license
sequence | language
stringclasses 1
value | identifier
stringlengths 1
123
| original_docstring
stringlengths 8
49.2k
| docstring
stringlengths 5
8.63k
| docstring_tokens
sequence | code
stringlengths 25
988k
| code_tokens
sequence | short_docstring
stringlengths 0
6.18k
| short_docstring_tokens
sequence | comment
sequence | parameters
list | docstring_params
dict |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fe803918cf350fcefe347aa44339a518629a5a6f | bigdatagenomics/convert | convert-ga4gh/src/test/java/org/bdgenomics/convert/ga4gh/BdgenomicsFeatureToGa4ghFeatureTest.java | [
"Apache-2.0"
] | Java | BdgenomicsFeatureToGa4ghFeatureTest | /**
* Unit test for BdgenomicsFeatureToGa4ghFeature.
*/ | Unit test for BdgenomicsFeatureToGa4ghFeature. | [
"Unit",
"test",
"for",
"BdgenomicsFeatureToGa4ghFeature",
"."
] | public final class BdgenomicsFeatureToGa4ghFeatureTest {
private final Logger logger = LoggerFactory.getLogger(BdgenomicsFeatureToGa4ghFeatureTest.class);
private Converter<String, ga4gh.Common.OntologyTerm> featureTypeConverter;
private Converter<org.bdgenomics.formats.avro.Strand, ga4gh.Common.Strand> strandConverter;
private Converter<org.bdgenomics.formats.avro.Feature, ga4gh.SequenceAnnotations.Feature> featureConverter;
private Converter<Map<String, String>, ga4gh.Common.Attributes> attributeConverter;
@Before
public void setUp() {
featureTypeConverter = new StringToOntologyTerm();
strandConverter = new BdgenomicsStrandToGa4ghStrand();
attributeConverter = new MapToGa4ghAttributes();
featureConverter = new BdgenomicsFeatureToGa4ghFeature(featureTypeConverter, strandConverter, attributeConverter);
}
@Test
public void testConstructor() {
assertNotNull(featureConverter);
}
@Test(expected=NullPointerException.class)
public void testConstructorNullFeatureTypeConverter() {
new BdgenomicsFeatureToGa4ghFeature(null, strandConverter, attributeConverter);
}
@Test(expected=NullPointerException.class)
public void testConstructorNullStrandConverter() {
new BdgenomicsFeatureToGa4ghFeature(featureTypeConverter, null, attributeConverter);
}
@Test(expected=NullPointerException.class)
public void testConstructorNullAttributesConverter() {
new BdgenomicsFeatureToGa4ghFeature(featureTypeConverter, strandConverter, null);
}
@Test(expected=ConversionException.class)
public void testConvertNullStrict() {
featureConverter.convert(null, ConversionStringency.STRICT, logger);
}
@Test
public void testConvertNullLenient() {
assertNull(featureConverter.convert(null, ConversionStringency.LENIENT, logger));
}
@Test
public void testConvertNullSilent() {
assertNull(featureConverter.convert(null, ConversionStringency.SILENT, logger));
}
@Test
public void testConvert() {
ga4gh.SequenceAnnotations.Feature expected = ga4gh.SequenceAnnotations.Feature.newBuilder()
.setReferenceName("1")
.setStart(0L)
.setEnd(42L)
.setStrand(ga4gh.Common.Strand.POS_STRAND)
.setFeatureType(ga4gh.Common.OntologyTerm.newBuilder().setTermId("exon").build())
.setAttributes(ga4gh.Common.Attributes.newBuilder().build())
.build();
org.bdgenomics.formats.avro.Feature feature = org.bdgenomics.formats.avro.Feature.newBuilder()
.setReferenceName("1")
.setStart(0L)
.setEnd(42L)
.setStrand(org.bdgenomics.formats.avro.Strand.FORWARD)
.setFeatureType("exon")
.build();
assertEquals(expected, featureConverter.convert(feature, ConversionStringency.STRICT, logger));
}
@Test
public void testConvertWithAttributes() {
// attributes to test
Map<String, String> mapAttributes = new java.util.HashMap<String, String>();
mapAttributes.put("thickStrand", "10");
mapAttributes.put("blockCount", "1");
mapAttributes.put("blockSizes", "10,100,2,4,");
Map<String, Common.AttributeValueList> ga4ghAttributes = new HashMap<String, Common.AttributeValueList>();
Iterator<Map.Entry<String, String>> entries = mapAttributes.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
ga4ghAttributes.put(entry.getKey(), Common.AttributeValueList.newBuilder().addValues(Common.AttributeValue.newBuilder().setStringValue(entry.getValue())).build());
}
ga4gh.SequenceAnnotations.Feature expected = ga4gh.SequenceAnnotations.Feature.newBuilder()
.setReferenceName("1")
.setStart(0L)
.setEnd(42L)
.setStrand(ga4gh.Common.Strand.POS_STRAND)
.setId("exon_123")
.setGeneSymbol("GENE_SYMBOL")
.setFeatureType(ga4gh.Common.OntologyTerm.newBuilder().setTermId("exon").build())
.setAttributes(Common.Attributes.newBuilder().putAllAttr(ga4ghAttributes).build())
.build();
org.bdgenomics.formats.avro.Feature feature = org.bdgenomics.formats.avro.Feature.newBuilder()
.setReferenceName("1")
.setStart(0L)
.setEnd(42L)
.setStrand(org.bdgenomics.formats.avro.Strand.FORWARD)
.setFeatureType("exon")
.setFeatureId("exon_123")
.setGeneId("GENE_SYMBOL")
.setAttributes(mapAttributes)
.build();
assertEquals(expected, featureConverter.convert(feature, ConversionStringency.STRICT, logger));
}
} | [
"public",
"final",
"class",
"BdgenomicsFeatureToGa4ghFeatureTest",
"{",
"private",
"final",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"BdgenomicsFeatureToGa4ghFeatureTest",
".",
"class",
")",
";",
"private",
"Converter",
"<",
"String",
",",
"ga4gh",
".",
"Common",
".",
"OntologyTerm",
">",
"featureTypeConverter",
";",
"private",
"Converter",
"<",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Strand",
",",
"ga4gh",
".",
"Common",
".",
"Strand",
">",
"strandConverter",
";",
"private",
"Converter",
"<",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Feature",
",",
"ga4gh",
".",
"SequenceAnnotations",
".",
"Feature",
">",
"featureConverter",
";",
"private",
"Converter",
"<",
"Map",
"<",
"String",
",",
"String",
">",
",",
"ga4gh",
".",
"Common",
".",
"Attributes",
">",
"attributeConverter",
";",
"@",
"Before",
"public",
"void",
"setUp",
"(",
")",
"{",
"featureTypeConverter",
"=",
"new",
"StringToOntologyTerm",
"(",
")",
";",
"strandConverter",
"=",
"new",
"BdgenomicsStrandToGa4ghStrand",
"(",
")",
";",
"attributeConverter",
"=",
"new",
"MapToGa4ghAttributes",
"(",
")",
";",
"featureConverter",
"=",
"new",
"BdgenomicsFeatureToGa4ghFeature",
"(",
"featureTypeConverter",
",",
"strandConverter",
",",
"attributeConverter",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testConstructor",
"(",
")",
"{",
"assertNotNull",
"(",
"featureConverter",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"NullPointerException",
".",
"class",
")",
"public",
"void",
"testConstructorNullFeatureTypeConverter",
"(",
")",
"{",
"new",
"BdgenomicsFeatureToGa4ghFeature",
"(",
"null",
",",
"strandConverter",
",",
"attributeConverter",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"NullPointerException",
".",
"class",
")",
"public",
"void",
"testConstructorNullStrandConverter",
"(",
")",
"{",
"new",
"BdgenomicsFeatureToGa4ghFeature",
"(",
"featureTypeConverter",
",",
"null",
",",
"attributeConverter",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"NullPointerException",
".",
"class",
")",
"public",
"void",
"testConstructorNullAttributesConverter",
"(",
")",
"{",
"new",
"BdgenomicsFeatureToGa4ghFeature",
"(",
"featureTypeConverter",
",",
"strandConverter",
",",
"null",
")",
";",
"}",
"@",
"Test",
"(",
"expected",
"=",
"ConversionException",
".",
"class",
")",
"public",
"void",
"testConvertNullStrict",
"(",
")",
"{",
"featureConverter",
".",
"convert",
"(",
"null",
",",
"ConversionStringency",
".",
"STRICT",
",",
"logger",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testConvertNullLenient",
"(",
")",
"{",
"assertNull",
"(",
"featureConverter",
".",
"convert",
"(",
"null",
",",
"ConversionStringency",
".",
"LENIENT",
",",
"logger",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testConvertNullSilent",
"(",
")",
"{",
"assertNull",
"(",
"featureConverter",
".",
"convert",
"(",
"null",
",",
"ConversionStringency",
".",
"SILENT",
",",
"logger",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testConvert",
"(",
")",
"{",
"ga4gh",
".",
"SequenceAnnotations",
".",
"Feature",
"expected",
"=",
"ga4gh",
".",
"SequenceAnnotations",
".",
"Feature",
".",
"newBuilder",
"(",
")",
".",
"setReferenceName",
"(",
"\"",
"1",
"\"",
")",
".",
"setStart",
"(",
"0L",
")",
".",
"setEnd",
"(",
"42L",
")",
".",
"setStrand",
"(",
"ga4gh",
".",
"Common",
".",
"Strand",
".",
"POS_STRAND",
")",
".",
"setFeatureType",
"(",
"ga4gh",
".",
"Common",
".",
"OntologyTerm",
".",
"newBuilder",
"(",
")",
".",
"setTermId",
"(",
"\"",
"exon",
"\"",
")",
".",
"build",
"(",
")",
")",
".",
"setAttributes",
"(",
"ga4gh",
".",
"Common",
".",
"Attributes",
".",
"newBuilder",
"(",
")",
".",
"build",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Feature",
"feature",
"=",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Feature",
".",
"newBuilder",
"(",
")",
".",
"setReferenceName",
"(",
"\"",
"1",
"\"",
")",
".",
"setStart",
"(",
"0L",
")",
".",
"setEnd",
"(",
"42L",
")",
".",
"setStrand",
"(",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Strand",
".",
"FORWARD",
")",
".",
"setFeatureType",
"(",
"\"",
"exon",
"\"",
")",
".",
"build",
"(",
")",
";",
"assertEquals",
"(",
"expected",
",",
"featureConverter",
".",
"convert",
"(",
"feature",
",",
"ConversionStringency",
".",
"STRICT",
",",
"logger",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testConvertWithAttributes",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"mapAttributes",
"=",
"new",
"java",
".",
"util",
".",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"mapAttributes",
".",
"put",
"(",
"\"",
"thickStrand",
"\"",
",",
"\"",
"10",
"\"",
")",
";",
"mapAttributes",
".",
"put",
"(",
"\"",
"blockCount",
"\"",
",",
"\"",
"1",
"\"",
")",
";",
"mapAttributes",
".",
"put",
"(",
"\"",
"blockSizes",
"\"",
",",
"\"",
"10,100,2,4,",
"\"",
")",
";",
"Map",
"<",
"String",
",",
"Common",
".",
"AttributeValueList",
">",
"ga4ghAttributes",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Common",
".",
"AttributeValueList",
">",
"(",
")",
";",
"Iterator",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
">",
"entries",
"=",
"mapAttributes",
".",
"entrySet",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"entries",
".",
"hasNext",
"(",
")",
")",
"{",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
"=",
"entries",
".",
"next",
"(",
")",
";",
"ga4ghAttributes",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"Common",
".",
"AttributeValueList",
".",
"newBuilder",
"(",
")",
".",
"addValues",
"(",
"Common",
".",
"AttributeValue",
".",
"newBuilder",
"(",
")",
".",
"setStringValue",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
")",
".",
"build",
"(",
")",
")",
";",
"}",
"ga4gh",
".",
"SequenceAnnotations",
".",
"Feature",
"expected",
"=",
"ga4gh",
".",
"SequenceAnnotations",
".",
"Feature",
".",
"newBuilder",
"(",
")",
".",
"setReferenceName",
"(",
"\"",
"1",
"\"",
")",
".",
"setStart",
"(",
"0L",
")",
".",
"setEnd",
"(",
"42L",
")",
".",
"setStrand",
"(",
"ga4gh",
".",
"Common",
".",
"Strand",
".",
"POS_STRAND",
")",
".",
"setId",
"(",
"\"",
"exon_123",
"\"",
")",
".",
"setGeneSymbol",
"(",
"\"",
"GENE_SYMBOL",
"\"",
")",
".",
"setFeatureType",
"(",
"ga4gh",
".",
"Common",
".",
"OntologyTerm",
".",
"newBuilder",
"(",
")",
".",
"setTermId",
"(",
"\"",
"exon",
"\"",
")",
".",
"build",
"(",
")",
")",
".",
"setAttributes",
"(",
"Common",
".",
"Attributes",
".",
"newBuilder",
"(",
")",
".",
"putAllAttr",
"(",
"ga4ghAttributes",
")",
".",
"build",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Feature",
"feature",
"=",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Feature",
".",
"newBuilder",
"(",
")",
".",
"setReferenceName",
"(",
"\"",
"1",
"\"",
")",
".",
"setStart",
"(",
"0L",
")",
".",
"setEnd",
"(",
"42L",
")",
".",
"setStrand",
"(",
"org",
".",
"bdgenomics",
".",
"formats",
".",
"avro",
".",
"Strand",
".",
"FORWARD",
")",
".",
"setFeatureType",
"(",
"\"",
"exon",
"\"",
")",
".",
"setFeatureId",
"(",
"\"",
"exon_123",
"\"",
")",
".",
"setGeneId",
"(",
"\"",
"GENE_SYMBOL",
"\"",
")",
".",
"setAttributes",
"(",
"mapAttributes",
")",
".",
"build",
"(",
")",
";",
"assertEquals",
"(",
"expected",
",",
"featureConverter",
".",
"convert",
"(",
"feature",
",",
"ConversionStringency",
".",
"STRICT",
",",
"logger",
")",
")",
";",
"}",
"}"
] | Unit test for BdgenomicsFeatureToGa4ghFeature. | [
"Unit",
"test",
"for",
"BdgenomicsFeatureToGa4ghFeature",
"."
] | [
"// attributes to test"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fe810b1595675e368efca49da6d58bcc69c9226c | BobHanson/ciftools-SwingJS | unused/api/generated/PdbxLinkedEntityList.java | [
"MIT"
] | Java | PdbxLinkedEntityList | /**
* Data items in the PDBX_LINKED_ENTITY_LIST category record
* the list of entity constituents for this molecule.
*/ | Data items in the PDBX_LINKED_ENTITY_LIST category record
the list of entity constituents for this molecule. | [
"Data",
"items",
"in",
"the",
"PDBX_LINKED_ENTITY_LIST",
"category",
"record",
"the",
"list",
"of",
"entity",
"constituents",
"for",
"this",
"molecule",
"."
] | @Generated("org.rcsb.cif.generator.SchemaGenerator")
public class PdbxLinkedEntityList extends BaseCategory {
public PdbxLinkedEntityList(String name, Map<String, Column> columns) {
super(name, columns);
}
public PdbxLinkedEntityList(String name, int rowCount, Object[] encodedColumns) {
super(name, rowCount, encodedColumns);
}
public PdbxLinkedEntityList(String name) {
super(name);
}
/**
* The value of _pdbx_linked_entity_list.linked_entity_id is a reference
* _pdbx_linked_entity.linked_entity_id in the PDBX_LINKED_ENTITY category.
* @return StrColumn
*/
public StrColumn getLinkedEntityId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("linked_entity_id", StrColumn::new) :
getBinaryColumn("linked_entity_id"));
}
/**
* The value of _pdbx_linked_entity_list.ref_entity_id is a unique identifier
* the a constituent entity within this reference molecule.
* @return StrColumn
*/
public StrColumn getEntityId() {
return (StrColumn) (isText ? textFields.computeIfAbsent("entity_id", StrColumn::new) :
getBinaryColumn("entity_id"));
}
/**
* The component number of this entity within the molecule.
* @return IntColumn
*/
public IntColumn getComponentId() {
return (IntColumn) (isText ? textFields.computeIfAbsent("component_id", IntColumn::new) :
getBinaryColumn("component_id"));
}
/**
* Additional details about this entity within this molecule.
* @return StrColumn
*/
public StrColumn getDetails() {
return (StrColumn) (isText ? textFields.computeIfAbsent("details", StrColumn::new) :
getBinaryColumn("details"));
}
} | [
"@",
"Generated",
"(",
"\"",
"org.rcsb.cif.generator.SchemaGenerator",
"\"",
")",
"public",
"class",
"PdbxLinkedEntityList",
"extends",
"BaseCategory",
"{",
"public",
"PdbxLinkedEntityList",
"(",
"String",
"name",
",",
"Map",
"<",
"String",
",",
"Column",
">",
"columns",
")",
"{",
"super",
"(",
"name",
",",
"columns",
")",
";",
"}",
"public",
"PdbxLinkedEntityList",
"(",
"String",
"name",
",",
"int",
"rowCount",
",",
"Object",
"[",
"]",
"encodedColumns",
")",
"{",
"super",
"(",
"name",
",",
"rowCount",
",",
"encodedColumns",
")",
";",
"}",
"public",
"PdbxLinkedEntityList",
"(",
"String",
"name",
")",
"{",
"super",
"(",
"name",
")",
";",
"}",
"/**\n * The value of _pdbx_linked_entity_list.linked_entity_id is a reference\n * _pdbx_linked_entity.linked_entity_id in the PDBX_LINKED_ENTITY category.\n * @return StrColumn\n */",
"public",
"StrColumn",
"getLinkedEntityId",
"(",
")",
"{",
"return",
"(",
"StrColumn",
")",
"(",
"isText",
"?",
"textFields",
".",
"computeIfAbsent",
"(",
"\"",
"linked_entity_id",
"\"",
",",
"StrColumn",
"::",
"new",
")",
":",
"getBinaryColumn",
"(",
"\"",
"linked_entity_id",
"\"",
")",
")",
";",
"}",
"/**\n * The value of _pdbx_linked_entity_list.ref_entity_id is a unique identifier\n * the a constituent entity within this reference molecule.\n * @return StrColumn\n */",
"public",
"StrColumn",
"getEntityId",
"(",
")",
"{",
"return",
"(",
"StrColumn",
")",
"(",
"isText",
"?",
"textFields",
".",
"computeIfAbsent",
"(",
"\"",
"entity_id",
"\"",
",",
"StrColumn",
"::",
"new",
")",
":",
"getBinaryColumn",
"(",
"\"",
"entity_id",
"\"",
")",
")",
";",
"}",
"/**\n * The component number of this entity within the molecule.\n * @return IntColumn\n */",
"public",
"IntColumn",
"getComponentId",
"(",
")",
"{",
"return",
"(",
"IntColumn",
")",
"(",
"isText",
"?",
"textFields",
".",
"computeIfAbsent",
"(",
"\"",
"component_id",
"\"",
",",
"IntColumn",
"::",
"new",
")",
":",
"getBinaryColumn",
"(",
"\"",
"component_id",
"\"",
")",
")",
";",
"}",
"/**\n * Additional details about this entity within this molecule.\n * @return StrColumn\n */",
"public",
"StrColumn",
"getDetails",
"(",
")",
"{",
"return",
"(",
"StrColumn",
")",
"(",
"isText",
"?",
"textFields",
".",
"computeIfAbsent",
"(",
"\"",
"details",
"\"",
",",
"StrColumn",
"::",
"new",
")",
":",
"getBinaryColumn",
"(",
"\"",
"details",
"\"",
")",
")",
";",
"}",
"}"
] | Data items in the PDBX_LINKED_ENTITY_LIST category record
the list of entity constituents for this molecule. | [
"Data",
"items",
"in",
"the",
"PDBX_LINKED_ENTITY_LIST",
"category",
"record",
"the",
"list",
"of",
"entity",
"constituents",
"for",
"this",
"molecule",
"."
] | [] | [
{
"param": "BaseCategory",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseCategory",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fe8439331e576da9d6a7cfd3494ab14dacc6ab8d | ashishbh/dropwizard | dropwizard-logging/src/main/java/io/dropwizard/logging/socket/DropwizardUdpSocketAppender.java | [
"Apache-2.0"
] | Java | DropwizardUdpSocketAppender | /**
* Sends log events to a UDP server, a connection to which is represented as a stream.
*/ | Sends log events to a UDP server, a connection to which is represented as a stream. | [
"Sends",
"log",
"events",
"to",
"a",
"UDP",
"server",
"a",
"connection",
"to",
"which",
"is",
"represented",
"as",
"a",
"stream",
"."
] | public class DropwizardUdpSocketAppender<E extends DeferredProcessingAware> extends OutputStreamAppender<E> {
private final String host;
private final int port;
public DropwizardUdpSocketAppender(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void start() {
setOutputStream(datagramSocketOutputStream(host, port));
super.start();
}
protected OutputStream datagramSocketOutputStream(String host, int port) {
try {
return new OutputStream() {
private final DatagramSocket datagramSocket = new DatagramSocket();
@Override
public void write(int b) throws IOException {
throw new UnsupportedOperationException("Datagram doesn't work at byte level");
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
// Important not to cache InetAddress and let the JVM/OS to handle DNS caching.
datagramSocket.send(new DatagramPacket(b, off, len, InetAddress.getByName(host), port));
}
@Override
public void close() throws IOException {
datagramSocket.close();
}
};
} catch (SocketException e) {
throw new IllegalStateException("Unable to create a datagram socket", e);
}
}
} | [
"public",
"class",
"DropwizardUdpSocketAppender",
"<",
"E",
"extends",
"DeferredProcessingAware",
">",
"extends",
"OutputStreamAppender",
"<",
"E",
">",
"{",
"private",
"final",
"String",
"host",
";",
"private",
"final",
"int",
"port",
";",
"public",
"DropwizardUdpSocketAppender",
"(",
"String",
"host",
",",
"int",
"port",
")",
"{",
"this",
".",
"host",
"=",
"host",
";",
"this",
".",
"port",
"=",
"port",
";",
"}",
"@",
"Override",
"public",
"void",
"start",
"(",
")",
"{",
"setOutputStream",
"(",
"datagramSocketOutputStream",
"(",
"host",
",",
"port",
")",
")",
";",
"super",
".",
"start",
"(",
")",
";",
"}",
"protected",
"OutputStream",
"datagramSocketOutputStream",
"(",
"String",
"host",
",",
"int",
"port",
")",
"{",
"try",
"{",
"return",
"new",
"OutputStream",
"(",
")",
"{",
"private",
"final",
"DatagramSocket",
"datagramSocket",
"=",
"new",
"DatagramSocket",
"(",
")",
";",
"@",
"Override",
"public",
"void",
"write",
"(",
"int",
"b",
")",
"throws",
"IOException",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"",
"Datagram doesn't work at byte level",
"\"",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"datagramSocket",
".",
"send",
"(",
"new",
"DatagramPacket",
"(",
"b",
",",
"off",
",",
"len",
",",
"InetAddress",
".",
"getByName",
"(",
"host",
")",
",",
"port",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"datagramSocket",
".",
"close",
"(",
")",
";",
"}",
"}",
";",
"}",
"catch",
"(",
"SocketException",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"",
"Unable to create a datagram socket",
"\"",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Sends log events to a UDP server, a connection to which is represented as a stream. | [
"Sends",
"log",
"events",
"to",
"a",
"UDP",
"server",
"a",
"connection",
"to",
"which",
"is",
"represented",
"as",
"a",
"stream",
"."
] | [
"// Important not to cache InetAddress and let the JVM/OS to handle DNS caching."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fe847d500cd8e6d0ccbbacf98b9aad0ff3433e52 | timfel/netbeans | extide/gradle/netbeans-gradle-tooling/src/main/java/org/netbeans/modules/gradle/tooling/NetBeansExplodedWarPlugin.java | [
"Apache-2.0"
] | Java | NetBeansExplodedWarPlugin | /**
*
* @author Laszlo Kishalmi
*/ | @author Laszlo Kishalmi | [
"@author",
"Laszlo",
"Kishalmi"
] | class NetBeansExplodedWarPlugin implements Plugin<Project> {
private static final String EXPLODED_WAR_TASK = "explodedWar";
@Override
public void apply(Project project) {
project.afterEvaluate(p -> {
if (p.getPlugins().hasPlugin("war") && (project.getTasks().findByPath(EXPLODED_WAR_TASK) == null)){
addTask(p);
}
});
}
private void addTask(Project p) {
War war = (War) p.getTasks().getByName("war");
p.getTasks().register(EXPLODED_WAR_TASK, Sync.class, (sync) -> {
sync.setGroup("build");
sync.into(new File(new File(p.getBuildDir(), "exploded"), war.getArchiveFileName().get()));
sync.with(war);
});
war.dependsOn(EXPLODED_WAR_TASK);
}
} | [
"class",
"NetBeansExplodedWarPlugin",
"implements",
"Plugin",
"<",
"Project",
">",
"{",
"private",
"static",
"final",
"String",
"EXPLODED_WAR_TASK",
"=",
"\"",
"explodedWar",
"\"",
";",
"@",
"Override",
"public",
"void",
"apply",
"(",
"Project",
"project",
")",
"{",
"project",
".",
"afterEvaluate",
"(",
"p",
"->",
"{",
"if",
"(",
"p",
".",
"getPlugins",
"(",
")",
".",
"hasPlugin",
"(",
"\"",
"war",
"\"",
")",
"&&",
"(",
"project",
".",
"getTasks",
"(",
")",
".",
"findByPath",
"(",
"EXPLODED_WAR_TASK",
")",
"==",
"null",
")",
")",
"{",
"addTask",
"(",
"p",
")",
";",
"}",
"}",
")",
";",
"}",
"private",
"void",
"addTask",
"(",
"Project",
"p",
")",
"{",
"War",
"war",
"=",
"(",
"War",
")",
"p",
".",
"getTasks",
"(",
")",
".",
"getByName",
"(",
"\"",
"war",
"\"",
")",
";",
"p",
".",
"getTasks",
"(",
")",
".",
"register",
"(",
"EXPLODED_WAR_TASK",
",",
"Sync",
".",
"class",
",",
"(",
"sync",
")",
"->",
"{",
"sync",
".",
"setGroup",
"(",
"\"",
"build",
"\"",
")",
";",
"sync",
".",
"into",
"(",
"new",
"File",
"(",
"new",
"File",
"(",
"p",
".",
"getBuildDir",
"(",
")",
",",
"\"",
"exploded",
"\"",
")",
",",
"war",
".",
"getArchiveFileName",
"(",
")",
".",
"get",
"(",
")",
")",
")",
";",
"sync",
".",
"with",
"(",
"war",
")",
";",
"}",
")",
";",
"war",
".",
"dependsOn",
"(",
"EXPLODED_WAR_TASK",
")",
";",
"}",
"}"
] | @author Laszlo Kishalmi | [
"@author",
"Laszlo",
"Kishalmi"
] | [] | [
{
"param": "Plugin<Project>",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Plugin<Project>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fe86ea247c19f818bb92d06ec1dd2a9db5487fca | gwsshs22/incubator-nemo | compiler/optimizer/src/main/java/edu/snu/nemo/compiler/optimizer/pass/compiletime/annotating/DataSkewVertexPass.java | [
"Apache-2.0"
] | Java | DataSkewVertexPass | /**
* Pass to annotate the DAG for a job to perform data skew.
* It specifies which optimization to perform on the MetricCollectionBarrierVertex.
*/ | Pass to annotate the DAG for a job to perform data skew.
It specifies which optimization to perform on the MetricCollectionBarrierVertex. | [
"Pass",
"to",
"annotate",
"the",
"DAG",
"for",
"a",
"job",
"to",
"perform",
"data",
"skew",
".",
"It",
"specifies",
"which",
"optimization",
"to",
"perform",
"on",
"the",
"MetricCollectionBarrierVertex",
"."
] | public final class DataSkewVertexPass extends AnnotatingPass {
/**
* Default constructor.
*/
public DataSkewVertexPass() {
super(ExecutionProperty.Key.DynamicOptimizationType);
}
@Override
public DAG<IRVertex, IREdge> apply(final DAG<IRVertex, IREdge> dag) {
dag.topologicalDo(v -> {
// we only care about metric collection barrier vertices.
if (v instanceof MetricCollectionBarrierVertex) {
v.setProperty(DynamicOptimizationProperty.of(DynamicOptimizationProperty.Value.DataSkewRuntimePass));
}
});
return dag;
}
} | [
"public",
"final",
"class",
"DataSkewVertexPass",
"extends",
"AnnotatingPass",
"{",
"/**\n * Default constructor.\n */",
"public",
"DataSkewVertexPass",
"(",
")",
"{",
"super",
"(",
"ExecutionProperty",
".",
"Key",
".",
"DynamicOptimizationType",
")",
";",
"}",
"@",
"Override",
"public",
"DAG",
"<",
"IRVertex",
",",
"IREdge",
">",
"apply",
"(",
"final",
"DAG",
"<",
"IRVertex",
",",
"IREdge",
">",
"dag",
")",
"{",
"dag",
".",
"topologicalDo",
"(",
"v",
"->",
"{",
"if",
"(",
"v",
"instanceof",
"MetricCollectionBarrierVertex",
")",
"{",
"v",
".",
"setProperty",
"(",
"DynamicOptimizationProperty",
".",
"of",
"(",
"DynamicOptimizationProperty",
".",
"Value",
".",
"DataSkewRuntimePass",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"dag",
";",
"}",
"}"
] | Pass to annotate the DAG for a job to perform data skew. | [
"Pass",
"to",
"annotate",
"the",
"DAG",
"for",
"a",
"job",
"to",
"perform",
"data",
"skew",
"."
] | [
"// we only care about metric collection barrier vertices."
] | [
{
"param": "AnnotatingPass",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AnnotatingPass",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fe874a0d5ef4a702b311c60daece617848f17cb5 | wilx/maven-common-artifact-filters | src/main/java/org/apache/maven/shared/artifact/filter/resolve/ScopeFilter.java | [
"Apache-2.0"
] | Java | ScopeFilter | /**
* Filter based on scope. <strong>Note:</strong> There's no logic for inherited scoped
*
* @author Robert Scholte
* @since 3.0
* @see org.eclipse.aether.util.filter.ScopeDependencyFilter
*/ | Filter based on scope. Note: There's no logic for inherited scoped
@author Robert Scholte
@since 3.0
@see org.eclipse.aether.util.filter.ScopeDependencyFilter | [
"Filter",
"based",
"on",
"scope",
".",
"Note",
":",
"There",
"'",
"s",
"no",
"logic",
"for",
"inherited",
"scoped",
"@author",
"Robert",
"Scholte",
"@since",
"3",
".",
"0",
"@see",
"org",
".",
"eclipse",
".",
"aether",
".",
"util",
".",
"filter",
".",
"ScopeDependencyFilter"
] | public class ScopeFilter implements TransformableFilter
{
private final Collection<String> excluded;
private final Collection<String> included;
/**
* <p>Constructor for ScopeFilter.</p>
*
* @param included specific scopes to include or {@code null} to include all
* @param excluded specific scopes to exclude or {@code null} to exclude none
*/
public ScopeFilter( Collection<String> included, Collection<String> excluded )
{
this.included = ( included == null ? null : Collections.unmodifiableCollection( included ) );
this.excluded = ( excluded == null ? null : Collections.unmodifiableCollection( excluded ) );
}
/**
* Construct a ScopeFilter based on included scopes
*
* @param included the scopes to include, may be {@code null}
* @return the filter, never {@code null}
*/
public static ScopeFilter including( Collection<String> included )
{
return new ScopeFilter( included, null );
}
/**
* Construct a ScopeFilter based on included scopes
*
* @param included the scopes to include, must not be {@code null}
* @return the filter, never {@code null}
*/
public static ScopeFilter including( String... included )
{
return new ScopeFilter( Arrays.asList( included ), null );
}
/**
* Construct a ScopeFilter based on excluded scopes
*
* @param excluded the scopes to exclude, may be {@code null}
* @return the filter, never {@code null}
*/
public static ScopeFilter excluding( Collection<String> excluded )
{
return new ScopeFilter( null, excluded );
}
/**
* Construct a ScopeFilter based on excluded scopes
*
* @param excluded the scopes to exclude, must not be {@code null}
* @return the filter, never {@code null}
*/
public static ScopeFilter excluding( String... excluded )
{
return new ScopeFilter( null, Arrays.asList( excluded ) );
}
/**
* Get the excluded scopes
*
* @return the scopes to exclude, may be {@code null}
*/
public final Collection<String> getExcluded()
{
return excluded;
}
/**
* Get the included scopes
*
* @return the scopes to include, may be {@code null}
*/
public final Collection<String> getIncluded()
{
return included;
}
/**
* {@inheritDoc}
*
* Transform this filter to a tool specific implementation
*/
public <T> T transform ( FilterTransformer<T> transformer )
{
return transformer.transform( this );
}
} | [
"public",
"class",
"ScopeFilter",
"implements",
"TransformableFilter",
"{",
"private",
"final",
"Collection",
"<",
"String",
">",
"excluded",
";",
"private",
"final",
"Collection",
"<",
"String",
">",
"included",
";",
"/**\n * <p>Constructor for ScopeFilter.</p>\n *\n * @param included specific scopes to include or {@code null} to include all\n * @param excluded specific scopes to exclude or {@code null} to exclude none\n */",
"public",
"ScopeFilter",
"(",
"Collection",
"<",
"String",
">",
"included",
",",
"Collection",
"<",
"String",
">",
"excluded",
")",
"{",
"this",
".",
"included",
"=",
"(",
"included",
"==",
"null",
"?",
"null",
":",
"Collections",
".",
"unmodifiableCollection",
"(",
"included",
")",
")",
";",
"this",
".",
"excluded",
"=",
"(",
"excluded",
"==",
"null",
"?",
"null",
":",
"Collections",
".",
"unmodifiableCollection",
"(",
"excluded",
")",
")",
";",
"}",
"/**\n * Construct a ScopeFilter based on included scopes\n *\n * @param included the scopes to include, may be {@code null}\n * @return the filter, never {@code null}\n */",
"public",
"static",
"ScopeFilter",
"including",
"(",
"Collection",
"<",
"String",
">",
"included",
")",
"{",
"return",
"new",
"ScopeFilter",
"(",
"included",
",",
"null",
")",
";",
"}",
"/**\n * Construct a ScopeFilter based on included scopes\n *\n * @param included the scopes to include, must not be {@code null}\n * @return the filter, never {@code null}\n */",
"public",
"static",
"ScopeFilter",
"including",
"(",
"String",
"...",
"included",
")",
"{",
"return",
"new",
"ScopeFilter",
"(",
"Arrays",
".",
"asList",
"(",
"included",
")",
",",
"null",
")",
";",
"}",
"/**\n * Construct a ScopeFilter based on excluded scopes\n *\n * @param excluded the scopes to exclude, may be {@code null}\n * @return the filter, never {@code null}\n */",
"public",
"static",
"ScopeFilter",
"excluding",
"(",
"Collection",
"<",
"String",
">",
"excluded",
")",
"{",
"return",
"new",
"ScopeFilter",
"(",
"null",
",",
"excluded",
")",
";",
"}",
"/**\n * Construct a ScopeFilter based on excluded scopes\n *\n * @param excluded the scopes to exclude, must not be {@code null}\n * @return the filter, never {@code null}\n */",
"public",
"static",
"ScopeFilter",
"excluding",
"(",
"String",
"...",
"excluded",
")",
"{",
"return",
"new",
"ScopeFilter",
"(",
"null",
",",
"Arrays",
".",
"asList",
"(",
"excluded",
")",
")",
";",
"}",
"/**\n * Get the excluded scopes\n *\n * @return the scopes to exclude, may be {@code null}\n */",
"public",
"final",
"Collection",
"<",
"String",
">",
"getExcluded",
"(",
")",
"{",
"return",
"excluded",
";",
"}",
"/**\n * Get the included scopes\n *\n * @return the scopes to include, may be {@code null}\n */",
"public",
"final",
"Collection",
"<",
"String",
">",
"getIncluded",
"(",
")",
"{",
"return",
"included",
";",
"}",
"/**\n * {@inheritDoc}\n *\n * Transform this filter to a tool specific implementation\n */",
"public",
"<",
"T",
">",
"T",
"transform",
"(",
"FilterTransformer",
"<",
"T",
">",
"transformer",
")",
"{",
"return",
"transformer",
".",
"transform",
"(",
"this",
")",
";",
"}",
"}"
] | Filter based on scope. | [
"Filter",
"based",
"on",
"scope",
"."
] | [] | [
{
"param": "TransformableFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "TransformableFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fe87e544eeed3a399c84311bf57de3d340624f2c | jbescos/metro-jax-ws | jaxws-ri/extras/helidon-integration/samples/helidon-soap-demo/src/main/java/org/eclipse/metro/helidon/example/fromwsdl/AddNumbersImpl.java | [
"BSD-3-Clause"
] | Java | AddNumbersImpl | /*
* Normally the web service implementation class would implement the endpointInterface class.
* However, it is not necessary as this sample demonstrates. It is useful to implement the
* endpointInteface as the compiler will catch errors in the methods signatures of the
* implementation class.
*/ | Normally the web service implementation class would implement the endpointInterface class.
However, it is not necessary as this sample demonstrates. It is useful to implement the
endpointInteface as the compiler will catch errors in the methods signatures of the
implementation class. | [
"Normally",
"the",
"web",
"service",
"implementation",
"class",
"would",
"implement",
"the",
"endpointInterface",
"class",
".",
"However",
"it",
"is",
"not",
"necessary",
"as",
"this",
"sample",
"demonstrates",
".",
"It",
"is",
"useful",
"to",
"implement",
"the",
"endpointInteface",
"as",
"the",
"compiler",
"will",
"catch",
"errors",
"in",
"the",
"methods",
"signatures",
"of",
"the",
"implementation",
"class",
"."
] | @WebService(
wsdlLocation="WEB-INF/wsdl/AddNumbers.wsdl",
endpointInterface = "org.example.duke.AddNumbersPortType"
)
public class AddNumbersImpl {
@Resource
private WebServiceContext ctx;
/**
* @param number1
* @param number2
* @return The sum
* @throws AddNumbersFault_Exception if any of the numbers to be added is
* negative.
*/
public int addNumbers(int number1, int number2) throws AddNumbersFault_Exception {
Objects.nonNull(ctx);
if (number1 < 0 || number2 < 0) {
String message = "Negative number cant be added!";
String detail = "Numbers: " + number1 + ", " + number2;
AddNumbersFault fault = new AddNumbersFault();
fault.setMessage(message);
fault.setFaultInfo(detail);
throw new AddNumbersFault_Exception(message, fault);
}
return number1 + number2;
}
/*
* Simple one-way method that takes an integer.
*/
public void oneWayInt(int number) {
Objects.nonNull(ctx);
System.out.println("");
System.out.println("Service received: " + number);
System.out.println("MessageContext: ");
new TreeMap<>(ctx.getMessageContext()).entrySet()
.forEach((entry) ->
System.out.println(entry.getKey() + "\n\t" + entry.getValue()));
System.out.println("");
}
} | [
"@",
"WebService",
"(",
"wsdlLocation",
"=",
"\"",
"WEB-INF/wsdl/AddNumbers.wsdl",
"\"",
",",
"endpointInterface",
"=",
"\"",
"org.example.duke.AddNumbersPortType",
"\"",
")",
"public",
"class",
"AddNumbersImpl",
"{",
"@",
"Resource",
"private",
"WebServiceContext",
"ctx",
";",
"/**\n * @param number1\n * @param number2\n * @return The sum\n * @throws AddNumbersFault_Exception if any of the numbers to be added is\n * negative.\n */",
"public",
"int",
"addNumbers",
"(",
"int",
"number1",
",",
"int",
"number2",
")",
"throws",
"AddNumbersFault_Exception",
"{",
"Objects",
".",
"nonNull",
"(",
"ctx",
")",
";",
"if",
"(",
"number1",
"<",
"0",
"||",
"number2",
"<",
"0",
")",
"{",
"String",
"message",
"=",
"\"",
"Negative number cant be added!",
"\"",
";",
"String",
"detail",
"=",
"\"",
"Numbers: ",
"\"",
"+",
"number1",
"+",
"\"",
", ",
"\"",
"+",
"number2",
";",
"AddNumbersFault",
"fault",
"=",
"new",
"AddNumbersFault",
"(",
")",
";",
"fault",
".",
"setMessage",
"(",
"message",
")",
";",
"fault",
".",
"setFaultInfo",
"(",
"detail",
")",
";",
"throw",
"new",
"AddNumbersFault_Exception",
"(",
"message",
",",
"fault",
")",
";",
"}",
"return",
"number1",
"+",
"number2",
";",
"}",
"/*\n * Simple one-way method that takes an integer.\n */",
"public",
"void",
"oneWayInt",
"(",
"int",
"number",
")",
"{",
"Objects",
".",
"nonNull",
"(",
"ctx",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\"",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Service received: ",
"\"",
"+",
"number",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"MessageContext: ",
"\"",
")",
";",
"new",
"TreeMap",
"<",
">",
"(",
"ctx",
".",
"getMessageContext",
"(",
")",
")",
".",
"entrySet",
"(",
")",
".",
"forEach",
"(",
"(",
"entry",
")",
"->",
"System",
".",
"out",
".",
"println",
"(",
"entry",
".",
"getKey",
"(",
")",
"+",
"\"",
"\\n",
"\\t",
"\"",
"+",
"entry",
".",
"getValue",
"(",
")",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\"",
")",
";",
"}",
"}"
] | Normally the web service implementation class would implement the endpointInterface class. | [
"Normally",
"the",
"web",
"service",
"implementation",
"class",
"would",
"implement",
"the",
"endpointInterface",
"class",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fe89ff3e1ba807a8faaed4d7dc6f43249da16d7e | sbour/DPCC-OMeta-soulwing | cas-subsystem/src/main/java/org/soulwing/cas/service/JasigAuthenticator.java | [
"Apache-2.0"
] | Java | JasigAuthenticator | /**
* An {@link Authenticator} that delegates to the JASIG CAS client library.
*
* @author Carl Harris
*/ | An Authenticator that delegates to the JASIG CAS client library.
@author Carl Harris | [
"An",
"Authenticator",
"that",
"delegates",
"to",
"the",
"JASIG",
"CAS",
"client",
"library",
".",
"@author",
"Carl",
"Harris"
] | public class JasigAuthenticator implements Authenticator, Serializable {
private static final long serialVersionUID = 364417311301329226L;
public static final String LOGIN_PATH = "login";
public static final String LOGOUT_PATH = "logout";
private final Configuration config;
private final transient TicketValidator validator;
/**
* Constructs a new instance.
* @param config configuration profile
* @param validator ticket validator
*/
public JasigAuthenticator(Configuration config, TicketValidator validator) {
this.config = config;
this.validator = validator;
}
/**
* Gets the {@code validator} property.
* @return property value
*/
TicketValidator getValidator() {
return validator;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isPostAuthRedirect() {
return config.isPostAuthRedirect();
}
/**
* {@inheritDoc}
*/
@Override
public String loginUrl(String requestPath, String queryString) {
String serviceUrl = serviceUrl(requestPath, queryString);
String loginUrl = CommonUtils.constructRedirectUrl(
appendPathToUrl(config.getServerUrl(), LOGIN_PATH),
config.getProtocol().getServiceParameterName(),
serviceUrl, config.isRenew(), false);
return loginUrl;
}
/**
* {@inheritDoc}
*/
@Override
public String logoutUrl(String path) {
if (path != null && !path.startsWith("/")) {
throw new IllegalArgumentException(
"must specify an absolute path for an application resource");
}
final StringBuilder url = new StringBuilder();
final String serverUrl = config.getServerUrl();
url.append(appendPathToUrl(serverUrl, LOGOUT_PATH));
if (path != null) {
url.append("?url=");
url.append(CommonUtils.urlEncode(applicationUrl(path)));
}
return url.toString();
}
private String appendPathToUrl(String url, String path) {
StringBuilder sb = new StringBuilder();
sb.append(url);
if (!url.endsWith("/") && !path.startsWith("/")) {
sb.append("/");
}
sb.append(path);
return sb.toString();
}
private String applicationUrl(String path) {
if (!path.startsWith("/")) {
throw new IllegalArgumentException(
"must specify an absolute path for an application resource");
}
URI uri = URI.create(config.getServiceUrl());
StringBuilder sb = new StringBuilder();
sb.append(uri.getScheme());
sb.append("://");
sb.append(uri.getAuthority());
sb.append(path);
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public IdentityAssertion validateTicket(String requestPath,
String queryString)
throws NoTicketException, AuthenticationException {
String ticket = QueryUtil.findParameter(
config.getProtocol().getTicketParameterName(), queryString);
if (ticket == null) {
throw new NoTicketException();
}
try {
ticket = URLDecoder.decode(ticket, "UTF-8");
}
catch (UnsupportedEncodingException ex) {
throw new AuthenticationException("cannot decode ticket", ex);
}
String serviceUrl = serviceUrl(requestPath, queryString);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("validating ticket '" + ticket + "' for service " + serviceUrl);
}
try {
return new JasigIdentityAssertion(this,
validator.validate(ticket, serviceUrl),
config.getAttributeTransformers());
}
catch (TicketValidationException ex) {
throw new AuthenticationException(ex.getMessage(), ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public String postAuthUrl(String requestUrl, String queryString) {
StringBuilder sb = new StringBuilder();
sb.append(requestUrl);
queryString = QueryUtil.removeProtocolParameters(config.getProtocol(),
queryString);
if (!queryString.isEmpty()) {
sb.append('?');
sb.append(queryString);
}
return sb.toString();
}
String serviceUrl(String requestPath, String queryString) {
URI uri = URI.create(config.getServiceUrl());
StringBuilder sb = new StringBuilder();
sb.append(uri.getScheme());
sb.append("://");
sb.append(uri.getAuthority());
if(requestPath.contains("//")) {
String realPath = requestPath.substring(0, requestPath.indexOf("//"));
requestPath = realPath;
}
sb.append(requestPath);
queryString = QueryUtil.removeProtocolParameters(config.getProtocol(),
queryString);
if (!queryString.isEmpty()) {
sb.append('?');
sb.append(queryString);
}
return sb.toString();
}
} | [
"public",
"class",
"JasigAuthenticator",
"implements",
"Authenticator",
",",
"Serializable",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"364417311301329226L",
";",
"public",
"static",
"final",
"String",
"LOGIN_PATH",
"=",
"\"",
"login",
"\"",
";",
"public",
"static",
"final",
"String",
"LOGOUT_PATH",
"=",
"\"",
"logout",
"\"",
";",
"private",
"final",
"Configuration",
"config",
";",
"private",
"final",
"transient",
"TicketValidator",
"validator",
";",
"/**\n * Constructs a new instance.\n * @param config configuration profile\n * @param validator ticket validator\n */",
"public",
"JasigAuthenticator",
"(",
"Configuration",
"config",
",",
"TicketValidator",
"validator",
")",
"{",
"this",
".",
"config",
"=",
"config",
";",
"this",
".",
"validator",
"=",
"validator",
";",
"}",
"/**\n * Gets the {@code validator} property.\n * @return property value\n */",
"TicketValidator",
"getValidator",
"(",
")",
"{",
"return",
"validator",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"isPostAuthRedirect",
"(",
")",
"{",
"return",
"config",
".",
"isPostAuthRedirect",
"(",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"String",
"loginUrl",
"(",
"String",
"requestPath",
",",
"String",
"queryString",
")",
"{",
"String",
"serviceUrl",
"=",
"serviceUrl",
"(",
"requestPath",
",",
"queryString",
")",
";",
"String",
"loginUrl",
"=",
"CommonUtils",
".",
"constructRedirectUrl",
"(",
"appendPathToUrl",
"(",
"config",
".",
"getServerUrl",
"(",
")",
",",
"LOGIN_PATH",
")",
",",
"config",
".",
"getProtocol",
"(",
")",
".",
"getServiceParameterName",
"(",
")",
",",
"serviceUrl",
",",
"config",
".",
"isRenew",
"(",
")",
",",
"false",
")",
";",
"return",
"loginUrl",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"String",
"logoutUrl",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"path",
"!=",
"null",
"&&",
"!",
"path",
".",
"startsWith",
"(",
"\"",
"/",
"\"",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"must specify an absolute path for an application resource",
"\"",
")",
";",
"}",
"final",
"StringBuilder",
"url",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"final",
"String",
"serverUrl",
"=",
"config",
".",
"getServerUrl",
"(",
")",
";",
"url",
".",
"append",
"(",
"appendPathToUrl",
"(",
"serverUrl",
",",
"LOGOUT_PATH",
")",
")",
";",
"if",
"(",
"path",
"!=",
"null",
")",
"{",
"url",
".",
"append",
"(",
"\"",
"?url=",
"\"",
")",
";",
"url",
".",
"append",
"(",
"CommonUtils",
".",
"urlEncode",
"(",
"applicationUrl",
"(",
"path",
")",
")",
")",
";",
"}",
"return",
"url",
".",
"toString",
"(",
")",
";",
"}",
"private",
"String",
"appendPathToUrl",
"(",
"String",
"url",
",",
"String",
"path",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"url",
")",
";",
"if",
"(",
"!",
"url",
".",
"endsWith",
"(",
"\"",
"/",
"\"",
")",
"&&",
"!",
"path",
".",
"startsWith",
"(",
"\"",
"/",
"\"",
")",
")",
"{",
"sb",
".",
"append",
"(",
"\"",
"/",
"\"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"path",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"private",
"String",
"applicationUrl",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"!",
"path",
".",
"startsWith",
"(",
"\"",
"/",
"\"",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"must specify an absolute path for an application resource",
"\"",
")",
";",
"}",
"URI",
"uri",
"=",
"URI",
".",
"create",
"(",
"config",
".",
"getServiceUrl",
"(",
")",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"uri",
".",
"getScheme",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"",
"://",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"uri",
".",
"getAuthority",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"path",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"IdentityAssertion",
"validateTicket",
"(",
"String",
"requestPath",
",",
"String",
"queryString",
")",
"throws",
"NoTicketException",
",",
"AuthenticationException",
"{",
"String",
"ticket",
"=",
"QueryUtil",
".",
"findParameter",
"(",
"config",
".",
"getProtocol",
"(",
")",
".",
"getTicketParameterName",
"(",
")",
",",
"queryString",
")",
";",
"if",
"(",
"ticket",
"==",
"null",
")",
"{",
"throw",
"new",
"NoTicketException",
"(",
")",
";",
"}",
"try",
"{",
"ticket",
"=",
"URLDecoder",
".",
"decode",
"(",
"ticket",
",",
"\"",
"UTF-8",
"\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"ex",
")",
"{",
"throw",
"new",
"AuthenticationException",
"(",
"\"",
"cannot decode ticket",
"\"",
",",
"ex",
")",
";",
"}",
"String",
"serviceUrl",
"=",
"serviceUrl",
"(",
"requestPath",
",",
"queryString",
")",
";",
"if",
"(",
"LOGGER",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"",
"validating ticket '",
"\"",
"+",
"ticket",
"+",
"\"",
"' for service ",
"\"",
"+",
"serviceUrl",
")",
";",
"}",
"try",
"{",
"return",
"new",
"JasigIdentityAssertion",
"(",
"this",
",",
"validator",
".",
"validate",
"(",
"ticket",
",",
"serviceUrl",
")",
",",
"config",
".",
"getAttributeTransformers",
"(",
")",
")",
";",
"}",
"catch",
"(",
"TicketValidationException",
"ex",
")",
"{",
"throw",
"new",
"AuthenticationException",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
")",
";",
"}",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"String",
"postAuthUrl",
"(",
"String",
"requestUrl",
",",
"String",
"queryString",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"requestUrl",
")",
";",
"queryString",
"=",
"QueryUtil",
".",
"removeProtocolParameters",
"(",
"config",
".",
"getProtocol",
"(",
")",
",",
"queryString",
")",
";",
"if",
"(",
"!",
"queryString",
".",
"isEmpty",
"(",
")",
")",
"{",
"sb",
".",
"append",
"(",
"'?'",
")",
";",
"sb",
".",
"append",
"(",
"queryString",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"String",
"serviceUrl",
"(",
"String",
"requestPath",
",",
"String",
"queryString",
")",
"{",
"URI",
"uri",
"=",
"URI",
".",
"create",
"(",
"config",
".",
"getServiceUrl",
"(",
")",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"uri",
".",
"getScheme",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"",
"://",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"uri",
".",
"getAuthority",
"(",
")",
")",
";",
"if",
"(",
"requestPath",
".",
"contains",
"(",
"\"",
"//",
"\"",
")",
")",
"{",
"String",
"realPath",
"=",
"requestPath",
".",
"substring",
"(",
"0",
",",
"requestPath",
".",
"indexOf",
"(",
"\"",
"//",
"\"",
")",
")",
";",
"requestPath",
"=",
"realPath",
";",
"}",
"sb",
".",
"append",
"(",
"requestPath",
")",
";",
"queryString",
"=",
"QueryUtil",
".",
"removeProtocolParameters",
"(",
"config",
".",
"getProtocol",
"(",
")",
",",
"queryString",
")",
";",
"if",
"(",
"!",
"queryString",
".",
"isEmpty",
"(",
")",
")",
"{",
"sb",
".",
"append",
"(",
"'?'",
")",
";",
"sb",
".",
"append",
"(",
"queryString",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | An {@link Authenticator} that delegates to the JASIG CAS client library. | [
"An",
"{",
"@link",
"Authenticator",
"}",
"that",
"delegates",
"to",
"the",
"JASIG",
"CAS",
"client",
"library",
"."
] | [] | [
{
"param": "Authenticator, Serializable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Authenticator, Serializable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fe8be6d552991a7361a4106668c168f48449457d | PaddyKe/Quarto | src/player/HumanPlayer.java | [
"MIT"
] | Java | HumanPlayer | /*
This class provides a Interfce for two humans to play against each other.
Currently playing via network is not supported.
*/ | This class provides a Interfce for two humans to play against each other.
Currently playing via network is not supported. | [
"This",
"class",
"provides",
"a",
"Interfce",
"for",
"two",
"humans",
"to",
"play",
"against",
"each",
"other",
".",
"Currently",
"playing",
"via",
"network",
"is",
"not",
"supported",
"."
] | public class HumanPlayer extends Player {
public enum State {
NONE, PLACED_FIGURE, FIGURE_SELECTED;
}
private static int counter = 0;
public State playerState;
private int field = -1;
private int figure = -1;
public HumanPlayer() {
super();
this.playerState = State.NONE;
}
public HumanPlayer(String name) {
super(name);
this.playerState = State.NONE;
}
public void handleFieldClick(int index) {
this.field = index;
}
public void handleFigureClick(int index) {
this.figure = index;
}
@Override
public void reset() {
this.playerState = State.NONE;
this.field = -1;
this.figure = -1;
}
@Override
public int placeFigure(Figure f, Figure[][] board, List<Figure> remaining) {
int row = (this.field / 4);
int col = this.field % 4;
if(this.field >= 0) {
if (board[row][col] == null) {
int temp = this.field;
this.field = -1;
return temp;
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if(board[i][j] == null) {
this.field = -1;
return i * 4 + j;
}
}
}
throw new RuntimeException("Field already in use");
}
@Override
public Figure selectFigure(List<Figure> remaining, Figure[] board) {
Figure temp = new Figure((byte) figure);
if (remaining.contains(temp)) {
this.figure = -1;
return remaining.get(remaining.indexOf(temp));
}
this.figure = -1;
return remaining.get(0);
}
} | [
"public",
"class",
"HumanPlayer",
"extends",
"Player",
"{",
"public",
"enum",
"State",
"{",
"NONE",
",",
"PLACED_FIGURE",
",",
"FIGURE_SELECTED",
";",
"}",
"private",
"static",
"int",
"counter",
"=",
"0",
";",
"public",
"State",
"playerState",
";",
"private",
"int",
"field",
"=",
"-",
"1",
";",
"private",
"int",
"figure",
"=",
"-",
"1",
";",
"public",
"HumanPlayer",
"(",
")",
"{",
"super",
"(",
")",
";",
"this",
".",
"playerState",
"=",
"State",
".",
"NONE",
";",
"}",
"public",
"HumanPlayer",
"(",
"String",
"name",
")",
"{",
"super",
"(",
"name",
")",
";",
"this",
".",
"playerState",
"=",
"State",
".",
"NONE",
";",
"}",
"public",
"void",
"handleFieldClick",
"(",
"int",
"index",
")",
"{",
"this",
".",
"field",
"=",
"index",
";",
"}",
"public",
"void",
"handleFigureClick",
"(",
"int",
"index",
")",
"{",
"this",
".",
"figure",
"=",
"index",
";",
"}",
"@",
"Override",
"public",
"void",
"reset",
"(",
")",
"{",
"this",
".",
"playerState",
"=",
"State",
".",
"NONE",
";",
"this",
".",
"field",
"=",
"-",
"1",
";",
"this",
".",
"figure",
"=",
"-",
"1",
";",
"}",
"@",
"Override",
"public",
"int",
"placeFigure",
"(",
"Figure",
"f",
",",
"Figure",
"[",
"]",
"[",
"]",
"board",
",",
"List",
"<",
"Figure",
">",
"remaining",
")",
"{",
"int",
"row",
"=",
"(",
"this",
".",
"field",
"/",
"4",
")",
";",
"int",
"col",
"=",
"this",
".",
"field",
"%",
"4",
";",
"if",
"(",
"this",
".",
"field",
">=",
"0",
")",
"{",
"if",
"(",
"board",
"[",
"row",
"]",
"[",
"col",
"]",
"==",
"null",
")",
"{",
"int",
"temp",
"=",
"this",
".",
"field",
";",
"this",
".",
"field",
"=",
"-",
"1",
";",
"return",
"temp",
";",
"}",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"4",
";",
"i",
"++",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"4",
";",
"j",
"++",
")",
"{",
"if",
"(",
"board",
"[",
"i",
"]",
"[",
"j",
"]",
"==",
"null",
")",
"{",
"this",
".",
"field",
"=",
"-",
"1",
";",
"return",
"i",
"*",
"4",
"+",
"j",
";",
"}",
"}",
"}",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Field already in use",
"\"",
")",
";",
"}",
"@",
"Override",
"public",
"Figure",
"selectFigure",
"(",
"List",
"<",
"Figure",
">",
"remaining",
",",
"Figure",
"[",
"]",
"board",
")",
"{",
"Figure",
"temp",
"=",
"new",
"Figure",
"(",
"(",
"byte",
")",
"figure",
")",
";",
"if",
"(",
"remaining",
".",
"contains",
"(",
"temp",
")",
")",
"{",
"this",
".",
"figure",
"=",
"-",
"1",
";",
"return",
"remaining",
".",
"get",
"(",
"remaining",
".",
"indexOf",
"(",
"temp",
")",
")",
";",
"}",
"this",
".",
"figure",
"=",
"-",
"1",
";",
"return",
"remaining",
".",
"get",
"(",
"0",
")",
";",
"}",
"}"
] | This class provides a Interfce for two humans to play against each other. | [
"This",
"class",
"provides",
"a",
"Interfce",
"for",
"two",
"humans",
"to",
"play",
"against",
"each",
"other",
"."
] | [] | [
{
"param": "Player",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Player",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fe912d1c9de95eb39f9a690fba6dd0fee9df488b | yoshi-code-bot/google-api-java-client-services | clients/google-api-services-cloudkms/v1/1.31.0/com/google/api/services/cloudkms/v1/model/DecryptResponse.java | [
"Apache-2.0"
] | Java | DecryptResponse | /**
* Response message for KeyManagementService.Decrypt.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Key Management Service (KMS) API. For a
* detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/ |
@author Google, Inc. | [
"@author",
"Google",
"Inc",
"."
] | @SuppressWarnings("javadoc")
public final class DecryptResponse extends com.google.api.client.json.GenericJson {
/**
* The decrypted data originally supplied in EncryptRequest.plaintext.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String plaintext;
/**
* Integrity verification field. A CRC32C checksum of the returned DecryptResponse.plaintext. An
* integrity check of DecryptResponse.plaintext can be performed by computing the CRC32C checksum
* of DecryptResponse.plaintext and comparing your results to this field. Discard the response in
* case of non-matching checksum values, and perform a limited number of retries. A persistent
* mismatch may indicate an issue in your computation of the CRC32C checksum. Note: receiving this
* response message indicates that KeyManagementService is able to successfully decrypt the
* ciphertext. Note: This field is defined as int64 for reasons of compatibility across different
* languages. However, it is a non-negative integer, which will never exceed 2^32-1, and can be
* safely downconverted to uint32 in languages that support this type.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long plaintextCrc32c;
/**
* The ProtectionLevel of the CryptoKeyVersion used in decryption.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String protectionLevel;
/**
* Whether the Decryption was performed using the primary key version.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean usedPrimary;
/**
* The decrypted data originally supplied in EncryptRequest.plaintext.
* @see #decodePlaintext()
* @return value or {@code null} for none
*/
public java.lang.String getPlaintext() {
return plaintext;
}
/**
* The decrypted data originally supplied in EncryptRequest.plaintext.
* @see #getPlaintext()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodePlaintext() {
return com.google.api.client.util.Base64.decodeBase64(plaintext);
}
/**
* The decrypted data originally supplied in EncryptRequest.plaintext.
* @see #encodePlaintext()
* @param plaintext plaintext or {@code null} for none
*/
public DecryptResponse setPlaintext(java.lang.String plaintext) {
this.plaintext = plaintext;
return this;
}
/**
* The decrypted data originally supplied in EncryptRequest.plaintext.
* @see #setPlaintext()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public DecryptResponse encodePlaintext(byte[] plaintext) {
this.plaintext = com.google.api.client.util.Base64.encodeBase64URLSafeString(plaintext);
return this;
}
/**
* Integrity verification field. A CRC32C checksum of the returned DecryptResponse.plaintext. An
* integrity check of DecryptResponse.plaintext can be performed by computing the CRC32C checksum
* of DecryptResponse.plaintext and comparing your results to this field. Discard the response in
* case of non-matching checksum values, and perform a limited number of retries. A persistent
* mismatch may indicate an issue in your computation of the CRC32C checksum. Note: receiving this
* response message indicates that KeyManagementService is able to successfully decrypt the
* ciphertext. Note: This field is defined as int64 for reasons of compatibility across different
* languages. However, it is a non-negative integer, which will never exceed 2^32-1, and can be
* safely downconverted to uint32 in languages that support this type.
* @return value or {@code null} for none
*/
public java.lang.Long getPlaintextCrc32c() {
return plaintextCrc32c;
}
/**
* Integrity verification field. A CRC32C checksum of the returned DecryptResponse.plaintext. An
* integrity check of DecryptResponse.plaintext can be performed by computing the CRC32C checksum
* of DecryptResponse.plaintext and comparing your results to this field. Discard the response in
* case of non-matching checksum values, and perform a limited number of retries. A persistent
* mismatch may indicate an issue in your computation of the CRC32C checksum. Note: receiving this
* response message indicates that KeyManagementService is able to successfully decrypt the
* ciphertext. Note: This field is defined as int64 for reasons of compatibility across different
* languages. However, it is a non-negative integer, which will never exceed 2^32-1, and can be
* safely downconverted to uint32 in languages that support this type.
* @param plaintextCrc32c plaintextCrc32c or {@code null} for none
*/
public DecryptResponse setPlaintextCrc32c(java.lang.Long plaintextCrc32c) {
this.plaintextCrc32c = plaintextCrc32c;
return this;
}
/**
* The ProtectionLevel of the CryptoKeyVersion used in decryption.
* @return value or {@code null} for none
*/
public java.lang.String getProtectionLevel() {
return protectionLevel;
}
/**
* The ProtectionLevel of the CryptoKeyVersion used in decryption.
* @param protectionLevel protectionLevel or {@code null} for none
*/
public DecryptResponse setProtectionLevel(java.lang.String protectionLevel) {
this.protectionLevel = protectionLevel;
return this;
}
/**
* Whether the Decryption was performed using the primary key version.
* @return value or {@code null} for none
*/
public java.lang.Boolean getUsedPrimary() {
return usedPrimary;
}
/**
* Whether the Decryption was performed using the primary key version.
* @param usedPrimary usedPrimary or {@code null} for none
*/
public DecryptResponse setUsedPrimary(java.lang.Boolean usedPrimary) {
this.usedPrimary = usedPrimary;
return this;
}
@Override
public DecryptResponse set(String fieldName, Object value) {
return (DecryptResponse) super.set(fieldName, value);
}
@Override
public DecryptResponse clone() {
return (DecryptResponse) super.clone();
}
} | [
"@",
"SuppressWarnings",
"(",
"\"",
"javadoc",
"\"",
")",
"public",
"final",
"class",
"DecryptResponse",
"extends",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"json",
".",
"GenericJson",
"{",
"/**\n * The decrypted data originally supplied in EncryptRequest.plaintext.\n * The value may be {@code null}.\n */",
"@",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"util",
".",
"Key",
"private",
"java",
".",
"lang",
".",
"String",
"plaintext",
";",
"/**\n * Integrity verification field. A CRC32C checksum of the returned DecryptResponse.plaintext. An\n * integrity check of DecryptResponse.plaintext can be performed by computing the CRC32C checksum\n * of DecryptResponse.plaintext and comparing your results to this field. Discard the response in\n * case of non-matching checksum values, and perform a limited number of retries. A persistent\n * mismatch may indicate an issue in your computation of the CRC32C checksum. Note: receiving this\n * response message indicates that KeyManagementService is able to successfully decrypt the\n * ciphertext. Note: This field is defined as int64 for reasons of compatibility across different\n * languages. However, it is a non-negative integer, which will never exceed 2^32-1, and can be\n * safely downconverted to uint32 in languages that support this type.\n * The value may be {@code null}.\n */",
"@",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"util",
".",
"Key",
"@",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"json",
".",
"JsonString",
"private",
"java",
".",
"lang",
".",
"Long",
"plaintextCrc32c",
";",
"/**\n * The ProtectionLevel of the CryptoKeyVersion used in decryption.\n * The value may be {@code null}.\n */",
"@",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"util",
".",
"Key",
"private",
"java",
".",
"lang",
".",
"String",
"protectionLevel",
";",
"/**\n * Whether the Decryption was performed using the primary key version.\n * The value may be {@code null}.\n */",
"@",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"util",
".",
"Key",
"private",
"java",
".",
"lang",
".",
"Boolean",
"usedPrimary",
";",
"/**\n * The decrypted data originally supplied in EncryptRequest.plaintext.\n * @see #decodePlaintext()\n * @return value or {@code null} for none\n */",
"public",
"java",
".",
"lang",
".",
"String",
"getPlaintext",
"(",
")",
"{",
"return",
"plaintext",
";",
"}",
"/**\n * The decrypted data originally supplied in EncryptRequest.plaintext.\n * @see #getPlaintext()\n * @return Base64 decoded value or {@code null} for none\n *\n * @since 1.14\n */",
"public",
"byte",
"[",
"]",
"decodePlaintext",
"(",
")",
"{",
"return",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"util",
".",
"Base64",
".",
"decodeBase64",
"(",
"plaintext",
")",
";",
"}",
"/**\n * The decrypted data originally supplied in EncryptRequest.plaintext.\n * @see #encodePlaintext()\n * @param plaintext plaintext or {@code null} for none\n */",
"public",
"DecryptResponse",
"setPlaintext",
"(",
"java",
".",
"lang",
".",
"String",
"plaintext",
")",
"{",
"this",
".",
"plaintext",
"=",
"plaintext",
";",
"return",
"this",
";",
"}",
"/**\n * The decrypted data originally supplied in EncryptRequest.plaintext.\n * @see #setPlaintext()\n *\n * <p>\n * The value is encoded Base64 or {@code null} for none.\n * </p>\n *\n * @since 1.14\n */",
"public",
"DecryptResponse",
"encodePlaintext",
"(",
"byte",
"[",
"]",
"plaintext",
")",
"{",
"this",
".",
"plaintext",
"=",
"com",
".",
"google",
".",
"api",
".",
"client",
".",
"util",
".",
"Base64",
".",
"encodeBase64URLSafeString",
"(",
"plaintext",
")",
";",
"return",
"this",
";",
"}",
"/**\n * Integrity verification field. A CRC32C checksum of the returned DecryptResponse.plaintext. An\n * integrity check of DecryptResponse.plaintext can be performed by computing the CRC32C checksum\n * of DecryptResponse.plaintext and comparing your results to this field. Discard the response in\n * case of non-matching checksum values, and perform a limited number of retries. A persistent\n * mismatch may indicate an issue in your computation of the CRC32C checksum. Note: receiving this\n * response message indicates that KeyManagementService is able to successfully decrypt the\n * ciphertext. Note: This field is defined as int64 for reasons of compatibility across different\n * languages. However, it is a non-negative integer, which will never exceed 2^32-1, and can be\n * safely downconverted to uint32 in languages that support this type.\n * @return value or {@code null} for none\n */",
"public",
"java",
".",
"lang",
".",
"Long",
"getPlaintextCrc32c",
"(",
")",
"{",
"return",
"plaintextCrc32c",
";",
"}",
"/**\n * Integrity verification field. A CRC32C checksum of the returned DecryptResponse.plaintext. An\n * integrity check of DecryptResponse.plaintext can be performed by computing the CRC32C checksum\n * of DecryptResponse.plaintext and comparing your results to this field. Discard the response in\n * case of non-matching checksum values, and perform a limited number of retries. A persistent\n * mismatch may indicate an issue in your computation of the CRC32C checksum. Note: receiving this\n * response message indicates that KeyManagementService is able to successfully decrypt the\n * ciphertext. Note: This field is defined as int64 for reasons of compatibility across different\n * languages. However, it is a non-negative integer, which will never exceed 2^32-1, and can be\n * safely downconverted to uint32 in languages that support this type.\n * @param plaintextCrc32c plaintextCrc32c or {@code null} for none\n */",
"public",
"DecryptResponse",
"setPlaintextCrc32c",
"(",
"java",
".",
"lang",
".",
"Long",
"plaintextCrc32c",
")",
"{",
"this",
".",
"plaintextCrc32c",
"=",
"plaintextCrc32c",
";",
"return",
"this",
";",
"}",
"/**\n * The ProtectionLevel of the CryptoKeyVersion used in decryption.\n * @return value or {@code null} for none\n */",
"public",
"java",
".",
"lang",
".",
"String",
"getProtectionLevel",
"(",
")",
"{",
"return",
"protectionLevel",
";",
"}",
"/**\n * The ProtectionLevel of the CryptoKeyVersion used in decryption.\n * @param protectionLevel protectionLevel or {@code null} for none\n */",
"public",
"DecryptResponse",
"setProtectionLevel",
"(",
"java",
".",
"lang",
".",
"String",
"protectionLevel",
")",
"{",
"this",
".",
"protectionLevel",
"=",
"protectionLevel",
";",
"return",
"this",
";",
"}",
"/**\n * Whether the Decryption was performed using the primary key version.\n * @return value or {@code null} for none\n */",
"public",
"java",
".",
"lang",
".",
"Boolean",
"getUsedPrimary",
"(",
")",
"{",
"return",
"usedPrimary",
";",
"}",
"/**\n * Whether the Decryption was performed using the primary key version.\n * @param usedPrimary usedPrimary or {@code null} for none\n */",
"public",
"DecryptResponse",
"setUsedPrimary",
"(",
"java",
".",
"lang",
".",
"Boolean",
"usedPrimary",
")",
"{",
"this",
".",
"usedPrimary",
"=",
"usedPrimary",
";",
"return",
"this",
";",
"}",
"@",
"Override",
"public",
"DecryptResponse",
"set",
"(",
"String",
"fieldName",
",",
"Object",
"value",
")",
"{",
"return",
"(",
"DecryptResponse",
")",
"super",
".",
"set",
"(",
"fieldName",
",",
"value",
")",
";",
"}",
"@",
"Override",
"public",
"DecryptResponse",
"clone",
"(",
")",
"{",
"return",
"(",
"DecryptResponse",
")",
"super",
".",
"clone",
"(",
")",
";",
"}",
"}"
] | Response message for KeyManagementService.Decrypt. | [
"Response",
"message",
"for",
"KeyManagementService",
".",
"Decrypt",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fe923797da2598c99c772cbb8df7e153c9712322 | chazwong/chaz-bct | src/main/java/chaz/trade/connector/huobi/HuobiWSConnector.java | [
"Apache-2.0"
] | Java | HuobiWSConnector | /**
* Created by Administrator on 2017/8/28.
*/ | Created by Administrator on 2017/8/28. | [
"Created",
"by",
"Administrator",
"on",
"2017",
"/",
"8",
"/",
"28",
"."
] | public class HuobiWSConnector extends AbstractWSConnector {
private static final Logger LOGGER = LoggerFactory.getLogger(HuobiWSConnector.class);
private final String url = "wss://api.huobi.com/ws";
private final String apiv3 = "https://api.huobi.com/apiv3";
private final Gson gson = new GsonBuilder().create();
private final String access_key = "6a674ef0-7468c57c-eff323dd-c9441";
private final String secret_key = "b4167183-2fd35090-a1b96186-7c4f4";
private final Map<String, Account> accountMap = new HashMap<>();
private void init() {
accountMap.put("cny", new Account());
refreshAllAccounts();
}
private Endpoint endpoint;
@Override
protected String getUrl() {
return url;
}
@Override
protected Object getEndpointInstance() {
return endpoint;
}
private void refreshAllAccounts() {
refreshAccount("cny");
}
private void refreshAccount(String market) {
try {
Map<String, Object> map = new HashMap<>();
map.put("method", "get_account_info");
map.put("access_key", access_key);
map.put("created", String.valueOf(System.currentTimeMillis() / 1000));
putMD5(map);
map.put("market", market);
Response httpResponse = ClientBuilder.newClient().target(apiv3).request(MediaType.APPLICATION_JSON).post(Entity.form(Utils.toMultivaluedHashMap(map)));
Map<String, String> response = gson.fromJson(httpResponse.readEntity(String.class), Map.class);
accountMap.get(market).setAvailable(Double.valueOf(response.get("available_cny_display")));
accountMap.get(market).setFrozen(Double.valueOf(response.get("frozen_cny_display")));
} catch (Exception e) {
LOGGER.error("refresh account failed", e);
}
}
private final Map<String, Object> createOrder(Order order) {
Map<String, Object> map = new HashMap<>();
// map.put("method", getMethod(order.getOrderType()));
// map.put("access_key", access_key);
// map.put("coin_type", getCoinType(order.getMarketType()));
// map.put("price", order.getPrice());
// map.put("amount", order.getVolume());
// map.put("created", System.currentTimeMillis());
// putMD5(map);
// map.put("trade_password", "wcz19891124097X");
// map.put("trade_id", 111);
// map.put("market", "cny");
return map;
}
private final String getMethod(chaz.trade.model.OrderType orderType) {
switch (orderType) {
case ASK:
return "sell";
case BID:
return "buy";
default:
throw new RuntimeException("unknown type" + orderType.name());
}
}
private final int getCoinType(MarketType marketType) {
switch (marketType) {
case BTC:
return 1;
case LTC:
return 2;
default:
throw new RuntimeException("unsupported coin type" + marketType.name());
}
}
private final void putMD5(Map<String, Object> map) {
map.put("secret_key", secret_key);
map.put("sign", Utils.MD5(map).toLowerCase());
map.remove("secret_key");
}
} | [
"public",
"class",
"HuobiWSConnector",
"extends",
"AbstractWSConnector",
"{",
"private",
"static",
"final",
"Logger",
"LOGGER",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"HuobiWSConnector",
".",
"class",
")",
";",
"private",
"final",
"String",
"url",
"=",
"\"",
"wss://api.huobi.com/ws",
"\"",
";",
"private",
"final",
"String",
"apiv3",
"=",
"\"",
"https://api.huobi.com/apiv3",
"\"",
";",
"private",
"final",
"Gson",
"gson",
"=",
"new",
"GsonBuilder",
"(",
")",
".",
"create",
"(",
")",
";",
"private",
"final",
"String",
"access_key",
"=",
"\"",
"6a674ef0-7468c57c-eff323dd-c9441",
"\"",
";",
"private",
"final",
"String",
"secret_key",
"=",
"\"",
"b4167183-2fd35090-a1b96186-7c4f4",
"\"",
";",
"private",
"final",
"Map",
"<",
"String",
",",
"Account",
">",
"accountMap",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"private",
"void",
"init",
"(",
")",
"{",
"accountMap",
".",
"put",
"(",
"\"",
"cny",
"\"",
",",
"new",
"Account",
"(",
")",
")",
";",
"refreshAllAccounts",
"(",
")",
";",
"}",
"private",
"Endpoint",
"endpoint",
";",
"@",
"Override",
"protected",
"String",
"getUrl",
"(",
")",
"{",
"return",
"url",
";",
"}",
"@",
"Override",
"protected",
"Object",
"getEndpointInstance",
"(",
")",
"{",
"return",
"endpoint",
";",
"}",
"private",
"void",
"refreshAllAccounts",
"(",
")",
"{",
"refreshAccount",
"(",
"\"",
"cny",
"\"",
")",
";",
"}",
"private",
"void",
"refreshAccount",
"(",
"String",
"market",
")",
"{",
"try",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"map",
".",
"put",
"(",
"\"",
"method",
"\"",
",",
"\"",
"get_account_info",
"\"",
")",
";",
"map",
".",
"put",
"(",
"\"",
"access_key",
"\"",
",",
"access_key",
")",
";",
"map",
".",
"put",
"(",
"\"",
"created",
"\"",
",",
"String",
".",
"valueOf",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
"/",
"1000",
")",
")",
";",
"putMD5",
"(",
"map",
")",
";",
"map",
".",
"put",
"(",
"\"",
"market",
"\"",
",",
"market",
")",
";",
"Response",
"httpResponse",
"=",
"ClientBuilder",
".",
"newClient",
"(",
")",
".",
"target",
"(",
"apiv3",
")",
".",
"request",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
".",
"post",
"(",
"Entity",
".",
"form",
"(",
"Utils",
".",
"toMultivaluedHashMap",
"(",
"map",
")",
")",
")",
";",
"Map",
"<",
"String",
",",
"String",
">",
"response",
"=",
"gson",
".",
"fromJson",
"(",
"httpResponse",
".",
"readEntity",
"(",
"String",
".",
"class",
")",
",",
"Map",
".",
"class",
")",
";",
"accountMap",
".",
"get",
"(",
"market",
")",
".",
"setAvailable",
"(",
"Double",
".",
"valueOf",
"(",
"response",
".",
"get",
"(",
"\"",
"available_cny_display",
"\"",
")",
")",
")",
";",
"accountMap",
".",
"get",
"(",
"market",
")",
".",
"setFrozen",
"(",
"Double",
".",
"valueOf",
"(",
"response",
".",
"get",
"(",
"\"",
"frozen_cny_display",
"\"",
")",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"",
"refresh account failed",
"\"",
",",
"e",
")",
";",
"}",
"}",
"private",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"createOrder",
"(",
"Order",
"order",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"return",
"map",
";",
"}",
"private",
"final",
"String",
"getMethod",
"(",
"chaz",
".",
"trade",
".",
"model",
".",
"OrderType",
"orderType",
")",
"{",
"switch",
"(",
"orderType",
")",
"{",
"case",
"ASK",
":",
"return",
"\"",
"sell",
"\"",
";",
"case",
"BID",
":",
"return",
"\"",
"buy",
"\"",
";",
"default",
":",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"unknown type",
"\"",
"+",
"orderType",
".",
"name",
"(",
")",
")",
";",
"}",
"}",
"private",
"final",
"int",
"getCoinType",
"(",
"MarketType",
"marketType",
")",
"{",
"switch",
"(",
"marketType",
")",
"{",
"case",
"BTC",
":",
"return",
"1",
";",
"case",
"LTC",
":",
"return",
"2",
";",
"default",
":",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"unsupported coin type",
"\"",
"+",
"marketType",
".",
"name",
"(",
")",
")",
";",
"}",
"}",
"private",
"final",
"void",
"putMD5",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
")",
"{",
"map",
".",
"put",
"(",
"\"",
"secret_key",
"\"",
",",
"secret_key",
")",
";",
"map",
".",
"put",
"(",
"\"",
"sign",
"\"",
",",
"Utils",
".",
"MD5",
"(",
"map",
")",
".",
"toLowerCase",
"(",
")",
")",
";",
"map",
".",
"remove",
"(",
"\"",
"secret_key",
"\"",
")",
";",
"}",
"}"
] | Created by Administrator on 2017/8/28. | [
"Created",
"by",
"Administrator",
"on",
"2017",
"/",
"8",
"/",
"28",
"."
] | [
"// map.put(\"method\", getMethod(order.getOrderType()));",
"// map.put(\"access_key\", access_key);",
"// map.put(\"coin_type\", getCoinType(order.getMarketType()));",
"// map.put(\"price\", order.getPrice());",
"// map.put(\"amount\", order.getVolume());",
"// map.put(\"created\", System.currentTimeMillis());",
"// putMD5(map);",
"// map.put(\"trade_password\", \"wcz19891124097X\");",
"// map.put(\"trade_id\", 111);",
"// map.put(\"market\", \"cny\");"
] | [
{
"param": "AbstractWSConnector",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractWSConnector",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fe98d6287c1f0b916baf1eb83d98043fb6c82421 | CommuniTakeLtd/core | src/main/java/org/primefaces/extensions/application/PrimeFacesExtensionsResourceHandler.java | [
"Apache-2.0"
] | Java | PrimeFacesExtensionsResourceHandler | /**
* {@link ResourceHandlerWrapper} which wraps PrimeFaces Extensions resources and appends the version of PrimeFaces Extensions in the
* {@link PrimeFacesExtensionsResource}.
*
* @author Thomas Andraschko / last modified by $Author$
* @version $Revision$
* @since 0.1
*/ | ResourceHandlerWrapper which wraps PrimeFaces Extensions resources and appends the version of PrimeFaces Extensions in the
PrimeFacesExtensionsResource.
@author Thomas Andraschko / last modified by $Author$
@version $Revision$
@since 0.1 | [
"ResourceHandlerWrapper",
"which",
"wraps",
"PrimeFaces",
"Extensions",
"resources",
"and",
"appends",
"the",
"version",
"of",
"PrimeFaces",
"Extensions",
"in",
"the",
"PrimeFacesExtensionsResource",
".",
"@author",
"Thomas",
"Andraschko",
"/",
"last",
"modified",
"by",
"$Author$",
"@version",
"$Revision$",
"@since",
"0",
".",
"1"
] | public class PrimeFacesExtensionsResourceHandler extends ResourceHandlerWrapper {
private final ResourceHandler wrapped;
public PrimeFacesExtensionsResourceHandler(final ResourceHandler resourceHandler) {
super();
wrapped = resourceHandler;
}
@Override
public ResourceHandler getWrapped() {
return wrapped;
}
@Override
public Resource createResource(final String resourceName, final String libraryName) {
if (Constants.LIBRARY.equalsIgnoreCase(libraryName)) {
Resource resource = super.createResource(resourceName, libraryName);
return resource != null ? new PrimeFacesExtensionsResource(resource) : null;
}
return super.createResource(resourceName, libraryName);
}
@Override
public Resource createResource(String resourceName, String libraryName, String contentType) {
if (Constants.LIBRARY.equalsIgnoreCase(libraryName)) {
Resource resource = super.createResource(resourceName, libraryName, contentType);
return resource != null ? new PrimeFacesExtensionsResource(resource) : null;
}
return super.createResource(resourceName, libraryName, contentType);
}
} | [
"public",
"class",
"PrimeFacesExtensionsResourceHandler",
"extends",
"ResourceHandlerWrapper",
"{",
"private",
"final",
"ResourceHandler",
"wrapped",
";",
"public",
"PrimeFacesExtensionsResourceHandler",
"(",
"final",
"ResourceHandler",
"resourceHandler",
")",
"{",
"super",
"(",
")",
";",
"wrapped",
"=",
"resourceHandler",
";",
"}",
"@",
"Override",
"public",
"ResourceHandler",
"getWrapped",
"(",
")",
"{",
"return",
"wrapped",
";",
"}",
"@",
"Override",
"public",
"Resource",
"createResource",
"(",
"final",
"String",
"resourceName",
",",
"final",
"String",
"libraryName",
")",
"{",
"if",
"(",
"Constants",
".",
"LIBRARY",
".",
"equalsIgnoreCase",
"(",
"libraryName",
")",
")",
"{",
"Resource",
"resource",
"=",
"super",
".",
"createResource",
"(",
"resourceName",
",",
"libraryName",
")",
";",
"return",
"resource",
"!=",
"null",
"?",
"new",
"PrimeFacesExtensionsResource",
"(",
"resource",
")",
":",
"null",
";",
"}",
"return",
"super",
".",
"createResource",
"(",
"resourceName",
",",
"libraryName",
")",
";",
"}",
"@",
"Override",
"public",
"Resource",
"createResource",
"(",
"String",
"resourceName",
",",
"String",
"libraryName",
",",
"String",
"contentType",
")",
"{",
"if",
"(",
"Constants",
".",
"LIBRARY",
".",
"equalsIgnoreCase",
"(",
"libraryName",
")",
")",
"{",
"Resource",
"resource",
"=",
"super",
".",
"createResource",
"(",
"resourceName",
",",
"libraryName",
",",
"contentType",
")",
";",
"return",
"resource",
"!=",
"null",
"?",
"new",
"PrimeFacesExtensionsResource",
"(",
"resource",
")",
":",
"null",
";",
"}",
"return",
"super",
".",
"createResource",
"(",
"resourceName",
",",
"libraryName",
",",
"contentType",
")",
";",
"}",
"}"
] | {@link ResourceHandlerWrapper} which wraps PrimeFaces Extensions resources and appends the version of PrimeFaces Extensions in the
{@link PrimeFacesExtensionsResource}. | [
"{",
"@link",
"ResourceHandlerWrapper",
"}",
"which",
"wraps",
"PrimeFaces",
"Extensions",
"resources",
"and",
"appends",
"the",
"version",
"of",
"PrimeFaces",
"Extensions",
"in",
"the",
"{",
"@link",
"PrimeFacesExtensionsResource",
"}",
"."
] | [] | [
{
"param": "ResourceHandlerWrapper",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ResourceHandlerWrapper",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fea0187eed69a684484d76e8d3bb618290413c74 | mli014/hadoop-openstack-swifta | src/main/java/org/apache/hadoop/fs/swifta/snative/SwiftNativeOutputStreamMultipartWithSplit.java | [
"Apache-2.0"
] | Java | SwiftNativeOutputStreamMultipartWithSplit | /**
* Output stream, buffers data on local disk. Writes to Swift on the close() method, unless the file
* is significantly large that it is being written as partitions. In this case, the first partition
* is written on the first write that puts data over the partition, as may later writes. The close()
* then causes the final partition to be written, along with a partition manifest.
*/ | Output stream, buffers data on local disk. Writes to Swift on the close() method, unless the file
is significantly large that it is being written as partitions. In this case, the first partition
is written on the first write that puts data over the partition, as may later writes. The close()
then causes the final partition to be written, along with a partition manifest. | [
"Output",
"stream",
"buffers",
"data",
"on",
"local",
"disk",
".",
"Writes",
"to",
"Swift",
"on",
"the",
"close",
"()",
"method",
"unless",
"the",
"file",
"is",
"significantly",
"large",
"that",
"it",
"is",
"being",
"written",
"as",
"partitions",
".",
"In",
"this",
"case",
"the",
"first",
"partition",
"is",
"written",
"on",
"the",
"first",
"write",
"that",
"puts",
"data",
"over",
"the",
"partition",
"as",
"may",
"later",
"writes",
".",
"The",
"close",
"()",
"then",
"causes",
"the",
"final",
"partition",
"to",
"be",
"written",
"along",
"with",
"a",
"partition",
"manifest",
"."
] | public class SwiftNativeOutputStreamMultipartWithSplit extends SwiftOutputStream {
private static final Log LOG = LogFactory.getLog(SwiftNativeOutputStreamMultipartWithSplit.class);
private static final MetricsFactory metric =
MetricsFactory.getMetricsFactory(SwiftNativeOutputStreamMultipartWithSplit.class);
private static final int ATTEMPT_LIMIT = 3;
private long filePartSize;
private String key;
private BufferedOutputStream backupStream;
private final SwiftNativeFileSystemStore nativeStore;
private boolean closed;
private long blockOffset;
private long bytesWritten;
private AtomicLong bytesUploaded;
private volatile boolean partUpload = false;
/**
* The minimum files to trigger a background upload.
*/
static final int BACKGROUND_UPLOAD_BATCH_SIZE = 20;
final byte[] oneByte = new byte[1];
final String backupDir;
BlockingQueue<BackupFile> backupFiles;
private AtomicInteger partNumber;
@SuppressWarnings("rawtypes")
final List<Future> uploads;
@SuppressWarnings("rawtypes")
final List<Future> closes;
final File dir;
private AsynchronousUpload uploadThread;
private int outputBufferSize = DEFAULT_SWIFT_INPUT_STREAM_BUFFER_SIZE;
private ThreadManager closeThreads = null;
private BackupFile file;
private File newDir;
/**
* Create an output stream.
*
* @param conf configuration to use
* @param nativeStore native store to write through
* @param key the key to write
* @param partSizeKB the partition size
* @param outputBufferSize buffer size
* @throws IOException IOException
*/
@SuppressWarnings("rawtypes")
public SwiftNativeOutputStreamMultipartWithSplit(Configuration conf,
SwiftNativeFileSystemStore nativeStore, String key, long partSizeKB, int outputBufferSize)
throws IOException {
dir = new File(conf.get(HADOOP_TMP_DIR));
this.key = key;
this.nativeStore = nativeStore;
this.blockOffset = 0;
this.partNumber = new AtomicInteger(1);
bytesUploaded = new AtomicLong(0);
this.filePartSize = partSizeKB << 10;
backupDir = UUID.randomUUID().toString();
backupFiles = new LinkedBlockingQueue<BackupFile>();
newDir = new File(dir, backupDir);
newDir.deleteOnExit();
if (!newDir.exists()) {
if (!newDir.mkdirs() && !newDir.exists()) {
throw new SwiftException("Cannot create Swift buffer directory: " + dir);
}
}
this.openForWrite(partNumber.getAndIncrement());
uploads = new ArrayList<Future>();
closes = new ArrayList<Future>();
if (outputBufferSize > 0) {
this.outputBufferSize = outputBufferSize;
}
closeThreads = new ThreadManager(15, 20, Boolean.TRUE);
metric.increase(key, this);
metric.report();
}
private synchronized void openForWrite(int partNumber) throws IOException {
if (backupStream != null) {
BufferedOutputStream oldStream = backupStream;
closes.add(this.doClose(closeThreads, oldStream, file));
}
File tmp = newBackupFile(partNumber);
file = new BackupFile(tmp, partNumber,
new BufferedOutputStream(new FileOutputStream(tmp), outputBufferSize));
backupFiles.offer(file);
backupStream = file.getOutput();
}
private File newBackupFile(int partNumber) throws IOException {
String file = SwiftUtils.partitionFilenameFromNumber(partNumber);
if (LOG.isDebugEnabled()) {
LOG.debug("Temporary file:" + newDir + "/" + file);
}
File result = File.createTempFile(file, ".tmp", newDir);
result.deleteOnExit();
return result;
}
/**
* Flush the local backing stream. This does not trigger a flush of data to the remote blobstore.
*
* @throws IOException IOException
*/
@Override
public synchronized void flush() throws IOException {
backupStream.flush();
}
/**
* Check that the output stream is open.
*
* @throws SwiftException if it is not
*/
private synchronized void verifyOpen() throws SwiftException {
if (closed) {
throw new SwiftException("Output stream is closed");
}
}
/**
* Close the stream. This will trigger the upload of all locally cached data to the remote
* blobstore.
*
* @throws IOException IO problems uploading the data.
*/
@Override
public synchronized void close() throws IOException {
if (closed) {
return;
}
try {
if (backupStream != null) {
backupStream.close();
}
this.cleanCloseThread();
closed = true;
this.waitToFinish(closes);
this.cleanUploadThread();
Path keypath = new Path(key);
if (partUpload) {
// uploadParts();
nativeStore.createManifestForPartUpload(keypath, this.bytesUploaded.get());
} else {
uploadOnClose(keypath);
}
} finally {
cleanBackupFiles();
// this.cleanUploadThread();
this.clean();
metric.remove(this);
metric.report();
}
}
private void cleanUploadThread() {
if (uploadThread != null) {
uploadThread.close();
}
}
private void clean() {
try {
if (newDir != null) {
FileUtils.cleanDirectory(newDir);
}
} catch (Exception e) {
// Quiet
}
}
private void cleanCloseThread() {
if (closeThreads != null) {
closeThreads.shutdown();
}
}
@SuppressWarnings("rawtypes")
Future doClose(final ThreadManager tm, final OutputStream out, final BackupFile file) {
return tm.getPool().submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
try {
// Wait write to finish
if (out != null) {
out.close();
}
return Boolean.TRUE;
} catch (IOException e) {
LOG.error(e.getMessage());
return false;
} finally {
synchronized (file.lock) {
file.lock.notifyAll();
}
file.setClosed(Boolean.TRUE);
}
}
});
}
/**
* Do the actually upload.
*/
@SuppressWarnings("rawtypes")
public List<Future> doUpload(final ThreadManager tm, final BackupFile uploadFile,
final int partNumber) {
uploads.add(tm.getPool().submit(new Callable<Boolean>() {
public Boolean call() throws Exception {
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Upload file " + uploadFile.getUploadFile().getName() + ";partNumber="
+ partNumber + ";len=" + uploadFile.getUploadFile().length());
}
if (uploadFile.getOutput() != null) {
uploadFile.getOutput().close();
}
partUpload(uploadFile.getUploadFile(), partNumber);
return Boolean.TRUE;
} catch (IOException e) {
LOG.error(e.getMessage());
return false;
}
}
}));
return uploads;
}
private void cleanBackupFiles() {
if (backupFiles != null) {
// for (final BackupFile file : backupFiles) {
// delete(file.getUploadFile());
// }
backupFiles.clear();
}
}
/**
* Upload a file when closed, either in one go, or, if the file is already partitioned, by
* uploading the remaining partition and a manifest.
*
* @param keypath key as a path
* @throws IOException IO Problems
*/
private void uploadOnClose(Path keypath) throws IOException {
if (backupFiles.size() < 1) {
throw new SwiftException("No file to upload!");
}
if (backupFiles.size() > 1) {
throw new SwiftException("Too many backup file to upload. size = " + backupFiles.size());
}
boolean uploadSuccess = false;
int attempt = 0;
BackupFile backupFile = backupFiles.poll();
while (!uploadSuccess) {
try {
++attempt;
bytesUploaded.addAndGet(uploadFileAttempt(keypath, attempt, backupFile.getUploadFile()));
uploadSuccess = true;
} catch (IOException e) {
LOG.error("Upload failed " + e, e);
if (attempt > ATTEMPT_LIMIT) {
throw e;
}
}
}
}
private long uploadFileAttempt(Path keypath, int attempt, File backupFile) throws IOException {
long uploadLen = backupFile.length();
SwiftUtils.debug(LOG, "Closing write of file %s;" + " localfile=%s of length %d - attempt %d",
key, backupFile, uploadLen, attempt);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(backupFile);
nativeStore.uploadFile(keypath, inputStream, uploadLen);
} catch (IOException e) {
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
}
return uploadLen;
}
@SuppressWarnings("unused")
private void delete(File file) {
if (file != null) {
SwiftUtils.debug(LOG, "deleting %s", file);
if (!file.delete()) {
LOG.warn("Could not delete " + file);
file.deleteOnExit();
}
}
}
@Override
public void write(int b) throws IOException {
// insert to a one byte array
oneByte[0] = (byte) b;
// then delegate to the array writing routine
write(oneByte, 0, 1);
}
@Override
public synchronized void write(byte[] buffer, int offset, int len) throws IOException {
// validate args
if (offset < 0 || len < 0 || (offset + len) > buffer.length) {
throw new IndexOutOfBoundsException("Invalid offset/length for write");
}
// validate the output stream
verifyOpen();
this.autoWriteToSplittedBackupStream(buffer, offset, len);
}
@Override
protected void finalize() throws Throwable {
this.clean();
}
/**
* Write to the backup stream. Guarantees:
* <ol>
* <li>backupStream is open</li>
* <li>blockOffset + len < filePartSize</li>
* </ol>
*
* @param buffer buffer to write
* @param offset offset in buffer
* @param len length of write.
* @throws IOException backup stream write failing
*/
private void autoWriteToSplittedBackupStream(byte[] buffer, int offset, int len)
throws IOException {
while (len > 0) {
if ((blockOffset + len) >= filePartSize) {
int subLen = (int) (filePartSize - blockOffset);
backupStream.write(buffer, offset, subLen);
// Don't have to close backupStream here.
offset += subLen;
len -= subLen;
bytesWritten += subLen;
blockOffset = 0;
partUpload = Boolean.TRUE;
this.openForWrite(partNumber.getAndIncrement());
} else {
backupStream.write(buffer, offset, len);
blockOffset += len;
bytesWritten += len;
len = 0;
}
}
/**
* No race condition here. Upload files ahead if need.
*/
if (uploadThread == null && partUpload) {
int maxThreads = nativeStore.getMaxInParallelUpload() < 1
? SwiftNativeOutputStreamMultipartWithSplit.BACKGROUND_UPLOAD_BATCH_SIZE
: nativeStore.getMaxInParallelUpload();
uploadThread = new AsynchronousUpload(backupFiles, this, maxThreads);
uploadThread.start();
}
}
/**
* Wait to finish.
*/
@SuppressWarnings("rawtypes")
public boolean waitToFinish(List<Future> tasks) {
for (Future task : tasks) {
try {
task.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
task.cancel(Boolean.FALSE);
}
}
tasks.clear();
tasks = null;
return Boolean.TRUE;
}
/**
* Upload a single partition. This deletes the local backing-file, and re-opens it to create a new
* one.
*
* @param closingUpload is this the final upload of an upload
* @throws IOException on IO problems
*/
private void partUpload(final File backupFile, final int partNumber) throws IOException {
if (partUpload && backupFile.length() == 0) {
// skipping the upload if
// - it is close time
// - the final partition is 0 bytes long
// - one part has already been written
SwiftUtils.debug(LOG, "skipping upload of 0 byte final partition");
// delete(backupFile);
} else {
boolean uploadSuccess = false;
int attempt = 0;
while (!uploadSuccess) {
try {
bytesUploaded.addAndGet(uploadFilePartAttempt(attempt++, backupFile, partNumber));
uploadSuccess = true;
} catch (IOException e) {
LOG.error("Upload failed " + e, e);
if (attempt > ATTEMPT_LIMIT) {
throw e;
}
}
}
}
}
private long uploadFilePartAttempt(final int attempt, final File backupFile, final int partNumber)
throws IOException {
long uploadLen = backupFile.length();
BufferedInputStream inputStream = null;
FileInputStream input = null;
try {
input = new FileInputStream(backupFile);
inputStream = new BufferedInputStream(input);
nativeStore.uploadFilePart(new Path(key), partNumber, input, uploadLen);
} catch (IOException e) {
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(input);
backupFile.delete();
}
return uploadLen;
}
/**
* Get the file partition size.
*
* @return the partition size
*/
@Override
public long getFilePartSize() {
return filePartSize;
}
/**
* Query the number of partitions written This is intended for testing.
*
* @return the of partitions already written to the remote FS
*/
@Override
public synchronized int getPartitionsWritten() {
return partNumber.get() - 2;
}
/**
* Get the number of bytes written to the output stream. This should always be less than or equal
* to bytesUploaded.
*
* @return the number of bytes written to this stream
*/
@Override
public long getBytesWritten() {
return bytesWritten;
}
/**
* Get the number of bytes uploaded to remote Swift cluster. bytesUploaded -bytesWritten = the
* number of bytes left to upload.
*
* @return the number of bytes written to the remote endpoint
*/
@Override
public synchronized long getBytesUploaded() {
return bytesUploaded.get();
}
@Override
public String toString() {
return "SwiftNativeOutputStreamMultipartWithSplit{" + ", key='" + key + '\'' + ", closed="
+ closed + ", filePartSize=" + filePartSize + ", blockOffset=" + blockOffset
+ ", partUpload=" + partUpload + ", nativeStore=" + nativeStore + ", bytesWritten="
+ bytesWritten + ", bytesUploaded=" + bytesUploaded + '}';
}
} | [
"public",
"class",
"SwiftNativeOutputStreamMultipartWithSplit",
"extends",
"SwiftOutputStream",
"{",
"private",
"static",
"final",
"Log",
"LOG",
"=",
"LogFactory",
".",
"getLog",
"(",
"SwiftNativeOutputStreamMultipartWithSplit",
".",
"class",
")",
";",
"private",
"static",
"final",
"MetricsFactory",
"metric",
"=",
"MetricsFactory",
".",
"getMetricsFactory",
"(",
"SwiftNativeOutputStreamMultipartWithSplit",
".",
"class",
")",
";",
"private",
"static",
"final",
"int",
"ATTEMPT_LIMIT",
"=",
"3",
";",
"private",
"long",
"filePartSize",
";",
"private",
"String",
"key",
";",
"private",
"BufferedOutputStream",
"backupStream",
";",
"private",
"final",
"SwiftNativeFileSystemStore",
"nativeStore",
";",
"private",
"boolean",
"closed",
";",
"private",
"long",
"blockOffset",
";",
"private",
"long",
"bytesWritten",
";",
"private",
"AtomicLong",
"bytesUploaded",
";",
"private",
"volatile",
"boolean",
"partUpload",
"=",
"false",
";",
"/**\n * The minimum files to trigger a background upload.\n */",
"static",
"final",
"int",
"BACKGROUND_UPLOAD_BATCH_SIZE",
"=",
"20",
";",
"final",
"byte",
"[",
"]",
"oneByte",
"=",
"new",
"byte",
"[",
"1",
"]",
";",
"final",
"String",
"backupDir",
";",
"BlockingQueue",
"<",
"BackupFile",
">",
"backupFiles",
";",
"private",
"AtomicInteger",
"partNumber",
";",
"@",
"SuppressWarnings",
"(",
"\"",
"rawtypes",
"\"",
")",
"final",
"List",
"<",
"Future",
">",
"uploads",
";",
"@",
"SuppressWarnings",
"(",
"\"",
"rawtypes",
"\"",
")",
"final",
"List",
"<",
"Future",
">",
"closes",
";",
"final",
"File",
"dir",
";",
"private",
"AsynchronousUpload",
"uploadThread",
";",
"private",
"int",
"outputBufferSize",
"=",
"DEFAULT_SWIFT_INPUT_STREAM_BUFFER_SIZE",
";",
"private",
"ThreadManager",
"closeThreads",
"=",
"null",
";",
"private",
"BackupFile",
"file",
";",
"private",
"File",
"newDir",
";",
"/**\n * Create an output stream.\n * \n * @param conf configuration to use\n * @param nativeStore native store to write through\n * @param key the key to write\n * @param partSizeKB the partition size\n * @param outputBufferSize buffer size\n * @throws IOException IOException\n */",
"@",
"SuppressWarnings",
"(",
"\"",
"rawtypes",
"\"",
")",
"public",
"SwiftNativeOutputStreamMultipartWithSplit",
"(",
"Configuration",
"conf",
",",
"SwiftNativeFileSystemStore",
"nativeStore",
",",
"String",
"key",
",",
"long",
"partSizeKB",
",",
"int",
"outputBufferSize",
")",
"throws",
"IOException",
"{",
"dir",
"=",
"new",
"File",
"(",
"conf",
".",
"get",
"(",
"HADOOP_TMP_DIR",
")",
")",
";",
"this",
".",
"key",
"=",
"key",
";",
"this",
".",
"nativeStore",
"=",
"nativeStore",
";",
"this",
".",
"blockOffset",
"=",
"0",
";",
"this",
".",
"partNumber",
"=",
"new",
"AtomicInteger",
"(",
"1",
")",
";",
"bytesUploaded",
"=",
"new",
"AtomicLong",
"(",
"0",
")",
";",
"this",
".",
"filePartSize",
"=",
"partSizeKB",
"<<",
"10",
";",
"backupDir",
"=",
"UUID",
".",
"randomUUID",
"(",
")",
".",
"toString",
"(",
")",
";",
"backupFiles",
"=",
"new",
"LinkedBlockingQueue",
"<",
"BackupFile",
">",
"(",
")",
";",
"newDir",
"=",
"new",
"File",
"(",
"dir",
",",
"backupDir",
")",
";",
"newDir",
".",
"deleteOnExit",
"(",
")",
";",
"if",
"(",
"!",
"newDir",
".",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"!",
"newDir",
".",
"mkdirs",
"(",
")",
"&&",
"!",
"newDir",
".",
"exists",
"(",
")",
")",
"{",
"throw",
"new",
"SwiftException",
"(",
"\"",
"Cannot create Swift buffer directory: ",
"\"",
"+",
"dir",
")",
";",
"}",
"}",
"this",
".",
"openForWrite",
"(",
"partNumber",
".",
"getAndIncrement",
"(",
")",
")",
";",
"uploads",
"=",
"new",
"ArrayList",
"<",
"Future",
">",
"(",
")",
";",
"closes",
"=",
"new",
"ArrayList",
"<",
"Future",
">",
"(",
")",
";",
"if",
"(",
"outputBufferSize",
">",
"0",
")",
"{",
"this",
".",
"outputBufferSize",
"=",
"outputBufferSize",
";",
"}",
"closeThreads",
"=",
"new",
"ThreadManager",
"(",
"15",
",",
"20",
",",
"Boolean",
".",
"TRUE",
")",
";",
"metric",
".",
"increase",
"(",
"key",
",",
"this",
")",
";",
"metric",
".",
"report",
"(",
")",
";",
"}",
"private",
"synchronized",
"void",
"openForWrite",
"(",
"int",
"partNumber",
")",
"throws",
"IOException",
"{",
"if",
"(",
"backupStream",
"!=",
"null",
")",
"{",
"BufferedOutputStream",
"oldStream",
"=",
"backupStream",
";",
"closes",
".",
"add",
"(",
"this",
".",
"doClose",
"(",
"closeThreads",
",",
"oldStream",
",",
"file",
")",
")",
";",
"}",
"File",
"tmp",
"=",
"newBackupFile",
"(",
"partNumber",
")",
";",
"file",
"=",
"new",
"BackupFile",
"(",
"tmp",
",",
"partNumber",
",",
"new",
"BufferedOutputStream",
"(",
"new",
"FileOutputStream",
"(",
"tmp",
")",
",",
"outputBufferSize",
")",
")",
";",
"backupFiles",
".",
"offer",
"(",
"file",
")",
";",
"backupStream",
"=",
"file",
".",
"getOutput",
"(",
")",
";",
"}",
"private",
"File",
"newBackupFile",
"(",
"int",
"partNumber",
")",
"throws",
"IOException",
"{",
"String",
"file",
"=",
"SwiftUtils",
".",
"partitionFilenameFromNumber",
"(",
"partNumber",
")",
";",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"Temporary file:",
"\"",
"+",
"newDir",
"+",
"\"",
"/",
"\"",
"+",
"file",
")",
";",
"}",
"File",
"result",
"=",
"File",
".",
"createTempFile",
"(",
"file",
",",
"\"",
".tmp",
"\"",
",",
"newDir",
")",
";",
"result",
".",
"deleteOnExit",
"(",
")",
";",
"return",
"result",
";",
"}",
"/**\n * Flush the local backing stream. This does not trigger a flush of data to the remote blobstore.\n * \n * @throws IOException IOException\n */",
"@",
"Override",
"public",
"synchronized",
"void",
"flush",
"(",
")",
"throws",
"IOException",
"{",
"backupStream",
".",
"flush",
"(",
")",
";",
"}",
"/**\n * Check that the output stream is open.\n *\n * @throws SwiftException if it is not\n */",
"private",
"synchronized",
"void",
"verifyOpen",
"(",
")",
"throws",
"SwiftException",
"{",
"if",
"(",
"closed",
")",
"{",
"throw",
"new",
"SwiftException",
"(",
"\"",
"Output stream is closed",
"\"",
")",
";",
"}",
"}",
"/**\n * Close the stream. This will trigger the upload of all locally cached data to the remote\n * blobstore.\n * \n * @throws IOException IO problems uploading the data.\n */",
"@",
"Override",
"public",
"synchronized",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"closed",
")",
"{",
"return",
";",
"}",
"try",
"{",
"if",
"(",
"backupStream",
"!=",
"null",
")",
"{",
"backupStream",
".",
"close",
"(",
")",
";",
"}",
"this",
".",
"cleanCloseThread",
"(",
")",
";",
"closed",
"=",
"true",
";",
"this",
".",
"waitToFinish",
"(",
"closes",
")",
";",
"this",
".",
"cleanUploadThread",
"(",
")",
";",
"Path",
"keypath",
"=",
"new",
"Path",
"(",
"key",
")",
";",
"if",
"(",
"partUpload",
")",
"{",
"nativeStore",
".",
"createManifestForPartUpload",
"(",
"keypath",
",",
"this",
".",
"bytesUploaded",
".",
"get",
"(",
")",
")",
";",
"}",
"else",
"{",
"uploadOnClose",
"(",
"keypath",
")",
";",
"}",
"}",
"finally",
"{",
"cleanBackupFiles",
"(",
")",
";",
"this",
".",
"clean",
"(",
")",
";",
"metric",
".",
"remove",
"(",
"this",
")",
";",
"metric",
".",
"report",
"(",
")",
";",
"}",
"}",
"private",
"void",
"cleanUploadThread",
"(",
")",
"{",
"if",
"(",
"uploadThread",
"!=",
"null",
")",
"{",
"uploadThread",
".",
"close",
"(",
")",
";",
"}",
"}",
"private",
"void",
"clean",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"newDir",
"!=",
"null",
")",
"{",
"FileUtils",
".",
"cleanDirectory",
"(",
"newDir",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"}",
"private",
"void",
"cleanCloseThread",
"(",
")",
"{",
"if",
"(",
"closeThreads",
"!=",
"null",
")",
"{",
"closeThreads",
".",
"shutdown",
"(",
")",
";",
"}",
"}",
"@",
"SuppressWarnings",
"(",
"\"",
"rawtypes",
"\"",
")",
"Future",
"doClose",
"(",
"final",
"ThreadManager",
"tm",
",",
"final",
"OutputStream",
"out",
",",
"final",
"BackupFile",
"file",
")",
"{",
"return",
"tm",
".",
"getPool",
"(",
")",
".",
"submit",
"(",
"new",
"Callable",
"<",
"Boolean",
">",
"(",
")",
"{",
"public",
"Boolean",
"call",
"(",
")",
"throws",
"Exception",
"{",
"try",
"{",
"if",
"(",
"out",
"!=",
"null",
")",
"{",
"out",
".",
"close",
"(",
")",
";",
"}",
"return",
"Boolean",
".",
"TRUE",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"finally",
"{",
"synchronized",
"(",
"file",
".",
"lock",
")",
"{",
"file",
".",
"lock",
".",
"notifyAll",
"(",
")",
";",
"}",
"file",
".",
"setClosed",
"(",
"Boolean",
".",
"TRUE",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"/**\n * Do the actually upload.\n */",
"@",
"SuppressWarnings",
"(",
"\"",
"rawtypes",
"\"",
")",
"public",
"List",
"<",
"Future",
">",
"doUpload",
"(",
"final",
"ThreadManager",
"tm",
",",
"final",
"BackupFile",
"uploadFile",
",",
"final",
"int",
"partNumber",
")",
"{",
"uploads",
".",
"add",
"(",
"tm",
".",
"getPool",
"(",
")",
".",
"submit",
"(",
"new",
"Callable",
"<",
"Boolean",
">",
"(",
")",
"{",
"public",
"Boolean",
"call",
"(",
")",
"throws",
"Exception",
"{",
"try",
"{",
"if",
"(",
"LOG",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"Upload file ",
"\"",
"+",
"uploadFile",
".",
"getUploadFile",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"",
";partNumber=",
"\"",
"+",
"partNumber",
"+",
"\"",
";len=",
"\"",
"+",
"uploadFile",
".",
"getUploadFile",
"(",
")",
".",
"length",
"(",
")",
")",
";",
"}",
"if",
"(",
"uploadFile",
".",
"getOutput",
"(",
")",
"!=",
"null",
")",
"{",
"uploadFile",
".",
"getOutput",
"(",
")",
".",
"close",
"(",
")",
";",
"}",
"partUpload",
"(",
"uploadFile",
".",
"getUploadFile",
"(",
")",
",",
"partNumber",
")",
";",
"return",
"Boolean",
".",
"TRUE",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"}",
"}",
")",
")",
";",
"return",
"uploads",
";",
"}",
"private",
"void",
"cleanBackupFiles",
"(",
")",
"{",
"if",
"(",
"backupFiles",
"!=",
"null",
")",
"{",
"backupFiles",
".",
"clear",
"(",
")",
";",
"}",
"}",
"/**\n * Upload a file when closed, either in one go, or, if the file is already partitioned, by\n * uploading the remaining partition and a manifest.\n * \n * @param keypath key as a path\n * @throws IOException IO Problems\n */",
"private",
"void",
"uploadOnClose",
"(",
"Path",
"keypath",
")",
"throws",
"IOException",
"{",
"if",
"(",
"backupFiles",
".",
"size",
"(",
")",
"<",
"1",
")",
"{",
"throw",
"new",
"SwiftException",
"(",
"\"",
"No file to upload!",
"\"",
")",
";",
"}",
"if",
"(",
"backupFiles",
".",
"size",
"(",
")",
">",
"1",
")",
"{",
"throw",
"new",
"SwiftException",
"(",
"\"",
"Too many backup file to upload. size = ",
"\"",
"+",
"backupFiles",
".",
"size",
"(",
")",
")",
";",
"}",
"boolean",
"uploadSuccess",
"=",
"false",
";",
"int",
"attempt",
"=",
"0",
";",
"BackupFile",
"backupFile",
"=",
"backupFiles",
".",
"poll",
"(",
")",
";",
"while",
"(",
"!",
"uploadSuccess",
")",
"{",
"try",
"{",
"++",
"attempt",
";",
"bytesUploaded",
".",
"addAndGet",
"(",
"uploadFileAttempt",
"(",
"keypath",
",",
"attempt",
",",
"backupFile",
".",
"getUploadFile",
"(",
")",
")",
")",
";",
"uploadSuccess",
"=",
"true",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Upload failed ",
"\"",
"+",
"e",
",",
"e",
")",
";",
"if",
"(",
"attempt",
">",
"ATTEMPT_LIMIT",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"}",
"}",
"private",
"long",
"uploadFileAttempt",
"(",
"Path",
"keypath",
",",
"int",
"attempt",
",",
"File",
"backupFile",
")",
"throws",
"IOException",
"{",
"long",
"uploadLen",
"=",
"backupFile",
".",
"length",
"(",
")",
";",
"SwiftUtils",
".",
"debug",
"(",
"LOG",
",",
"\"",
"Closing write of file %s;",
"\"",
"+",
"\"",
" localfile=%s of length %d - attempt %d",
"\"",
",",
"key",
",",
"backupFile",
",",
"uploadLen",
",",
"attempt",
")",
";",
"FileInputStream",
"inputStream",
"=",
"null",
";",
"try",
"{",
"inputStream",
"=",
"new",
"FileInputStream",
"(",
"backupFile",
")",
";",
"nativeStore",
".",
"uploadFile",
"(",
"keypath",
",",
"inputStream",
",",
"uploadLen",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"inputStream",
")",
";",
"}",
"return",
"uploadLen",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"private",
"void",
"delete",
"(",
"File",
"file",
")",
"{",
"if",
"(",
"file",
"!=",
"null",
")",
"{",
"SwiftUtils",
".",
"debug",
"(",
"LOG",
",",
"\"",
"deleting %s",
"\"",
",",
"file",
")",
";",
"if",
"(",
"!",
"file",
".",
"delete",
"(",
")",
")",
"{",
"LOG",
".",
"warn",
"(",
"\"",
"Could not delete ",
"\"",
"+",
"file",
")",
";",
"file",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"int",
"b",
")",
"throws",
"IOException",
"{",
"oneByte",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"b",
";",
"write",
"(",
"oneByte",
",",
"0",
",",
"1",
")",
";",
"}",
"@",
"Override",
"public",
"synchronized",
"void",
"write",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"if",
"(",
"offset",
"<",
"0",
"||",
"len",
"<",
"0",
"||",
"(",
"offset",
"+",
"len",
")",
">",
"buffer",
".",
"length",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
"\"",
"Invalid offset/length for write",
"\"",
")",
";",
"}",
"verifyOpen",
"(",
")",
";",
"this",
".",
"autoWriteToSplittedBackupStream",
"(",
"buffer",
",",
"offset",
",",
"len",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"finalize",
"(",
")",
"throws",
"Throwable",
"{",
"this",
".",
"clean",
"(",
")",
";",
"}",
"/**\n * Write to the backup stream. Guarantees:\n * <ol>\n * <li>backupStream is open</li>\n * <li>blockOffset + len < filePartSize</li>\n * </ol>\n * \n * @param buffer buffer to write\n * @param offset offset in buffer\n * @param len length of write.\n * @throws IOException backup stream write failing\n */",
"private",
"void",
"autoWriteToSplittedBackupStream",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"offset",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"while",
"(",
"len",
">",
"0",
")",
"{",
"if",
"(",
"(",
"blockOffset",
"+",
"len",
")",
">=",
"filePartSize",
")",
"{",
"int",
"subLen",
"=",
"(",
"int",
")",
"(",
"filePartSize",
"-",
"blockOffset",
")",
";",
"backupStream",
".",
"write",
"(",
"buffer",
",",
"offset",
",",
"subLen",
")",
";",
"offset",
"+=",
"subLen",
";",
"len",
"-=",
"subLen",
";",
"bytesWritten",
"+=",
"subLen",
";",
"blockOffset",
"=",
"0",
";",
"partUpload",
"=",
"Boolean",
".",
"TRUE",
";",
"this",
".",
"openForWrite",
"(",
"partNumber",
".",
"getAndIncrement",
"(",
")",
")",
";",
"}",
"else",
"{",
"backupStream",
".",
"write",
"(",
"buffer",
",",
"offset",
",",
"len",
")",
";",
"blockOffset",
"+=",
"len",
";",
"bytesWritten",
"+=",
"len",
";",
"len",
"=",
"0",
";",
"}",
"}",
"/**\n * No race condition here. Upload files ahead if need.\n */",
"if",
"(",
"uploadThread",
"==",
"null",
"&&",
"partUpload",
")",
"{",
"int",
"maxThreads",
"=",
"nativeStore",
".",
"getMaxInParallelUpload",
"(",
")",
"<",
"1",
"?",
"SwiftNativeOutputStreamMultipartWithSplit",
".",
"BACKGROUND_UPLOAD_BATCH_SIZE",
":",
"nativeStore",
".",
"getMaxInParallelUpload",
"(",
")",
";",
"uploadThread",
"=",
"new",
"AsynchronousUpload",
"(",
"backupFiles",
",",
"this",
",",
"maxThreads",
")",
";",
"uploadThread",
".",
"start",
"(",
")",
";",
"}",
"}",
"/**\n * Wait to finish.\n */",
"@",
"SuppressWarnings",
"(",
"\"",
"rawtypes",
"\"",
")",
"public",
"boolean",
"waitToFinish",
"(",
"List",
"<",
"Future",
">",
"tasks",
")",
"{",
"for",
"(",
"Future",
"task",
":",
"tasks",
")",
"{",
"try",
"{",
"task",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"finally",
"{",
"task",
".",
"cancel",
"(",
"Boolean",
".",
"FALSE",
")",
";",
"}",
"}",
"tasks",
".",
"clear",
"(",
")",
";",
"tasks",
"=",
"null",
";",
"return",
"Boolean",
".",
"TRUE",
";",
"}",
"/**\n * Upload a single partition. This deletes the local backing-file, and re-opens it to create a new\n * one.\n * \n * @param closingUpload is this the final upload of an upload\n * @throws IOException on IO problems\n */",
"private",
"void",
"partUpload",
"(",
"final",
"File",
"backupFile",
",",
"final",
"int",
"partNumber",
")",
"throws",
"IOException",
"{",
"if",
"(",
"partUpload",
"&&",
"backupFile",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"SwiftUtils",
".",
"debug",
"(",
"LOG",
",",
"\"",
"skipping upload of 0 byte final partition",
"\"",
")",
";",
"}",
"else",
"{",
"boolean",
"uploadSuccess",
"=",
"false",
";",
"int",
"attempt",
"=",
"0",
";",
"while",
"(",
"!",
"uploadSuccess",
")",
"{",
"try",
"{",
"bytesUploaded",
".",
"addAndGet",
"(",
"uploadFilePartAttempt",
"(",
"attempt",
"++",
",",
"backupFile",
",",
"partNumber",
")",
")",
";",
"uploadSuccess",
"=",
"true",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Upload failed ",
"\"",
"+",
"e",
",",
"e",
")",
";",
"if",
"(",
"attempt",
">",
"ATTEMPT_LIMIT",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"}",
"}",
"}",
"private",
"long",
"uploadFilePartAttempt",
"(",
"final",
"int",
"attempt",
",",
"final",
"File",
"backupFile",
",",
"final",
"int",
"partNumber",
")",
"throws",
"IOException",
"{",
"long",
"uploadLen",
"=",
"backupFile",
".",
"length",
"(",
")",
";",
"BufferedInputStream",
"inputStream",
"=",
"null",
";",
"FileInputStream",
"input",
"=",
"null",
";",
"try",
"{",
"input",
"=",
"new",
"FileInputStream",
"(",
"backupFile",
")",
";",
"inputStream",
"=",
"new",
"BufferedInputStream",
"(",
"input",
")",
";",
"nativeStore",
".",
"uploadFilePart",
"(",
"new",
"Path",
"(",
"key",
")",
",",
"partNumber",
",",
"input",
",",
"uploadLen",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"e",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"inputStream",
")",
";",
"IOUtils",
".",
"closeQuietly",
"(",
"input",
")",
";",
"backupFile",
".",
"delete",
"(",
")",
";",
"}",
"return",
"uploadLen",
";",
"}",
"/**\n * Get the file partition size.\n * \n * @return the partition size\n */",
"@",
"Override",
"public",
"long",
"getFilePartSize",
"(",
")",
"{",
"return",
"filePartSize",
";",
"}",
"/**\n * Query the number of partitions written This is intended for testing.\n * \n * @return the of partitions already written to the remote FS\n */",
"@",
"Override",
"public",
"synchronized",
"int",
"getPartitionsWritten",
"(",
")",
"{",
"return",
"partNumber",
".",
"get",
"(",
")",
"-",
"2",
";",
"}",
"/**\n * Get the number of bytes written to the output stream. This should always be less than or equal\n * to bytesUploaded.\n * \n * @return the number of bytes written to this stream\n */",
"@",
"Override",
"public",
"long",
"getBytesWritten",
"(",
")",
"{",
"return",
"bytesWritten",
";",
"}",
"/**\n * Get the number of bytes uploaded to remote Swift cluster. bytesUploaded -bytesWritten = the\n * number of bytes left to upload.\n * \n * @return the number of bytes written to the remote endpoint\n */",
"@",
"Override",
"public",
"synchronized",
"long",
"getBytesUploaded",
"(",
")",
"{",
"return",
"bytesUploaded",
".",
"get",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"\"",
"SwiftNativeOutputStreamMultipartWithSplit{",
"\"",
"+",
"\"",
", key='",
"\"",
"+",
"key",
"+",
"'\\''",
"+",
"\"",
", closed=",
"\"",
"+",
"closed",
"+",
"\"",
", filePartSize=",
"\"",
"+",
"filePartSize",
"+",
"\"",
", blockOffset=",
"\"",
"+",
"blockOffset",
"+",
"\"",
", partUpload=",
"\"",
"+",
"partUpload",
"+",
"\"",
", nativeStore=",
"\"",
"+",
"nativeStore",
"+",
"\"",
", bytesWritten=",
"\"",
"+",
"bytesWritten",
"+",
"\"",
", bytesUploaded=",
"\"",
"+",
"bytesUploaded",
"+",
"'}'",
";",
"}",
"}"
] | Output stream, buffers data on local disk. | [
"Output",
"stream",
"buffers",
"data",
"on",
"local",
"disk",
"."
] | [
"// uploadParts();",
"// this.cleanUploadThread();",
"// Quiet",
"// Wait write to finish",
"// for (final BackupFile file : backupFiles) {",
"// delete(file.getUploadFile());",
"// }",
"// insert to a one byte array",
"// then delegate to the array writing routine",
"// validate args",
"// validate the output stream",
"// Don't have to close backupStream here.",
"// skipping the upload if",
"// - it is close time",
"// - the final partition is 0 bytes long",
"// - one part has already been written",
"// delete(backupFile);"
] | [
{
"param": "SwiftOutputStream",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "SwiftOutputStream",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fea8fe1ac3b5f5bd6e377c06f42c1e9bfab291ee | oeg-upm/geo.linkeddata.es-TripleGeoKettle | src/plugin/tripleGEOStepDialog.java | [
"Apache-2.0"
] | Java | tripleGEOStepDialog | /**
* This interface is used to launch Step Dialogs. All dialogs that implement this simple interface
* can be opened by Spoon.
* http://javadoc.pentaho.com/kettle/org/pentaho/di/trans/step/StepDialogInterface.html
*
* @author Rosangelis Garcia
* Last modified by: Rosangelis Garcia, 10/01/2016
*/ | This interface is used to launch Step Dialogs. All dialogs that implement this simple interface
can be opened by Spoon.
@author Rosangelis Garcia
Last modified by: Rosangelis Garcia, 10/01/2016 | [
"This",
"interface",
"is",
"used",
"to",
"launch",
"Step",
"Dialogs",
".",
"All",
"dialogs",
"that",
"implement",
"this",
"simple",
"interface",
"can",
"be",
"opened",
"by",
"Spoon",
".",
"@author",
"Rosangelis",
"Garcia",
"Last",
"modified",
"by",
":",
"Rosangelis",
"Garcia",
"10",
"/",
"01",
"/",
"2016"
] | public class tripleGEOStepDialog extends BaseStepDialog implements StepDialogInterface {
private static String PKG = tripleGEOStepDialog.class.getPackage().getName();
private tripleGEOStepMeta input;
private Label wlAttributeName;
private Text wAttributeName;
private FormData fdlAttributeName;
private FormData fdAttributeName;
private Label wlFeature;
private Text wFeature;
private FormData fdlFeature;
private FormData fdFeature;
private Label wlOntologyNS;
private Text wOntologyNS;
private FormData fdlOntologyNS;
private FormData fdOntologyNS;
private Label wlOntologyNSPrefix;
private Text wOntologyNSPrefix;
private FormData fdlOntologyNSPrefix;
private FormData fdOntologyNSPrefix;
private Label wlResourceNS;
private Text wResourceNS;
private FormData fdlResourceNS;
private FormData fdResourceNS;
private Label wlResourceNSPrefix;
private Text wResourceNSPrefix;
private FormData fdlResourceNSPrefix;
private FormData fdResourceNSPrefix;
private Label wlLanguage;
private Text wLanguage;
private FormData fdlLanguage;
private FormData fdLanguage;
private Label wlPathCSV;
private Text wPathCSV;
private FormData fdlPathCSV;
private FormData fdPathCSV;
private Button wbbPathCSV;
private Label wluuids;
private Button wuuids;
private FormData fdluuids;
private FormData fduuids;
private TableView wFields;
private FormData fdFields;
private Label wlColumns;
private TableView wColumns;
private FormData fdlColumns;
private FormData fdColumns;
private CTabFolder wTabFolder;
private FormData fdTabFolder;
private Button wRestartFields;
private Listener lsRestartFields;
private CTabItem wMainTab;
private TransMeta trans;
/**
* Instantiates a new base step dialog.
* @param parent - the parent shell
* @param baseStepMeta - the associated base step metadata
* @param transMeta - the associated transformation metadata
* @param stepname - the step name
*/
public tripleGEOStepDialog(Shell parent, Object in, TransMeta transMeta, String sname) {
super(parent, (BaseStepMeta)in, transMeta, sname);
this.input = ((tripleGEOStepMeta)in);
this.trans = transMeta;
}
/**
* Opens a step dialog window.
* @return the (potentially new) name of the step
*/
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
this.shell = new Shell(parent, 3312);
this.props.setLook(this.shell);
setShellImage(this.shell, this.input);
ModifyListener lsMod = new ModifyListener() {
public void modifyText(ModifyEvent e){ tripleGEOStepDialog.this.input.setChanged(); }
};
this.changed = this.input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = 5;
formLayout.marginHeight = 5;
this.shell.setLayout(formLayout);
this.shell.setText(BaseMessages.getString(PKG, "tripleGEOStepDialog.Shell.Title"));
int middle = this.props.getMiddlePct();
int margin = 4;
// STEPNAME
this.wlStepname = new Label(this.shell, 131072);
this.wlStepname.setText(BaseMessages.getString(PKG, "System.Label.StepName"));
this.props.setLook(this.wlStepname);
this.fdlStepname = new FormData();
this.fdlStepname.left = new FormAttachment(0, 0);
this.fdlStepname.right = new FormAttachment(middle, -margin);
this.fdlStepname.top = new FormAttachment(0, margin);
this.wlStepname.setLayoutData(this.fdlStepname);
this.wStepname = new Text(this.shell, 18436);
this.wStepname.setText(this.stepname);
this.props.setLook(this.wStepname);
this.wStepname.addModifyListener(lsMod);
this.fdStepname = new FormData();
this.fdStepname.left = new FormAttachment(middle, 0);
this.fdStepname.top = new FormAttachment(0, margin);
this.fdStepname.right = new FormAttachment(100, 0);
this.wStepname.setLayoutData(this.fdStepname);
// TAB FOLDER
this.wTabFolder = new CTabFolder(this.shell, 2048);
this.props.setLook(this.wTabFolder, 5);
this.fdTabFolder = new FormData();
this.fdTabFolder.left = new FormAttachment(0, 0);
this.fdTabFolder.top = new FormAttachment(this.wStepname, 4 * margin);
this.fdTabFolder.right = new FormAttachment(100, 0);
this.fdTabFolder.bottom = new FormAttachment(100, -50);
this.wTabFolder.setLayoutData(this.fdTabFolder);
this.wMainTab = new CTabItem(this.wTabFolder, 0);
this.wMainTab.setText(BaseMessages.getString(PKG, "tripleGEOStepDialog.Tab.MainTab"));
Composite cData = new Composite(this.wTabFolder, 0);
cData.setBackground(this.shell.getDisplay().getSystemColor(1));
FormLayout formLayout2 = new FormLayout();
formLayout2.marginWidth = this.wTabFolder.marginWidth;
formLayout2.marginHeight = this.wTabFolder.marginHeight;
cData.setLayout(formLayout2);
this.wMainTab.setControl(cData);
this.wTabFolder.setSelection(0);
// ATTRIBUTE NAME
this.wlAttributeName = new Label(cData, 131072);
this.wlAttributeName.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.AttributeName.Label"));
this.props.setLook(this.wlAttributeName);
this.fdlAttributeName = new FormData();
this.fdlAttributeName.left = new FormAttachment(0, 0);
this.fdlAttributeName.right = new FormAttachment(middle, -margin);
this.fdlAttributeName.top = new FormAttachment(0, margin);
this.wlAttributeName.setLayoutData(this.fdlAttributeName);
this.wAttributeName = new Text(cData, 18436);
this.props.setLook(this.wAttributeName);
this.wAttributeName.addModifyListener(lsMod);
this.fdAttributeName = new FormData();
this.fdAttributeName.left = new FormAttachment(middle, 0);
this.fdAttributeName.right = new FormAttachment(100, -margin);
this.fdAttributeName.top = new FormAttachment(0, margin);
this.wAttributeName.setLayoutData(this.fdAttributeName);
// FEATURE
this.wlFeature = new Label(cData, 131072);
this.wlFeature.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.Feature.Label"));
this.props.setLook(this.wlFeature);
this.fdlFeature = new FormData();
this.fdlFeature.left = new FormAttachment(0, 0);
this.fdlFeature.right = new FormAttachment(middle, -margin);
this.fdlFeature.top = new FormAttachment(this.wAttributeName, margin);
this.wlFeature.setLayoutData(this.fdlFeature);
this.wFeature = new Text(cData, 18436);
this.props.setLook(this.wFeature);
this.wFeature.addModifyListener(lsMod);
this.fdFeature = new FormData();
this.fdFeature.left = new FormAttachment(middle, 0);
this.fdFeature.right = new FormAttachment(100, -margin);
this.fdFeature.top = new FormAttachment(this.wAttributeName, margin);
this.wFeature.setLayoutData(this.fdFeature);
// ONTOLOGY NAMESPACE
this.wlOntologyNS = new Label(cData, 131072);
this.wlOntologyNS.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.OntologyNS.Label"));
this.props.setLook(this.wlOntologyNS);
this.fdlOntologyNS = new FormData();
this.fdlOntologyNS.left = new FormAttachment(0, 0);
this.fdlOntologyNS.right = new FormAttachment(middle, -margin);
this.fdlOntologyNS.top = new FormAttachment(this.wFeature, margin);
this.wlOntologyNS.setLayoutData(this.fdlOntologyNS);
this.wOntologyNS = new Text(cData, 18436);
this.props.setLook(this.wOntologyNS);
this.wOntologyNS.addModifyListener(lsMod);
this.fdOntologyNS = new FormData();
this.fdOntologyNS.left = new FormAttachment(middle, 0);
this.fdOntologyNS.right = new FormAttachment(100, -margin);
this.fdOntologyNS.top = new FormAttachment(this.wFeature, margin);
this.wOntologyNS.setLayoutData(this.fdOntologyNS);
// ONTOLOGY NAMESPACE PREFIX
this.wlOntologyNSPrefix = new Label(cData, 131072);
this.wlOntologyNSPrefix.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.OntologyNSPrefix.Label"));
this.props.setLook(this.wlOntologyNSPrefix);
this.fdlOntologyNSPrefix = new FormData();
this.fdlOntologyNSPrefix.left = new FormAttachment(0, 0);
this.fdlOntologyNSPrefix.right = new FormAttachment(middle, -margin);
this.fdlOntologyNSPrefix.top = new FormAttachment(this.wOntologyNS, margin);
this.wlOntologyNSPrefix.setLayoutData(this.fdlOntologyNSPrefix);
this.wOntologyNSPrefix = new Text(cData, 18436);
this.props.setLook(this.wOntologyNSPrefix);
this.wOntologyNSPrefix.addModifyListener(lsMod);
this.fdOntologyNSPrefix = new FormData();
this.fdOntologyNSPrefix.left = new FormAttachment(middle, 0);
this.fdOntologyNSPrefix.right = new FormAttachment(100, -margin);
this.fdOntologyNSPrefix.top = new FormAttachment(this.wOntologyNS, margin);
this.wOntologyNSPrefix.setLayoutData(this.fdOntologyNSPrefix);
// RESOURCE NAMESPACE
this.wlResourceNS = new Label(cData, 131072);
this.wlResourceNS.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.ResourceNS.Label"));
this.props.setLook(this.wlResourceNS);
this.fdlResourceNS = new FormData();
this.fdlResourceNS.left = new FormAttachment(0, 0);
this.fdlResourceNS.right = new FormAttachment(middle, -margin);
this.fdlResourceNS.top = new FormAttachment(this.wOntologyNSPrefix, margin);
this.wlResourceNS.setLayoutData(this.fdlResourceNS);
this.wResourceNS = new Text(cData, 18436);
this.props.setLook(this.wResourceNS);
this.wResourceNS.addModifyListener(lsMod);
this.fdResourceNS = new FormData();
this.fdResourceNS.left = new FormAttachment(middle, 0);
this.fdResourceNS.right = new FormAttachment(100, -margin);
this.fdResourceNS.top = new FormAttachment(this.wOntologyNSPrefix, margin);
this.wResourceNS.setLayoutData(this.fdResourceNS);
// RESOURCE NAMESPACE PREFIX
this.wlResourceNSPrefix = new Label(cData, 131072);
this.wlResourceNSPrefix.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.ResourceNSPrefix.Label"));
this.props.setLook(this.wlResourceNSPrefix);
this.fdlResourceNSPrefix = new FormData();
this.fdlResourceNSPrefix.left = new FormAttachment(0, 0);
this.fdlResourceNSPrefix.right = new FormAttachment(middle, -margin);
this.fdlResourceNSPrefix.top = new FormAttachment(this.wResourceNS, margin);
this.wlResourceNSPrefix.setLayoutData(this.fdlResourceNSPrefix);
this.wResourceNSPrefix = new Text(cData, 18436);
this.props.setLook(this.wResourceNSPrefix);
this.wResourceNSPrefix.addModifyListener(lsMod);
this.fdResourceNSPrefix = new FormData();
this.fdResourceNSPrefix.left = new FormAttachment(middle, 0);
this.fdResourceNSPrefix.right = new FormAttachment(100, -margin);
this.fdResourceNSPrefix.top = new FormAttachment(this.wResourceNS, margin);
this.wResourceNSPrefix.setLayoutData(this.fdResourceNSPrefix);
// LANGUAGE
this.wlLanguage = new Label(cData, 131072);
this.wlLanguage.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.Language.Label"));
this.props.setLook(this.wlLanguage);
this.fdlLanguage = new FormData();
this.fdlLanguage.left = new FormAttachment(0, 0);
this.fdlLanguage.right = new FormAttachment(middle, -margin);
this.fdlLanguage.top = new FormAttachment(this.wResourceNSPrefix, margin);
this.wlLanguage.setLayoutData(this.fdlLanguage);
this.wLanguage = new Text(cData, 18436);
this.props.setLook(this.wLanguage);
this.wLanguage.addModifyListener(lsMod);
this.fdLanguage = new FormData();
this.fdLanguage.left = new FormAttachment(middle, 0);
this.fdLanguage.right = new FormAttachment(100, -margin);
this.fdLanguage.top = new FormAttachment(this.wResourceNSPrefix, margin);
this.wLanguage.setLayoutData(this.fdLanguage);
// PATH CSV PathCSV
this.wbbPathCSV = new Button(cData,131072);
props.setLook(this.wbbPathCSV);
this.wbbPathCSV.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.PathCSVButton.Label"));
this.wbbPathCSV.setToolTipText(BaseMessages.getString(PKG,"tripleGEOStepDialog.PathCSVButtonTooltip.Label"));
FormData fdbFilename = new FormData();
fdbFilename.top = new FormAttachment(this.wLanguage, margin);
fdbFilename.right = new FormAttachment(100, 0);
this.wbbPathCSV.setLayoutData(fdbFilename);
this.wlPathCSV = new Label(cData, 131072);
this.wlPathCSV.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.PathCSV.Label"));
this.props.setLook(this.wlPathCSV);
this.fdlPathCSV = new FormData();
this.fdlPathCSV.left = new FormAttachment(0, 0);
this.fdlPathCSV.right = new FormAttachment(middle, -margin);
this.fdlPathCSV.top = new FormAttachment(this.wLanguage, margin);
this.wlPathCSV.setLayoutData(this.fdlPathCSV);
this.wPathCSV = new Text(cData, 18436);
this.props.setLook(this.wPathCSV);
this.wPathCSV.addModifyListener(lsMod);
this.fdPathCSV = new FormData();
this.fdPathCSV.left = new FormAttachment(middle, 0);
this.fdPathCSV.right = new FormAttachment(this.wbbPathCSV, -margin);
this.fdPathCSV.top = new FormAttachment(this.wLanguage, margin);
this.wPathCSV.setLayoutData(this.fdPathCSV);
// UUIDS
this.wluuids = new Label(cData, 131072);
this.wluuids.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.uuids.Label"));
this.props.setLook(this.wluuids);
this.fdluuids = new FormData();
this.fdluuids.left = new FormAttachment(0, 0);
this.fdluuids.right = new FormAttachment(middle, -margin);
this.fdluuids.top = new FormAttachment(this.wPathCSV, margin);
this.wluuids.setLayoutData(fdluuids);
this.wuuids = new Button(cData, 32);
this.props.setLook(this.wuuids);
this.fduuids = new FormData();
this.fduuids.left = new FormAttachment(middle, 0);
this.fduuids.right = new FormAttachment(100, -margin);
this.fduuids.top = new FormAttachment(this.wPathCSV, margin);
this.wuuids.setLayoutData(fduuids);
// CHECKBOX UUIDS
Listener lsUuids = new Listener() {
public void handleEvent(Event e) {
tripleGEOStepDialog.this.input.setUuidsActive(tripleGEOStepDialog.this.wuuids.getSelection());
}
};
this.wuuids.addListener(13, lsUuids);
// FIELDS
ColumnInfo[] ciFields = new ColumnInfo[2];
ciFields[0] = new ColumnInfo(BaseMessages.getString(PKG,"tripleGEOStepDialog.otherPrefix.Label"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
ciFields[1] = new ColumnInfo(BaseMessages.getString(PKG,"tripleGEOStepDialog.other.Label"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
this.wFields = new TableView(this.transMeta, cData, SWT.BORDER
| SWT.FULL_SELECTION | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL,
ciFields, this.input.getFields() == null ? 1
: this.input.getFields().length, lsMod, this.props);
this.fdFields = new FormData();
this.fdFields.left = new FormAttachment(0, 0);
this.fdFields.top = new FormAttachment(this.wuuids, margin);
this.fdFields.right = new FormAttachment(100, 0);
this.wFields.setLayoutData(this.fdFields);
// COLUMNS
this.wlColumns = new Label(cData, 131072);
this.wlColumns.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.Columns.Label"));
this.props.setLook(this.wlColumns);
this.fdlColumns = new FormData();
this.fdlColumns.left = new FormAttachment(0, 0);
this.fdlColumns.right = new FormAttachment(middle, -margin);
this.fdlColumns.top = new FormAttachment(this.wFields, margin);
this.wlColumns.setLayoutData(fdlColumns);
ColumnInfo[] ciColumns = new ColumnInfo[4];
ciColumns[0] = new ColumnInfo(BaseMessages.getString(PKG,"tripleGEOStepDialog.ShowColumns.Label"),
2, this.input.getShow(), true);
ciColumns[1] = new ColumnInfo(BaseMessages.getString(PKG,"tripleGEOStepDialog.Column.Label"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
ciColumns[2] = new ColumnInfo(BaseMessages.getString(PKG,"tripleGEOStepDialog.otherPrefixColumns.Label"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
ciColumns[3] = new ColumnInfo(BaseMessages.getString(PKG,"tripleGEOStepDialog.otherColumns.Label"),
ColumnInfo.COLUMN_TYPE_TEXT, false);
this.wColumns = new TableView(this.transMeta, cData, SWT.BORDER | SWT.MULTI,
ciColumns, this.input.getColumns() == null ? 1
: this.input.getColumns().length, true, lsMod, this.props);
this.wColumns.setSortable(false); // Turns off sort arrows
this.fdColumns = new FormData();
this.fdColumns.left = new FormAttachment(0, 0);
this.fdColumns.top = new FormAttachment(this.wlColumns, margin);
this.fdColumns.right = new FormAttachment(100, 0);
this.wColumns.setLayoutData(this.fdColumns);
// OK - CANCEL
this.wOK = new Button(this.shell, 8);
this.wOK.setText(BaseMessages.getString(PKG,"System.Button.OK"));
this.wCancel = new Button(this.shell, 8);
this.wCancel.setText(BaseMessages.getString(PKG,"System.Button.Cancel"));
this.wRestartFields = new Button(this.shell, 8);
this.wRestartFields.setText(BaseMessages.getString(PKG,"tripleGEOStepDialog.RestartFields.Button"));
BaseStepDialog.positionBottomButtons(this.shell,
new Button[] { this.wOK, this.wRestartFields, this.wCancel }, margin, null);
this.lsCancel = new Listener(){ public void handleEvent(Event e){ tripleGEOStepDialog.this.cancel(); } };
this.lsOK = new Listener(){ public void handleEvent(Event e){tripleGEOStepDialog.this.ok(); } };
this.lsRestartFields = new Listener() {
public void handleEvent(Event e) {
tripleGEOStepDialog.this.wColumns.removeAll();
loadColumns();
}
};
this.wCancel.addListener(13, this.lsCancel);
this.wOK.addListener(13, this.lsOK);
this.wRestartFields.addListener(13, this.lsRestartFields);
this.lsDef = new SelectionAdapter(){
public void widgetDefaultSelected(SelectionEvent e) { tripleGEOStepDialog.this.ok(); }
};
this.wStepname.addSelectionListener(this.lsDef);
// Detect X or ALT-F4 or something that kills this window
this.shell.addShellListener(new ShellAdapter(){
public void shellClosed(ShellEvent e){ tripleGEOStepDialog.this.cancel(); }
});
// Listen to the browse button next to the file name
this.wbbPathCSV.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[] { "*.csv;*.CSV", "*" });
if (tripleGEOStepDialog.this.wPathCSV.getText() != null) {
dialog.setFileName(tripleGEOStepDialog.this.wPathCSV.getText());
}
dialog.setFilterNames(new String[] {"CSV files", "All files" });
if (dialog.open() != null) {
String str = dialog.getFilterPath()
+ System.getProperty("file.separator")
+ dialog.getFileName();
tripleGEOStepDialog.this.wPathCSV.setText(str);
}
}
});
// Set the shell size, based upon previous time
setSize(this.shell, 600, 600, true);
getData();
this.input.setChanged(this.changed);
this.shell.open();
while (!this.shell.isDisposed()) {
if (!display.readAndDispatch()) { display.sleep(); }
}
return this.stepname;
}
/**
* Collect data from the meta and place it in the dialog.
*/
public void getData() {
this.wStepname.selectAll();
this.wAttributeName.setText(this.input.getAttributeName());
this.wFeature.setText(this.input.getFeature());
this.wOntologyNS.setText(this.input.getOntologyNS());
this.wOntologyNSPrefix.setText(this.input.getOntologyNSPrefix());
this.wResourceNS.setText(this.input.getResourceNS());
this.wResourceNSPrefix.setText(this.input.getResourceNSPrefix());
this.wLanguage.setText(this.input.getLanguage());
this.wPathCSV.setText(this.input.getPathCSV());
this.wuuids.setSelection(this.input.isUuidsActive());
FieldDefinition[] fields = this.input.getFields();
if (fields != null) {
for (FieldDefinition field : fields) {
TableItem item = new TableItem(this.wFields.table, SWT.NONE);
int colnr = 1;
item.setText(colnr++, Const.NVL(field.prefix, Constants.empty));
item.setText(colnr++, Const.NVL(field.uri, Constants.empty));
}
}
this.wFields.removeEmptyRows();
this.wFields.setRowNums();
this.wFields.optWidth(true);
ColumnDefinition[] columns = this.input.getColumns();
if (columns != null || (columns != null && !this.trans.haveHopsChanged())) {
for (ColumnDefinition c : columns) {
TableItem item = new TableItem(this.wColumns.table, SWT.NONE);
int colnr = 1;
item.setText(colnr++, Const.NVL(c.show, "YES"));
item.setText(colnr++, Const.NVL(c.column, Constants.empty));
if (c.getColumn().equalsIgnoreCase(Constants.the_geom)){
item.setText(colnr++, "n/a");
item.setText(colnr++, "n/a");
} else {
item.setText(colnr++, Const.NVL(c.prefix, Constants.empty));
item.setText(colnr++, Const.NVL(c.uri, Constants.empty));
}
}
} else if ((columns != null && this.trans.haveHopsChanged()) || (columns == null)){
loadColumns();
}
this.wColumns.removeEmptyRows();
this.wColumns.setRowNums();
this.wColumns.optWidth(true);
}
/**
* Let the tripleGEOStepMeta know about the entered data
* @throws KettleValueException
*/
private void ok() {
this.stepname = this.wStepname.getText();
if (!isEmpty(this.wAttributeName.getText())) {
this.input.setAttributeName(this.wAttributeName.getText());
} else {
this.input.setAttributeName(this.input.getAttributeName());
}
if (!isEmpty(this.wFeature.getText())) {
this.input.setFeature(this.wFeature.getText());
} else {
this.input.setFeature(this.input.getFeature());
}
if (!isEmpty(this.wOntologyNS.getText())) {
this.input.setOntologyNS(this.wOntologyNS.getText());
} else {
this.input.setOntologyNS(this.input.getOntologyNS());
}
if (!isEmpty(this.wOntologyNSPrefix.getText())) {
this.input.setOntologyNSPrefix(this.wOntologyNSPrefix.getText());
} else {
this.input.setOntologyNSPrefix(this.input.getOntologyNSPrefix());
}
if (!isEmpty(this.wResourceNS.getText())) {
this.input.setResourceNS(this.wResourceNS.getText());
} else {
this.input.setResourceNS(this.input.getResourceNS());
}
if (!isEmpty(this.wResourceNSPrefix.getText())) {
this.input.setResourceNSPrefix(this.wResourceNSPrefix.getText());
} else {
this.input.setResourceNSPrefix(this.input.getResourceNSPrefix());
}
if (!isEmpty(this.wLanguage.getText())) {
this.input.setLanguage(this.wLanguage.getText());
} else {
this.input.setLanguage(Constants.null_);
}
if (!isEmpty(this.wPathCSV.getText())) {
String ext = FilenameUtils.getExtension(this.wPathCSV.getText());
if (ext.equalsIgnoreCase("csv")){
this.input.setPathCSV(this.wPathCSV.getText());
} else {
this.input.setPathCSV(this.input.getPathCSV());
}
} else {
this.input.setPathCSV(Constants.null_);
}
int nrNonEmptyFields = this.wFields.nrNonEmpty();
FieldDefinition[] fields = new FieldDefinition[nrNonEmptyFields];
for (int i = 0; i < nrNonEmptyFields; i++) {
TableItem item = this.wFields.getNonEmpty(i);
fields[i] = new FieldDefinition();
int colnr = 1;
fields[i].prefix = item.getText(colnr++);
fields[i].uri = item.getText(colnr++);
}
this.input.setFields(fields);
this.wFields.removeEmptyRows();
this.wFields.setRowNums();
this.wFields.optWidth(true);
int nrNonEmptyColumns = this.wColumns.nrNonEmpty();
ColumnDefinition[] columns = new ColumnDefinition[nrNonEmptyColumns];
for (int i = 0; i < nrNonEmptyColumns; i++) {
TableItem item = this.wColumns.getNonEmpty(i);
columns[i] = new ColumnDefinition();
int colnr = 1;
columns[i].show = item.getText(colnr++);
if (i == 0){
columns[i].column = "the_geom";
colnr++;
} else {
String col = item.getText(colnr++);
if (!isEmpty(col)) {
columns[i].column = col;
} else {
columns[i].column = "empty";
}
}
columns[i].prefix = item.getText(colnr++);
@SuppressWarnings("unused")
Boolean flag = true;
if (columns[i].column.equalsIgnoreCase("the_geom")){
flag = false;
} else {
flag = true;
}
String uri = item.getText(colnr++);
if (isValidURL(uri,true)){
columns[i].uri = uri;
} else {
columns[i].uri = null;
}
}
if (nrNonEmptyColumns > 0){
this.input.setColumns(columns);
if (this.input.getColumn_name() == null) {
loadColumnName();
}
int j = 0;
for (String c : this.input.getColumn_name()) {
columns[j].column_shp = c;
if (columns[j].column.equalsIgnoreCase("empty")){
columns[j].column = c;
}
j++;
}
}
this.wColumns.removeEmptyRows();
this.wColumns.setRowNums();
this.wColumns.optWidth(true);
this.input.setChanged();
dispose();
}
/**
* Cancel
*/
private void cancel() {
this.stepname = null;
this.input.setChanged(this.changed);
dispose();
}
/**
* Verifies if the string is empty
* @param string - The string
* @return true if the string is empty; otherwise, false
*/
public static boolean isEmpty(String string) {
if (string == null || string.length() == 0) {
return true;
}
for (int i = 0; i < string.length(); i++) {
if ((Character.isWhitespace(string.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
* Validate an URL
* @param url
* @return true if the url is valid; otherwise, false
*/
public boolean isValidURL(String url, Boolean flag) {
if (flag) {
URL u = null;
try {
u = new URL(url);
} catch (MalformedURLException e) {
return false;
}
try {
u.toURI();
} catch (URISyntaxException e) {
return false;
}
return true;
}
return true;
}
/**
* Load columns name in a ArrayList
*/
private void loadColumnName() {
try {
ArrayList<String> column_name = new ArrayList<String>();
if (this.trans.getPrevStepFields(this.trans.findStep(this.wStepname.getText())) != null){
RowMetaInterface rm = this.trans.getPrevStepFields(this.trans.findStep(this.wStepname.getText()));
for (ValueMetaInterface vmeta : rm.getValueMetaList()) {
column_name.add(vmeta.getName());
}
}
this.input.setColumn_name(column_name);
} catch (KettleStepException e) {
e.printStackTrace();
}
}
/**
* Load columns shapefile
*/
private void loadColumns() {
try {
ArrayList<String> column_name = new ArrayList<String>();
RowMetaInterface rm = this.trans.getPrevStepFields(this.trans.findStep(this.wStepname.getText()));
for (ValueMetaInterface vmeta : rm.getValueMetaList()) {
TableItem item = new TableItem(this.wColumns.table, 0);
item.setText(1, "YES");
item.setText(2, vmeta.getName());
if (vmeta.getName().equalsIgnoreCase(Constants.the_geom)){
item.setText(3, "n/a");
item.setText(4, "n/a");
}
column_name.add(vmeta.getName());
}
this.input.setColumn_name(column_name);
this.wColumns.removeEmptyRows();
this.wColumns.setRowNums();
this.wColumns.optWidth(true);
} catch (KettleStepException e) {
e.printStackTrace();
}
}
} | [
"public",
"class",
"tripleGEOStepDialog",
"extends",
"BaseStepDialog",
"implements",
"StepDialogInterface",
"{",
"private",
"static",
"String",
"PKG",
"=",
"tripleGEOStepDialog",
".",
"class",
".",
"getPackage",
"(",
")",
".",
"getName",
"(",
")",
";",
"private",
"tripleGEOStepMeta",
"input",
";",
"private",
"Label",
"wlAttributeName",
";",
"private",
"Text",
"wAttributeName",
";",
"private",
"FormData",
"fdlAttributeName",
";",
"private",
"FormData",
"fdAttributeName",
";",
"private",
"Label",
"wlFeature",
";",
"private",
"Text",
"wFeature",
";",
"private",
"FormData",
"fdlFeature",
";",
"private",
"FormData",
"fdFeature",
";",
"private",
"Label",
"wlOntologyNS",
";",
"private",
"Text",
"wOntologyNS",
";",
"private",
"FormData",
"fdlOntologyNS",
";",
"private",
"FormData",
"fdOntologyNS",
";",
"private",
"Label",
"wlOntologyNSPrefix",
";",
"private",
"Text",
"wOntologyNSPrefix",
";",
"private",
"FormData",
"fdlOntologyNSPrefix",
";",
"private",
"FormData",
"fdOntologyNSPrefix",
";",
"private",
"Label",
"wlResourceNS",
";",
"private",
"Text",
"wResourceNS",
";",
"private",
"FormData",
"fdlResourceNS",
";",
"private",
"FormData",
"fdResourceNS",
";",
"private",
"Label",
"wlResourceNSPrefix",
";",
"private",
"Text",
"wResourceNSPrefix",
";",
"private",
"FormData",
"fdlResourceNSPrefix",
";",
"private",
"FormData",
"fdResourceNSPrefix",
";",
"private",
"Label",
"wlLanguage",
";",
"private",
"Text",
"wLanguage",
";",
"private",
"FormData",
"fdlLanguage",
";",
"private",
"FormData",
"fdLanguage",
";",
"private",
"Label",
"wlPathCSV",
";",
"private",
"Text",
"wPathCSV",
";",
"private",
"FormData",
"fdlPathCSV",
";",
"private",
"FormData",
"fdPathCSV",
";",
"private",
"Button",
"wbbPathCSV",
";",
"private",
"Label",
"wluuids",
";",
"private",
"Button",
"wuuids",
";",
"private",
"FormData",
"fdluuids",
";",
"private",
"FormData",
"fduuids",
";",
"private",
"TableView",
"wFields",
";",
"private",
"FormData",
"fdFields",
";",
"private",
"Label",
"wlColumns",
";",
"private",
"TableView",
"wColumns",
";",
"private",
"FormData",
"fdlColumns",
";",
"private",
"FormData",
"fdColumns",
";",
"private",
"CTabFolder",
"wTabFolder",
";",
"private",
"FormData",
"fdTabFolder",
";",
"private",
"Button",
"wRestartFields",
";",
"private",
"Listener",
"lsRestartFields",
";",
"private",
"CTabItem",
"wMainTab",
";",
"private",
"TransMeta",
"trans",
";",
"/**\n\t * Instantiates a new base step dialog.\n\t * @param parent - the parent shell\n\t * @param baseStepMeta - the associated base step metadata\n\t * @param transMeta - the associated transformation metadata\n\t * @param stepname - the step name\n\t */",
"public",
"tripleGEOStepDialog",
"(",
"Shell",
"parent",
",",
"Object",
"in",
",",
"TransMeta",
"transMeta",
",",
"String",
"sname",
")",
"{",
"super",
"(",
"parent",
",",
"(",
"BaseStepMeta",
")",
"in",
",",
"transMeta",
",",
"sname",
")",
";",
"this",
".",
"input",
"=",
"(",
"(",
"tripleGEOStepMeta",
")",
"in",
")",
";",
"this",
".",
"trans",
"=",
"transMeta",
";",
"}",
"/**\n\t * Opens a step dialog window.\n\t * @return the (potentially new) name of the step\n\t */",
"public",
"String",
"open",
"(",
")",
"{",
"Shell",
"parent",
"=",
"getParent",
"(",
")",
";",
"Display",
"display",
"=",
"parent",
".",
"getDisplay",
"(",
")",
";",
"this",
".",
"shell",
"=",
"new",
"Shell",
"(",
"parent",
",",
"3312",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"shell",
")",
";",
"setShellImage",
"(",
"this",
".",
"shell",
",",
"this",
".",
"input",
")",
";",
"ModifyListener",
"lsMod",
"=",
"new",
"ModifyListener",
"(",
")",
"{",
"public",
"void",
"modifyText",
"(",
"ModifyEvent",
"e",
")",
"{",
"tripleGEOStepDialog",
".",
"this",
".",
"input",
".",
"setChanged",
"(",
")",
";",
"}",
"}",
";",
"this",
".",
"changed",
"=",
"this",
".",
"input",
".",
"hasChanged",
"(",
")",
";",
"FormLayout",
"formLayout",
"=",
"new",
"FormLayout",
"(",
")",
";",
"formLayout",
".",
"marginWidth",
"=",
"5",
";",
"formLayout",
".",
"marginHeight",
"=",
"5",
";",
"this",
".",
"shell",
".",
"setLayout",
"(",
"formLayout",
")",
";",
"this",
".",
"shell",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.Shell.Title",
"\"",
")",
")",
";",
"int",
"middle",
"=",
"this",
".",
"props",
".",
"getMiddlePct",
"(",
")",
";",
"int",
"margin",
"=",
"4",
";",
"this",
".",
"wlStepname",
"=",
"new",
"Label",
"(",
"this",
".",
"shell",
",",
"131072",
")",
";",
"this",
".",
"wlStepname",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"System.Label.StepName",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlStepname",
")",
";",
"this",
".",
"fdlStepname",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlStepname",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlStepname",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlStepname",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"margin",
")",
";",
"this",
".",
"wlStepname",
".",
"setLayoutData",
"(",
"this",
".",
"fdlStepname",
")",
";",
"this",
".",
"wStepname",
"=",
"new",
"Text",
"(",
"this",
".",
"shell",
",",
"18436",
")",
";",
"this",
".",
"wStepname",
".",
"setText",
"(",
"this",
".",
"stepname",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wStepname",
")",
";",
"this",
".",
"wStepname",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdStepname",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdStepname",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdStepname",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"margin",
")",
";",
"this",
".",
"fdStepname",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"0",
")",
";",
"this",
".",
"wStepname",
".",
"setLayoutData",
"(",
"this",
".",
"fdStepname",
")",
";",
"this",
".",
"wTabFolder",
"=",
"new",
"CTabFolder",
"(",
"this",
".",
"shell",
",",
"2048",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wTabFolder",
",",
"5",
")",
";",
"this",
".",
"fdTabFolder",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdTabFolder",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdTabFolder",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wStepname",
",",
"4",
"*",
"margin",
")",
";",
"this",
".",
"fdTabFolder",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"0",
")",
";",
"this",
".",
"fdTabFolder",
".",
"bottom",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"50",
")",
";",
"this",
".",
"wTabFolder",
".",
"setLayoutData",
"(",
"this",
".",
"fdTabFolder",
")",
";",
"this",
".",
"wMainTab",
"=",
"new",
"CTabItem",
"(",
"this",
".",
"wTabFolder",
",",
"0",
")",
";",
"this",
".",
"wMainTab",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.Tab.MainTab",
"\"",
")",
")",
";",
"Composite",
"cData",
"=",
"new",
"Composite",
"(",
"this",
".",
"wTabFolder",
",",
"0",
")",
";",
"cData",
".",
"setBackground",
"(",
"this",
".",
"shell",
".",
"getDisplay",
"(",
")",
".",
"getSystemColor",
"(",
"1",
")",
")",
";",
"FormLayout",
"formLayout2",
"=",
"new",
"FormLayout",
"(",
")",
";",
"formLayout2",
".",
"marginWidth",
"=",
"this",
".",
"wTabFolder",
".",
"marginWidth",
";",
"formLayout2",
".",
"marginHeight",
"=",
"this",
".",
"wTabFolder",
".",
"marginHeight",
";",
"cData",
".",
"setLayout",
"(",
"formLayout2",
")",
";",
"this",
".",
"wMainTab",
".",
"setControl",
"(",
"cData",
")",
";",
"this",
".",
"wTabFolder",
".",
"setSelection",
"(",
"0",
")",
";",
"this",
".",
"wlAttributeName",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlAttributeName",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.AttributeName.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlAttributeName",
")",
";",
"this",
".",
"fdlAttributeName",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlAttributeName",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlAttributeName",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlAttributeName",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"margin",
")",
";",
"this",
".",
"wlAttributeName",
".",
"setLayoutData",
"(",
"this",
".",
"fdlAttributeName",
")",
";",
"this",
".",
"wAttributeName",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wAttributeName",
")",
";",
"this",
".",
"wAttributeName",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdAttributeName",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdAttributeName",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdAttributeName",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdAttributeName",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"margin",
")",
";",
"this",
".",
"wAttributeName",
".",
"setLayoutData",
"(",
"this",
".",
"fdAttributeName",
")",
";",
"this",
".",
"wlFeature",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlFeature",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.Feature.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlFeature",
")",
";",
"this",
".",
"fdlFeature",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlFeature",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlFeature",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlFeature",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wAttributeName",
",",
"margin",
")",
";",
"this",
".",
"wlFeature",
".",
"setLayoutData",
"(",
"this",
".",
"fdlFeature",
")",
";",
"this",
".",
"wFeature",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wFeature",
")",
";",
"this",
".",
"wFeature",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdFeature",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdFeature",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdFeature",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdFeature",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wAttributeName",
",",
"margin",
")",
";",
"this",
".",
"wFeature",
".",
"setLayoutData",
"(",
"this",
".",
"fdFeature",
")",
";",
"this",
".",
"wlOntologyNS",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlOntologyNS",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.OntologyNS.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlOntologyNS",
")",
";",
"this",
".",
"fdlOntologyNS",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlOntologyNS",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlOntologyNS",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlOntologyNS",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wFeature",
",",
"margin",
")",
";",
"this",
".",
"wlOntologyNS",
".",
"setLayoutData",
"(",
"this",
".",
"fdlOntologyNS",
")",
";",
"this",
".",
"wOntologyNS",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wOntologyNS",
")",
";",
"this",
".",
"wOntologyNS",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdOntologyNS",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdOntologyNS",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdOntologyNS",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdOntologyNS",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wFeature",
",",
"margin",
")",
";",
"this",
".",
"wOntologyNS",
".",
"setLayoutData",
"(",
"this",
".",
"fdOntologyNS",
")",
";",
"this",
".",
"wlOntologyNSPrefix",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlOntologyNSPrefix",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.OntologyNSPrefix.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlOntologyNSPrefix",
")",
";",
"this",
".",
"fdlOntologyNSPrefix",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlOntologyNSPrefix",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlOntologyNSPrefix",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlOntologyNSPrefix",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wOntologyNS",
",",
"margin",
")",
";",
"this",
".",
"wlOntologyNSPrefix",
".",
"setLayoutData",
"(",
"this",
".",
"fdlOntologyNSPrefix",
")",
";",
"this",
".",
"wOntologyNSPrefix",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wOntologyNSPrefix",
")",
";",
"this",
".",
"wOntologyNSPrefix",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdOntologyNSPrefix",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdOntologyNSPrefix",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdOntologyNSPrefix",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdOntologyNSPrefix",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wOntologyNS",
",",
"margin",
")",
";",
"this",
".",
"wOntologyNSPrefix",
".",
"setLayoutData",
"(",
"this",
".",
"fdOntologyNSPrefix",
")",
";",
"this",
".",
"wlResourceNS",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlResourceNS",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.ResourceNS.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlResourceNS",
")",
";",
"this",
".",
"fdlResourceNS",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlResourceNS",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlResourceNS",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlResourceNS",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wOntologyNSPrefix",
",",
"margin",
")",
";",
"this",
".",
"wlResourceNS",
".",
"setLayoutData",
"(",
"this",
".",
"fdlResourceNS",
")",
";",
"this",
".",
"wResourceNS",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wResourceNS",
")",
";",
"this",
".",
"wResourceNS",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdResourceNS",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdResourceNS",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdResourceNS",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdResourceNS",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wOntologyNSPrefix",
",",
"margin",
")",
";",
"this",
".",
"wResourceNS",
".",
"setLayoutData",
"(",
"this",
".",
"fdResourceNS",
")",
";",
"this",
".",
"wlResourceNSPrefix",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlResourceNSPrefix",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.ResourceNSPrefix.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlResourceNSPrefix",
")",
";",
"this",
".",
"fdlResourceNSPrefix",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlResourceNSPrefix",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlResourceNSPrefix",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlResourceNSPrefix",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wResourceNS",
",",
"margin",
")",
";",
"this",
".",
"wlResourceNSPrefix",
".",
"setLayoutData",
"(",
"this",
".",
"fdlResourceNSPrefix",
")",
";",
"this",
".",
"wResourceNSPrefix",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wResourceNSPrefix",
")",
";",
"this",
".",
"wResourceNSPrefix",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdResourceNSPrefix",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdResourceNSPrefix",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdResourceNSPrefix",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdResourceNSPrefix",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wResourceNS",
",",
"margin",
")",
";",
"this",
".",
"wResourceNSPrefix",
".",
"setLayoutData",
"(",
"this",
".",
"fdResourceNSPrefix",
")",
";",
"this",
".",
"wlLanguage",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlLanguage",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.Language.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlLanguage",
")",
";",
"this",
".",
"fdlLanguage",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlLanguage",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlLanguage",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlLanguage",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wResourceNSPrefix",
",",
"margin",
")",
";",
"this",
".",
"wlLanguage",
".",
"setLayoutData",
"(",
"this",
".",
"fdlLanguage",
")",
";",
"this",
".",
"wLanguage",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wLanguage",
")",
";",
"this",
".",
"wLanguage",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdLanguage",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdLanguage",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdLanguage",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdLanguage",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wResourceNSPrefix",
",",
"margin",
")",
";",
"this",
".",
"wLanguage",
".",
"setLayoutData",
"(",
"this",
".",
"fdLanguage",
")",
";",
"this",
".",
"wbbPathCSV",
"=",
"new",
"Button",
"(",
"cData",
",",
"131072",
")",
";",
"props",
".",
"setLook",
"(",
"this",
".",
"wbbPathCSV",
")",
";",
"this",
".",
"wbbPathCSV",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.PathCSVButton.Label",
"\"",
")",
")",
";",
"this",
".",
"wbbPathCSV",
".",
"setToolTipText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.PathCSVButtonTooltip.Label",
"\"",
")",
")",
";",
"FormData",
"fdbFilename",
"=",
"new",
"FormData",
"(",
")",
";",
"fdbFilename",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wLanguage",
",",
"margin",
")",
";",
"fdbFilename",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"0",
")",
";",
"this",
".",
"wbbPathCSV",
".",
"setLayoutData",
"(",
"fdbFilename",
")",
";",
"this",
".",
"wlPathCSV",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlPathCSV",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.PathCSV.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlPathCSV",
")",
";",
"this",
".",
"fdlPathCSV",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlPathCSV",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlPathCSV",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlPathCSV",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wLanguage",
",",
"margin",
")",
";",
"this",
".",
"wlPathCSV",
".",
"setLayoutData",
"(",
"this",
".",
"fdlPathCSV",
")",
";",
"this",
".",
"wPathCSV",
"=",
"new",
"Text",
"(",
"cData",
",",
"18436",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wPathCSV",
")",
";",
"this",
".",
"wPathCSV",
".",
"addModifyListener",
"(",
"lsMod",
")",
";",
"this",
".",
"fdPathCSV",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdPathCSV",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fdPathCSV",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wbbPathCSV",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdPathCSV",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wLanguage",
",",
"margin",
")",
";",
"this",
".",
"wPathCSV",
".",
"setLayoutData",
"(",
"this",
".",
"fdPathCSV",
")",
";",
"this",
".",
"wluuids",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wluuids",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.uuids.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wluuids",
")",
";",
"this",
".",
"fdluuids",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdluuids",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdluuids",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdluuids",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wPathCSV",
",",
"margin",
")",
";",
"this",
".",
"wluuids",
".",
"setLayoutData",
"(",
"fdluuids",
")",
";",
"this",
".",
"wuuids",
"=",
"new",
"Button",
"(",
"cData",
",",
"32",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wuuids",
")",
";",
"this",
".",
"fduuids",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fduuids",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"0",
")",
";",
"this",
".",
"fduuids",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"-",
"margin",
")",
";",
"this",
".",
"fduuids",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wPathCSV",
",",
"margin",
")",
";",
"this",
".",
"wuuids",
".",
"setLayoutData",
"(",
"fduuids",
")",
";",
"Listener",
"lsUuids",
"=",
"new",
"Listener",
"(",
")",
"{",
"public",
"void",
"handleEvent",
"(",
"Event",
"e",
")",
"{",
"tripleGEOStepDialog",
".",
"this",
".",
"input",
".",
"setUuidsActive",
"(",
"tripleGEOStepDialog",
".",
"this",
".",
"wuuids",
".",
"getSelection",
"(",
")",
")",
";",
"}",
"}",
";",
"this",
".",
"wuuids",
".",
"addListener",
"(",
"13",
",",
"lsUuids",
")",
";",
"ColumnInfo",
"[",
"]",
"ciFields",
"=",
"new",
"ColumnInfo",
"[",
"2",
"]",
";",
"ciFields",
"[",
"0",
"]",
"=",
"new",
"ColumnInfo",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.otherPrefix.Label",
"\"",
")",
",",
"ColumnInfo",
".",
"COLUMN_TYPE_TEXT",
",",
"false",
")",
";",
"ciFields",
"[",
"1",
"]",
"=",
"new",
"ColumnInfo",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.other.Label",
"\"",
")",
",",
"ColumnInfo",
".",
"COLUMN_TYPE_TEXT",
",",
"false",
")",
";",
"this",
".",
"wFields",
"=",
"new",
"TableView",
"(",
"this",
".",
"transMeta",
",",
"cData",
",",
"SWT",
".",
"BORDER",
"|",
"SWT",
".",
"FULL_SELECTION",
"|",
"SWT",
".",
"MULTI",
"|",
"SWT",
".",
"V_SCROLL",
"|",
"SWT",
".",
"H_SCROLL",
",",
"ciFields",
",",
"this",
".",
"input",
".",
"getFields",
"(",
")",
"==",
"null",
"?",
"1",
":",
"this",
".",
"input",
".",
"getFields",
"(",
")",
".",
"length",
",",
"lsMod",
",",
"this",
".",
"props",
")",
";",
"this",
".",
"fdFields",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdFields",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdFields",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wuuids",
",",
"margin",
")",
";",
"this",
".",
"fdFields",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"0",
")",
";",
"this",
".",
"wFields",
".",
"setLayoutData",
"(",
"this",
".",
"fdFields",
")",
";",
"this",
".",
"wlColumns",
"=",
"new",
"Label",
"(",
"cData",
",",
"131072",
")",
";",
"this",
".",
"wlColumns",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.Columns.Label",
"\"",
")",
")",
";",
"this",
".",
"props",
".",
"setLook",
"(",
"this",
".",
"wlColumns",
")",
";",
"this",
".",
"fdlColumns",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdlColumns",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdlColumns",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"middle",
",",
"-",
"margin",
")",
";",
"this",
".",
"fdlColumns",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wFields",
",",
"margin",
")",
";",
"this",
".",
"wlColumns",
".",
"setLayoutData",
"(",
"fdlColumns",
")",
";",
"ColumnInfo",
"[",
"]",
"ciColumns",
"=",
"new",
"ColumnInfo",
"[",
"4",
"]",
";",
"ciColumns",
"[",
"0",
"]",
"=",
"new",
"ColumnInfo",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.ShowColumns.Label",
"\"",
")",
",",
"2",
",",
"this",
".",
"input",
".",
"getShow",
"(",
")",
",",
"true",
")",
";",
"ciColumns",
"[",
"1",
"]",
"=",
"new",
"ColumnInfo",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.Column.Label",
"\"",
")",
",",
"ColumnInfo",
".",
"COLUMN_TYPE_TEXT",
",",
"false",
")",
";",
"ciColumns",
"[",
"2",
"]",
"=",
"new",
"ColumnInfo",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.otherPrefixColumns.Label",
"\"",
")",
",",
"ColumnInfo",
".",
"COLUMN_TYPE_TEXT",
",",
"false",
")",
";",
"ciColumns",
"[",
"3",
"]",
"=",
"new",
"ColumnInfo",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.otherColumns.Label",
"\"",
")",
",",
"ColumnInfo",
".",
"COLUMN_TYPE_TEXT",
",",
"false",
")",
";",
"this",
".",
"wColumns",
"=",
"new",
"TableView",
"(",
"this",
".",
"transMeta",
",",
"cData",
",",
"SWT",
".",
"BORDER",
"|",
"SWT",
".",
"MULTI",
",",
"ciColumns",
",",
"this",
".",
"input",
".",
"getColumns",
"(",
")",
"==",
"null",
"?",
"1",
":",
"this",
".",
"input",
".",
"getColumns",
"(",
")",
".",
"length",
",",
"true",
",",
"lsMod",
",",
"this",
".",
"props",
")",
";",
"this",
".",
"wColumns",
".",
"setSortable",
"(",
"false",
")",
";",
"this",
".",
"fdColumns",
"=",
"new",
"FormData",
"(",
")",
";",
"this",
".",
"fdColumns",
".",
"left",
"=",
"new",
"FormAttachment",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"fdColumns",
".",
"top",
"=",
"new",
"FormAttachment",
"(",
"this",
".",
"wlColumns",
",",
"margin",
")",
";",
"this",
".",
"fdColumns",
".",
"right",
"=",
"new",
"FormAttachment",
"(",
"100",
",",
"0",
")",
";",
"this",
".",
"wColumns",
".",
"setLayoutData",
"(",
"this",
".",
"fdColumns",
")",
";",
"this",
".",
"wOK",
"=",
"new",
"Button",
"(",
"this",
".",
"shell",
",",
"8",
")",
";",
"this",
".",
"wOK",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"System.Button.OK",
"\"",
")",
")",
";",
"this",
".",
"wCancel",
"=",
"new",
"Button",
"(",
"this",
".",
"shell",
",",
"8",
")",
";",
"this",
".",
"wCancel",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"System.Button.Cancel",
"\"",
")",
")",
";",
"this",
".",
"wRestartFields",
"=",
"new",
"Button",
"(",
"this",
".",
"shell",
",",
"8",
")",
";",
"this",
".",
"wRestartFields",
".",
"setText",
"(",
"BaseMessages",
".",
"getString",
"(",
"PKG",
",",
"\"",
"tripleGEOStepDialog.RestartFields.Button",
"\"",
")",
")",
";",
"BaseStepDialog",
".",
"positionBottomButtons",
"(",
"this",
".",
"shell",
",",
"new",
"Button",
"[",
"]",
"{",
"this",
".",
"wOK",
",",
"this",
".",
"wRestartFields",
",",
"this",
".",
"wCancel",
"}",
",",
"margin",
",",
"null",
")",
";",
"this",
".",
"lsCancel",
"=",
"new",
"Listener",
"(",
")",
"{",
"public",
"void",
"handleEvent",
"(",
"Event",
"e",
")",
"{",
"tripleGEOStepDialog",
".",
"this",
".",
"cancel",
"(",
")",
";",
"}",
"}",
";",
"this",
".",
"lsOK",
"=",
"new",
"Listener",
"(",
")",
"{",
"public",
"void",
"handleEvent",
"(",
"Event",
"e",
")",
"{",
"tripleGEOStepDialog",
".",
"this",
".",
"ok",
"(",
")",
";",
"}",
"}",
";",
"this",
".",
"lsRestartFields",
"=",
"new",
"Listener",
"(",
")",
"{",
"public",
"void",
"handleEvent",
"(",
"Event",
"e",
")",
"{",
"tripleGEOStepDialog",
".",
"this",
".",
"wColumns",
".",
"removeAll",
"(",
")",
";",
"loadColumns",
"(",
")",
";",
"}",
"}",
";",
"this",
".",
"wCancel",
".",
"addListener",
"(",
"13",
",",
"this",
".",
"lsCancel",
")",
";",
"this",
".",
"wOK",
".",
"addListener",
"(",
"13",
",",
"this",
".",
"lsOK",
")",
";",
"this",
".",
"wRestartFields",
".",
"addListener",
"(",
"13",
",",
"this",
".",
"lsRestartFields",
")",
";",
"this",
".",
"lsDef",
"=",
"new",
"SelectionAdapter",
"(",
")",
"{",
"public",
"void",
"widgetDefaultSelected",
"(",
"SelectionEvent",
"e",
")",
"{",
"tripleGEOStepDialog",
".",
"this",
".",
"ok",
"(",
")",
";",
"}",
"}",
";",
"this",
".",
"wStepname",
".",
"addSelectionListener",
"(",
"this",
".",
"lsDef",
")",
";",
"this",
".",
"shell",
".",
"addShellListener",
"(",
"new",
"ShellAdapter",
"(",
")",
"{",
"public",
"void",
"shellClosed",
"(",
"ShellEvent",
"e",
")",
"{",
"tripleGEOStepDialog",
".",
"this",
".",
"cancel",
"(",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"wbbPathCSV",
".",
"addSelectionListener",
"(",
"new",
"SelectionAdapter",
"(",
")",
"{",
"public",
"void",
"widgetSelected",
"(",
"SelectionEvent",
"e",
")",
"{",
"FileDialog",
"dialog",
"=",
"new",
"FileDialog",
"(",
"shell",
",",
"SWT",
".",
"OPEN",
")",
";",
"dialog",
".",
"setFilterExtensions",
"(",
"new",
"String",
"[",
"]",
"{",
"\"",
"*.csv;*.CSV",
"\"",
",",
"\"",
"*",
"\"",
"}",
")",
";",
"if",
"(",
"tripleGEOStepDialog",
".",
"this",
".",
"wPathCSV",
".",
"getText",
"(",
")",
"!=",
"null",
")",
"{",
"dialog",
".",
"setFileName",
"(",
"tripleGEOStepDialog",
".",
"this",
".",
"wPathCSV",
".",
"getText",
"(",
")",
")",
";",
"}",
"dialog",
".",
"setFilterNames",
"(",
"new",
"String",
"[",
"]",
"{",
"\"",
"CSV files",
"\"",
",",
"\"",
"All files",
"\"",
"}",
")",
";",
"if",
"(",
"dialog",
".",
"open",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"str",
"=",
"dialog",
".",
"getFilterPath",
"(",
")",
"+",
"System",
".",
"getProperty",
"(",
"\"",
"file.separator",
"\"",
")",
"+",
"dialog",
".",
"getFileName",
"(",
")",
";",
"tripleGEOStepDialog",
".",
"this",
".",
"wPathCSV",
".",
"setText",
"(",
"str",
")",
";",
"}",
"}",
"}",
")",
";",
"setSize",
"(",
"this",
".",
"shell",
",",
"600",
",",
"600",
",",
"true",
")",
";",
"getData",
"(",
")",
";",
"this",
".",
"input",
".",
"setChanged",
"(",
"this",
".",
"changed",
")",
";",
"this",
".",
"shell",
".",
"open",
"(",
")",
";",
"while",
"(",
"!",
"this",
".",
"shell",
".",
"isDisposed",
"(",
")",
")",
"{",
"if",
"(",
"!",
"display",
".",
"readAndDispatch",
"(",
")",
")",
"{",
"display",
".",
"sleep",
"(",
")",
";",
"}",
"}",
"return",
"this",
".",
"stepname",
";",
"}",
"/**\n\t * Collect data from the meta and place it in the dialog.\n\t */",
"public",
"void",
"getData",
"(",
")",
"{",
"this",
".",
"wStepname",
".",
"selectAll",
"(",
")",
";",
"this",
".",
"wAttributeName",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getAttributeName",
"(",
")",
")",
";",
"this",
".",
"wFeature",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getFeature",
"(",
")",
")",
";",
"this",
".",
"wOntologyNS",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getOntologyNS",
"(",
")",
")",
";",
"this",
".",
"wOntologyNSPrefix",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getOntologyNSPrefix",
"(",
")",
")",
";",
"this",
".",
"wResourceNS",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getResourceNS",
"(",
")",
")",
";",
"this",
".",
"wResourceNSPrefix",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getResourceNSPrefix",
"(",
")",
")",
";",
"this",
".",
"wLanguage",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getLanguage",
"(",
")",
")",
";",
"this",
".",
"wPathCSV",
".",
"setText",
"(",
"this",
".",
"input",
".",
"getPathCSV",
"(",
")",
")",
";",
"this",
".",
"wuuids",
".",
"setSelection",
"(",
"this",
".",
"input",
".",
"isUuidsActive",
"(",
")",
")",
";",
"FieldDefinition",
"[",
"]",
"fields",
"=",
"this",
".",
"input",
".",
"getFields",
"(",
")",
";",
"if",
"(",
"fields",
"!=",
"null",
")",
"{",
"for",
"(",
"FieldDefinition",
"field",
":",
"fields",
")",
"{",
"TableItem",
"item",
"=",
"new",
"TableItem",
"(",
"this",
".",
"wFields",
".",
"table",
",",
"SWT",
".",
"NONE",
")",
";",
"int",
"colnr",
"=",
"1",
";",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"Const",
".",
"NVL",
"(",
"field",
".",
"prefix",
",",
"Constants",
".",
"empty",
")",
")",
";",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"Const",
".",
"NVL",
"(",
"field",
".",
"uri",
",",
"Constants",
".",
"empty",
")",
")",
";",
"}",
"}",
"this",
".",
"wFields",
".",
"removeEmptyRows",
"(",
")",
";",
"this",
".",
"wFields",
".",
"setRowNums",
"(",
")",
";",
"this",
".",
"wFields",
".",
"optWidth",
"(",
"true",
")",
";",
"ColumnDefinition",
"[",
"]",
"columns",
"=",
"this",
".",
"input",
".",
"getColumns",
"(",
")",
";",
"if",
"(",
"columns",
"!=",
"null",
"||",
"(",
"columns",
"!=",
"null",
"&&",
"!",
"this",
".",
"trans",
".",
"haveHopsChanged",
"(",
")",
")",
")",
"{",
"for",
"(",
"ColumnDefinition",
"c",
":",
"columns",
")",
"{",
"TableItem",
"item",
"=",
"new",
"TableItem",
"(",
"this",
".",
"wColumns",
".",
"table",
",",
"SWT",
".",
"NONE",
")",
";",
"int",
"colnr",
"=",
"1",
";",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"Const",
".",
"NVL",
"(",
"c",
".",
"show",
",",
"\"",
"YES",
"\"",
")",
")",
";",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"Const",
".",
"NVL",
"(",
"c",
".",
"column",
",",
"Constants",
".",
"empty",
")",
")",
";",
"if",
"(",
"c",
".",
"getColumn",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"Constants",
".",
"the_geom",
")",
")",
"{",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"\"",
"n/a",
"\"",
")",
";",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"\"",
"n/a",
"\"",
")",
";",
"}",
"else",
"{",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"Const",
".",
"NVL",
"(",
"c",
".",
"prefix",
",",
"Constants",
".",
"empty",
")",
")",
";",
"item",
".",
"setText",
"(",
"colnr",
"++",
",",
"Const",
".",
"NVL",
"(",
"c",
".",
"uri",
",",
"Constants",
".",
"empty",
")",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"(",
"columns",
"!=",
"null",
"&&",
"this",
".",
"trans",
".",
"haveHopsChanged",
"(",
")",
")",
"||",
"(",
"columns",
"==",
"null",
")",
")",
"{",
"loadColumns",
"(",
")",
";",
"}",
"this",
".",
"wColumns",
".",
"removeEmptyRows",
"(",
")",
";",
"this",
".",
"wColumns",
".",
"setRowNums",
"(",
")",
";",
"this",
".",
"wColumns",
".",
"optWidth",
"(",
"true",
")",
";",
"}",
"/**\n\t * Let the tripleGEOStepMeta know about the entered data\n\t * @throws KettleValueException \n\t */",
"private",
"void",
"ok",
"(",
")",
"{",
"this",
".",
"stepname",
"=",
"this",
".",
"wStepname",
".",
"getText",
"(",
")",
";",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wAttributeName",
".",
"getText",
"(",
")",
")",
")",
"{",
"this",
".",
"input",
".",
"setAttributeName",
"(",
"this",
".",
"wAttributeName",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setAttributeName",
"(",
"this",
".",
"input",
".",
"getAttributeName",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wFeature",
".",
"getText",
"(",
")",
")",
")",
"{",
"this",
".",
"input",
".",
"setFeature",
"(",
"this",
".",
"wFeature",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setFeature",
"(",
"this",
".",
"input",
".",
"getFeature",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wOntologyNS",
".",
"getText",
"(",
")",
")",
")",
"{",
"this",
".",
"input",
".",
"setOntologyNS",
"(",
"this",
".",
"wOntologyNS",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setOntologyNS",
"(",
"this",
".",
"input",
".",
"getOntologyNS",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wOntologyNSPrefix",
".",
"getText",
"(",
")",
")",
")",
"{",
"this",
".",
"input",
".",
"setOntologyNSPrefix",
"(",
"this",
".",
"wOntologyNSPrefix",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setOntologyNSPrefix",
"(",
"this",
".",
"input",
".",
"getOntologyNSPrefix",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wResourceNS",
".",
"getText",
"(",
")",
")",
")",
"{",
"this",
".",
"input",
".",
"setResourceNS",
"(",
"this",
".",
"wResourceNS",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setResourceNS",
"(",
"this",
".",
"input",
".",
"getResourceNS",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wResourceNSPrefix",
".",
"getText",
"(",
")",
")",
")",
"{",
"this",
".",
"input",
".",
"setResourceNSPrefix",
"(",
"this",
".",
"wResourceNSPrefix",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setResourceNSPrefix",
"(",
"this",
".",
"input",
".",
"getResourceNSPrefix",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wLanguage",
".",
"getText",
"(",
")",
")",
")",
"{",
"this",
".",
"input",
".",
"setLanguage",
"(",
"this",
".",
"wLanguage",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setLanguage",
"(",
"Constants",
".",
"null_",
")",
";",
"}",
"if",
"(",
"!",
"isEmpty",
"(",
"this",
".",
"wPathCSV",
".",
"getText",
"(",
")",
")",
")",
"{",
"String",
"ext",
"=",
"FilenameUtils",
".",
"getExtension",
"(",
"this",
".",
"wPathCSV",
".",
"getText",
"(",
")",
")",
";",
"if",
"(",
"ext",
".",
"equalsIgnoreCase",
"(",
"\"",
"csv",
"\"",
")",
")",
"{",
"this",
".",
"input",
".",
"setPathCSV",
"(",
"this",
".",
"wPathCSV",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setPathCSV",
"(",
"this",
".",
"input",
".",
"getPathCSV",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"input",
".",
"setPathCSV",
"(",
"Constants",
".",
"null_",
")",
";",
"}",
"int",
"nrNonEmptyFields",
"=",
"this",
".",
"wFields",
".",
"nrNonEmpty",
"(",
")",
";",
"FieldDefinition",
"[",
"]",
"fields",
"=",
"new",
"FieldDefinition",
"[",
"nrNonEmptyFields",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nrNonEmptyFields",
";",
"i",
"++",
")",
"{",
"TableItem",
"item",
"=",
"this",
".",
"wFields",
".",
"getNonEmpty",
"(",
"i",
")",
";",
"fields",
"[",
"i",
"]",
"=",
"new",
"FieldDefinition",
"(",
")",
";",
"int",
"colnr",
"=",
"1",
";",
"fields",
"[",
"i",
"]",
".",
"prefix",
"=",
"item",
".",
"getText",
"(",
"colnr",
"++",
")",
";",
"fields",
"[",
"i",
"]",
".",
"uri",
"=",
"item",
".",
"getText",
"(",
"colnr",
"++",
")",
";",
"}",
"this",
".",
"input",
".",
"setFields",
"(",
"fields",
")",
";",
"this",
".",
"wFields",
".",
"removeEmptyRows",
"(",
")",
";",
"this",
".",
"wFields",
".",
"setRowNums",
"(",
")",
";",
"this",
".",
"wFields",
".",
"optWidth",
"(",
"true",
")",
";",
"int",
"nrNonEmptyColumns",
"=",
"this",
".",
"wColumns",
".",
"nrNonEmpty",
"(",
")",
";",
"ColumnDefinition",
"[",
"]",
"columns",
"=",
"new",
"ColumnDefinition",
"[",
"nrNonEmptyColumns",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nrNonEmptyColumns",
";",
"i",
"++",
")",
"{",
"TableItem",
"item",
"=",
"this",
".",
"wColumns",
".",
"getNonEmpty",
"(",
"i",
")",
";",
"columns",
"[",
"i",
"]",
"=",
"new",
"ColumnDefinition",
"(",
")",
";",
"int",
"colnr",
"=",
"1",
";",
"columns",
"[",
"i",
"]",
".",
"show",
"=",
"item",
".",
"getText",
"(",
"colnr",
"++",
")",
";",
"if",
"(",
"i",
"==",
"0",
")",
"{",
"columns",
"[",
"i",
"]",
".",
"column",
"=",
"\"",
"the_geom",
"\"",
";",
"colnr",
"++",
";",
"}",
"else",
"{",
"String",
"col",
"=",
"item",
".",
"getText",
"(",
"colnr",
"++",
")",
";",
"if",
"(",
"!",
"isEmpty",
"(",
"col",
")",
")",
"{",
"columns",
"[",
"i",
"]",
".",
"column",
"=",
"col",
";",
"}",
"else",
"{",
"columns",
"[",
"i",
"]",
".",
"column",
"=",
"\"",
"empty",
"\"",
";",
"}",
"}",
"columns",
"[",
"i",
"]",
".",
"prefix",
"=",
"item",
".",
"getText",
"(",
"colnr",
"++",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"Boolean",
"flag",
"=",
"true",
";",
"if",
"(",
"columns",
"[",
"i",
"]",
".",
"column",
".",
"equalsIgnoreCase",
"(",
"\"",
"the_geom",
"\"",
")",
")",
"{",
"flag",
"=",
"false",
";",
"}",
"else",
"{",
"flag",
"=",
"true",
";",
"}",
"String",
"uri",
"=",
"item",
".",
"getText",
"(",
"colnr",
"++",
")",
";",
"if",
"(",
"isValidURL",
"(",
"uri",
",",
"true",
")",
")",
"{",
"columns",
"[",
"i",
"]",
".",
"uri",
"=",
"uri",
";",
"}",
"else",
"{",
"columns",
"[",
"i",
"]",
".",
"uri",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"nrNonEmptyColumns",
">",
"0",
")",
"{",
"this",
".",
"input",
".",
"setColumns",
"(",
"columns",
")",
";",
"if",
"(",
"this",
".",
"input",
".",
"getColumn_name",
"(",
")",
"==",
"null",
")",
"{",
"loadColumnName",
"(",
")",
";",
"}",
"int",
"j",
"=",
"0",
";",
"for",
"(",
"String",
"c",
":",
"this",
".",
"input",
".",
"getColumn_name",
"(",
")",
")",
"{",
"columns",
"[",
"j",
"]",
".",
"column_shp",
"=",
"c",
";",
"if",
"(",
"columns",
"[",
"j",
"]",
".",
"column",
".",
"equalsIgnoreCase",
"(",
"\"",
"empty",
"\"",
")",
")",
"{",
"columns",
"[",
"j",
"]",
".",
"column",
"=",
"c",
";",
"}",
"j",
"++",
";",
"}",
"}",
"this",
".",
"wColumns",
".",
"removeEmptyRows",
"(",
")",
";",
"this",
".",
"wColumns",
".",
"setRowNums",
"(",
")",
";",
"this",
".",
"wColumns",
".",
"optWidth",
"(",
"true",
")",
";",
"this",
".",
"input",
".",
"setChanged",
"(",
")",
";",
"dispose",
"(",
")",
";",
"}",
"/**\n\t * Cancel\n\t */",
"private",
"void",
"cancel",
"(",
")",
"{",
"this",
".",
"stepname",
"=",
"null",
";",
"this",
".",
"input",
".",
"setChanged",
"(",
"this",
".",
"changed",
")",
";",
"dispose",
"(",
")",
";",
"}",
"/**\n\t * Verifies if the string is empty\n\t * @param string - The string\n\t * @return true if the string is empty; otherwise, false\n\t */",
"public",
"static",
"boolean",
"isEmpty",
"(",
"String",
"string",
")",
"{",
"if",
"(",
"string",
"==",
"null",
"||",
"string",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"true",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"string",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"Character",
".",
"isWhitespace",
"(",
"string",
".",
"charAt",
"(",
"i",
")",
")",
"==",
"false",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"/**\n\t * Validate an URL\n\t * @param url\n\t * @return true if the url is valid; otherwise, false\n\t */",
"public",
"boolean",
"isValidURL",
"(",
"String",
"url",
",",
"Boolean",
"flag",
")",
"{",
"if",
"(",
"flag",
")",
"{",
"URL",
"u",
"=",
"null",
";",
"try",
"{",
"u",
"=",
"new",
"URL",
"(",
"url",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"u",
".",
"toURI",
"(",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"return",
"true",
";",
"}",
"/**\n\t * Load columns name in a ArrayList\n\t */",
"private",
"void",
"loadColumnName",
"(",
")",
"{",
"try",
"{",
"ArrayList",
"<",
"String",
">",
"column_name",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
"this",
".",
"trans",
".",
"getPrevStepFields",
"(",
"this",
".",
"trans",
".",
"findStep",
"(",
"this",
".",
"wStepname",
".",
"getText",
"(",
")",
")",
")",
"!=",
"null",
")",
"{",
"RowMetaInterface",
"rm",
"=",
"this",
".",
"trans",
".",
"getPrevStepFields",
"(",
"this",
".",
"trans",
".",
"findStep",
"(",
"this",
".",
"wStepname",
".",
"getText",
"(",
")",
")",
")",
";",
"for",
"(",
"ValueMetaInterface",
"vmeta",
":",
"rm",
".",
"getValueMetaList",
"(",
")",
")",
"{",
"column_name",
".",
"add",
"(",
"vmeta",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"this",
".",
"input",
".",
"setColumn_name",
"(",
"column_name",
")",
";",
"}",
"catch",
"(",
"KettleStepException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"/**\n\t * Load columns shapefile\n\t */",
"private",
"void",
"loadColumns",
"(",
")",
"{",
"try",
"{",
"ArrayList",
"<",
"String",
">",
"column_name",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"RowMetaInterface",
"rm",
"=",
"this",
".",
"trans",
".",
"getPrevStepFields",
"(",
"this",
".",
"trans",
".",
"findStep",
"(",
"this",
".",
"wStepname",
".",
"getText",
"(",
")",
")",
")",
";",
"for",
"(",
"ValueMetaInterface",
"vmeta",
":",
"rm",
".",
"getValueMetaList",
"(",
")",
")",
"{",
"TableItem",
"item",
"=",
"new",
"TableItem",
"(",
"this",
".",
"wColumns",
".",
"table",
",",
"0",
")",
";",
"item",
".",
"setText",
"(",
"1",
",",
"\"",
"YES",
"\"",
")",
";",
"item",
".",
"setText",
"(",
"2",
",",
"vmeta",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"vmeta",
".",
"getName",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"Constants",
".",
"the_geom",
")",
")",
"{",
"item",
".",
"setText",
"(",
"3",
",",
"\"",
"n/a",
"\"",
")",
";",
"item",
".",
"setText",
"(",
"4",
",",
"\"",
"n/a",
"\"",
")",
";",
"}",
"column_name",
".",
"add",
"(",
"vmeta",
".",
"getName",
"(",
")",
")",
";",
"}",
"this",
".",
"input",
".",
"setColumn_name",
"(",
"column_name",
")",
";",
"this",
".",
"wColumns",
".",
"removeEmptyRows",
"(",
")",
";",
"this",
".",
"wColumns",
".",
"setRowNums",
"(",
")",
";",
"this",
".",
"wColumns",
".",
"optWidth",
"(",
"true",
")",
";",
"}",
"catch",
"(",
"KettleStepException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}"
] | This interface is used to launch Step Dialogs. | [
"This",
"interface",
"is",
"used",
"to",
"launch",
"Step",
"Dialogs",
"."
] | [
"// STEPNAME",
"// TAB FOLDER",
"// ATTRIBUTE NAME",
"// FEATURE\t ",
"// ONTOLOGY NAMESPACE",
"// ONTOLOGY NAMESPACE PREFIX",
"// RESOURCE NAMESPACE",
"// RESOURCE NAMESPACE PREFIX",
"// LANGUAGE",
"// PATH CSV PathCSV",
"// UUIDS",
"// CHECKBOX UUIDS",
"// FIELDS",
"// COLUMNS\t\t",
"// Turns off sort arrows",
"// OK - CANCEL",
"// Detect X or ALT-F4 or something that kills this window",
"// Listen to the browse button next to the file name",
"// Set the shell size, based upon previous time"
] | [
{
"param": "BaseStepDialog",
"type": null
},
{
"param": "StepDialogInterface",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseStepDialog",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "StepDialogInterface",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
feac32ac058db8d21144b5381727625c32775b35 | paul-hyun/emp | src/main/java/com/hellonms/platforms/emp_onion/client_swt/widget/viewpart/ViewPart4One.java | [
"Apache-2.0"
] | Java | ViewPart4One | /**
* <p>
* Hash Only One page
* </p>
*
* @since 1.6
* @create 2015. 5. 18.
* @modified 2015. 5. 18.
* @author cchyun
*
*/ |
Hash Only One page
| [
"Hash",
"Only",
"One",
"page"
] | public class ViewPart4One extends ViewPartAt {
private class PageItem {
private final PAGE page;
public PageItem(PAGE page) {
this.page = page;
}
public void dispose() {
}
}
private PageItem page;
public ViewPart4One(Workbench workbench, int style) {
super(workbench, style);
createGUI();
}
private void createGUI() {
}
@Override
public void openPage(PAGE page) {
if (this.page != null) {
this.page.dispose();
}
this.page = new PageItem(page);
}
private AtomicBoolean lock_layout = new AtomicBoolean(false);
@Override
public void layout() {
if (!lock_layout.get() && page != null) {
try {
lock_layout.set(true);
PageIf ppp = getWorkbench().getPage(page.page);
if (ppp != null) {
((Control) ppp).setBounds(getBounds());
}
} finally {
lock_layout.set(false);
}
}
}
} | [
"public",
"class",
"ViewPart4One",
"extends",
"ViewPartAt",
"{",
"private",
"class",
"PageItem",
"{",
"private",
"final",
"PAGE",
"page",
";",
"public",
"PageItem",
"(",
"PAGE",
"page",
")",
"{",
"this",
".",
"page",
"=",
"page",
";",
"}",
"public",
"void",
"dispose",
"(",
")",
"{",
"}",
"}",
"private",
"PageItem",
"page",
";",
"public",
"ViewPart4One",
"(",
"Workbench",
"workbench",
",",
"int",
"style",
")",
"{",
"super",
"(",
"workbench",
",",
"style",
")",
";",
"createGUI",
"(",
")",
";",
"}",
"private",
"void",
"createGUI",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"openPage",
"(",
"PAGE",
"page",
")",
"{",
"if",
"(",
"this",
".",
"page",
"!=",
"null",
")",
"{",
"this",
".",
"page",
".",
"dispose",
"(",
")",
";",
"}",
"this",
".",
"page",
"=",
"new",
"PageItem",
"(",
"page",
")",
";",
"}",
"private",
"AtomicBoolean",
"lock_layout",
"=",
"new",
"AtomicBoolean",
"(",
"false",
")",
";",
"@",
"Override",
"public",
"void",
"layout",
"(",
")",
"{",
"if",
"(",
"!",
"lock_layout",
".",
"get",
"(",
")",
"&&",
"page",
"!=",
"null",
")",
"{",
"try",
"{",
"lock_layout",
".",
"set",
"(",
"true",
")",
";",
"PageIf",
"ppp",
"=",
"getWorkbench",
"(",
")",
".",
"getPage",
"(",
"page",
".",
"page",
")",
";",
"if",
"(",
"ppp",
"!=",
"null",
")",
"{",
"(",
"(",
"Control",
")",
"ppp",
")",
".",
"setBounds",
"(",
"getBounds",
"(",
")",
")",
";",
"}",
"}",
"finally",
"{",
"lock_layout",
".",
"set",
"(",
"false",
")",
";",
"}",
"}",
"}",
"}"
] | <p>
Hash Only One page
</p> | [
"<p",
">",
"Hash",
"Only",
"One",
"page",
"<",
"/",
"p",
">"
] | [] | [
{
"param": "ViewPartAt",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ViewPartAt",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
feafdc13e5901e5df646c8ffd6492d90d5243027 | bmeurer/websitecompressor | src/main/java/de/benediktmeurer/websitecompressor/CmdLineCompressor.java | [
"Apache-2.0"
] | Java | CmdLineCompressor | /**
* Wrapper for website compression tools <code>htmlcompressor</code>
* and <code>yuicompressor</code>.
*
* <p>Usage: <code>java -jar websitecompressor.jar [options] [files]</code></p>
* <p>To view a list of all available parameters please run with <code>--help</code> option:</p>
* <p><code>java -jar websitecompressor.jar --help</code></p>
*
* @author <a href="mailto:[email protected]">Benedikt Meurer</a>
*/ | Wrapper for website compression tools htmlcompressor
and yuicompressor.
@author Benedikt Meurer | [
"Wrapper",
"for",
"website",
"compression",
"tools",
"htmlcompressor",
"and",
"yuicompressor",
".",
"@author",
"Benedikt",
"Meurer"
] | public class CmdLineCompressor {
private static CmdLineParser parser = new CmdLineParser();
private static CmdLineParser.Option helpOpt;
private static CmdLineParser.Option charsetOpt;
private static CmdLineParser.Option compressCssOpt;
private static CmdLineParser.Option compressJsOpt;
private static CmdLineParser.Option disableOptimizationsOpt;
private static CmdLineParser.Option lineBreakOpt;
private static CmdLineParser.Option nomungeOpt;
private static CmdLineParser.Option preserveCommentsOpt;
private static CmdLineParser.Option preserveIntertagSpacesOpt;
private static CmdLineParser.Option preserveLineBreaksOpt;
private static CmdLineParser.Option preserveMultiSpacesOpt;
private static CmdLineParser.Option preserveQuotesOpt;
private static CmdLineParser.Option preserveSemiOpt;
private static String charset;
private static int lineBreakPos = -1;
public static void main(String[] args) {
helpOpt = parser.addBooleanOption('h', "help");
charsetOpt = parser.addStringOption("charset");
compressCssOpt = parser.addBooleanOption("compress-css");
compressJsOpt = parser.addBooleanOption("compress-js");
disableOptimizationsOpt = parser.addBooleanOption("disable-optimizations");
lineBreakOpt = parser.addStringOption("line-break");
nomungeOpt = parser.addBooleanOption("nomunge");
preserveCommentsOpt = parser.addBooleanOption("preserve-comments");
preserveIntertagSpacesOpt = parser.addBooleanOption("preserve-intertag-spaces");
preserveLineBreaksOpt = parser.addBooleanOption("preserve-line-breaks");
preserveMultiSpacesOpt = parser.addBooleanOption("preserve-multi-spaces");
preserveQuotesOpt = parser.addBooleanOption("preserve-quotes");
preserveSemiOpt = parser.addBooleanOption("preserve-semi");
try {
parser.parse(args);
// help
Boolean help = (Boolean)parser.getOptionValue(helpOpt);
if (help != null && help.booleanValue()) {
printUsage(System.out);
System.exit(0);
}
// charset
charset = (String)parser.getOptionValue(charsetOpt, "UTF-8");
if (charset == null || !Charset.isSupported(charset)) {
charset = "UTF-8";
}
// line-break
String lineBreakStr = (String)parser.getOptionValue(lineBreakOpt);
if (lineBreakStr != null) {
try {
lineBreakPos = Integer.parseInt(lineBreakStr, 10);
}
catch (NumberFormatException e) {
printUsage(System.err);
System.exit(1);
}
}
// Compress all files and folders
String[] fileNames = parser.getRemainingArgs();
if (fileNames.length == 0) {
printUsage(System.err);
System.exit(1);
}
for (String fileName : fileNames) {
File file = new File(fileName);
compress(file);
}
}
catch (NoClassDefFoundError e) {
System.err.println(""
+ "ERROR: The additional jar files called htmlcompressor-1.4.3.jar\n"
+ "and yuicompressor-2.4.6.jar must be present in the same directory\n"
+ "as the websitecompressor jar file.");
System.exit(1);
}
catch (CmdLineParser.OptionException e) {
printUsage(System.err);
System.exit(1);
}
catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
private static class CompressorCss implements Compressor {
public String compress(String input) throws IOException {
CssCompressor cssCompressor = new CssCompressor(new StringReader(input));
StringWriter writer = new StringWriter();
cssCompressor.compress(writer, lineBreakPos);
return writer.toString();
}
}
private static class CompressorHtml implements Compressor {
private HtmlCompressor htmlCompressor = new HtmlCompressor();
public CompressorHtml() {
htmlCompressor.setCompressCss(parser.getOptionValue(compressCssOpt) != null);
htmlCompressor.setCompressJavaScript(parser.getOptionValue(compressJsOpt) != null);
htmlCompressor.setRemoveComments(parser.getOptionValue(preserveCommentsOpt) == null);
htmlCompressor.setRemoveIntertagSpaces(parser.getOptionValue(preserveIntertagSpacesOpt) == null);
htmlCompressor.setPreserveLineBreaks(parser.getOptionValue(preserveLineBreaksOpt) != null);
htmlCompressor.setRemoveMultiSpaces(parser.getOptionValue(preserveMultiSpacesOpt) == null);
htmlCompressor.setRemoveQuotes(parser.getOptionValue(preserveQuotesOpt) == null);
htmlCompressor.setYuiCssLineBreak(lineBreakPos);
htmlCompressor.setYuiJsDisableOptimizations(parser.getOptionValue(disableOptimizationsOpt) != null);
htmlCompressor.setYuiJsLineBreak(lineBreakPos);
htmlCompressor.setYuiJsNoMunge(parser.getOptionValue(nomungeOpt) != null);
htmlCompressor.setYuiJsPreserveAllSemiColons(parser.getOptionValue(preserveSemiOpt) != null);
}
public String compress(String input) throws IOException {
return htmlCompressor.compress(input);
}
}
private static class CompressorJs implements Compressor {
public String compress(String input) throws IOException {
JavaScriptCompressor javaScriptCompressor = new JavaScriptCompressor(new StringReader(input), new ErrorReporter() {
public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) {
if (line < 0) {
System.err.println("\n[WARNING] " + message);
} else {
System.err.println("\n[WARNING] " + line + ':' + lineOffset + ':' + message);
}
}
public void error(String message, String sourceName, int line, String lineSource, int lineOffset) {
if (line < 0) {
System.err.println("\n[ERROR] " + message);
} else {
System.err.println("\n[ERROR] " + line + ':' + lineOffset + ':' + message);
}
}
public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) {
error(message, sourceName, line, lineSource, lineOffset);
return new EvaluatorException(message);
}
});
boolean nomunge = (parser.getOptionValue(nomungeOpt) != null);
boolean preserveSemi = (parser.getOptionValue(preserveSemiOpt) != null);
boolean disableOptimizations = (parser.getOptionValue(disableOptimizationsOpt) != null);
StringWriter writer = new StringWriter();
javaScriptCompressor.compress(writer, lineBreakPos, !nomunge, false, preserveSemi, disableOptimizations);
return writer.toString();
}
}
private static class CompressorXml implements Compressor {
private XmlCompressor xmlCompressor = new XmlCompressor();
public CompressorXml() {
xmlCompressor.setRemoveComments(parser.getOptionValue(preserveCommentsOpt) == null);
xmlCompressor.setRemoveIntertagSpaces(parser.getOptionValue(preserveIntertagSpacesOpt) == null);
}
public String compress(String input) throws IOException {
return xmlCompressor.compress(input);
}
}
private static CompressorCss compressorCss = null;
private static CompressorHtml compressorHtml = null;
private static CompressorJs compressorJs = null;
private static CompressorXml compressorXml = null;
private static void compress(File file) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; ++i) {
compress(files[i]);
}
}
}
else {
String fileName = file.getName();
int fileDotIndex = fileName.lastIndexOf('.');
if (fileDotIndex > 0 && fileDotIndex + 1 < fileName.length()) {
String fileExtension = fileName.substring(fileDotIndex + 1);
Compressor compressor = null;
if ("css".equalsIgnoreCase(fileExtension)) {
if (compressorCss == null) {
compressorCss = new CompressorCss();
}
compressor = compressorCss;
}
else if ("html".equalsIgnoreCase(fileExtension)) {
if (compressorHtml == null) {
compressorHtml = new CompressorHtml();
}
compressor = compressorHtml;
}
else if ("js".equalsIgnoreCase(fileExtension)) {
if (compressorJs == null) {
compressorJs = new CompressorJs();
}
compressor = compressorJs;
}
else if ("xml".equalsIgnoreCase(fileExtension)) {
if (compressorXml == null) {
compressorXml = new CompressorXml();
}
compressor = compressorXml;
}
if (compressor != null) {
// Read the input from the file
StringBuilder input = new StringBuilder();
InputStream fileInputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, charset));
try {
String line;
String lineSeparator = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
input.append(line);
input.append(lineSeparator);
}
}
finally {
reader.close();
}
// Compress the file content
String output = compressor.compress(input.toString());
// Write the output to the file
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), charset);
try {
writer.write(output);
}
finally {
writer.close();
}
}
}
}
}
private static void printUsage(PrintStream s) {
s.println(""
+ "Usage: java -jar websitecompressor.jar [options] [files]\n"
+ "\n"
+ "<files or folders> The files are compressed in-place\n"
+ "\n"
+ "Global Options:\n"
+ " --charset <charset> Read the input files using <charset>\n"
+ " -h, --help Print this screen\n"
+ "\n"
+ "CSS Compression Options:\n"
+ " --line-break <column> Insert a line break after the specified column number\n"
+ "\n"
+ "HTML Compression Options:\n"
+ " --compress-css Enable inline CSS compression\n"
+ " --compress-js Enable inline JavaScript compression\n"
+ " --preserve-comments Preserve comments\n"
+ " --preserve-intertag-spaces Preserve intertag spaces\n"
+ " --preserve-line-breaks Preserve line breaks\n"
+ " --preserve-multi-spaces Preserve multiple spaces\n"
+ " --preserve-quotes Preserve unneeded quotes\n"
+ "\n"
+ "JavaScript Compression Options:\n"
+ " --disable-optimizations Disable all micro optimizations\n"
+ " --line-break <column> Insert a line break after the specified column number\n"
+ " --nomunge Minify only, do not obfuscate\n"
+ " --preserve-semi Preserve all semicolons\n"
+ "\n"
+ "XML Compression Options:\n"
+ " --preserve-comments Preserve comments\n"
+ " --preserve-intertag-spaces Preserve intertag spaces\n"
+ "\n"
+ "Please note that additional HTML Compressor and YUI Compressor jar\n"
+ "files must be present in the same directory as this jar file."
+ "");
}
} | [
"public",
"class",
"CmdLineCompressor",
"{",
"private",
"static",
"CmdLineParser",
"parser",
"=",
"new",
"CmdLineParser",
"(",
")",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"helpOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"charsetOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"compressCssOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"compressJsOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"disableOptimizationsOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"lineBreakOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"nomungeOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"preserveCommentsOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"preserveIntertagSpacesOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"preserveLineBreaksOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"preserveMultiSpacesOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"preserveQuotesOpt",
";",
"private",
"static",
"CmdLineParser",
".",
"Option",
"preserveSemiOpt",
";",
"private",
"static",
"String",
"charset",
";",
"private",
"static",
"int",
"lineBreakPos",
"=",
"-",
"1",
";",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"helpOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"'h'",
",",
"\"",
"help",
"\"",
")",
";",
"charsetOpt",
"=",
"parser",
".",
"addStringOption",
"(",
"\"",
"charset",
"\"",
")",
";",
"compressCssOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"compress-css",
"\"",
")",
";",
"compressJsOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"compress-js",
"\"",
")",
";",
"disableOptimizationsOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"disable-optimizations",
"\"",
")",
";",
"lineBreakOpt",
"=",
"parser",
".",
"addStringOption",
"(",
"\"",
"line-break",
"\"",
")",
";",
"nomungeOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"nomunge",
"\"",
")",
";",
"preserveCommentsOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"preserve-comments",
"\"",
")",
";",
"preserveIntertagSpacesOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"preserve-intertag-spaces",
"\"",
")",
";",
"preserveLineBreaksOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"preserve-line-breaks",
"\"",
")",
";",
"preserveMultiSpacesOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"preserve-multi-spaces",
"\"",
")",
";",
"preserveQuotesOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"preserve-quotes",
"\"",
")",
";",
"preserveSemiOpt",
"=",
"parser",
".",
"addBooleanOption",
"(",
"\"",
"preserve-semi",
"\"",
")",
";",
"try",
"{",
"parser",
".",
"parse",
"(",
"args",
")",
";",
"Boolean",
"help",
"=",
"(",
"Boolean",
")",
"parser",
".",
"getOptionValue",
"(",
"helpOpt",
")",
";",
"if",
"(",
"help",
"!=",
"null",
"&&",
"help",
".",
"booleanValue",
"(",
")",
")",
"{",
"printUsage",
"(",
"System",
".",
"out",
")",
";",
"System",
".",
"exit",
"(",
"0",
")",
";",
"}",
"charset",
"=",
"(",
"String",
")",
"parser",
".",
"getOptionValue",
"(",
"charsetOpt",
",",
"\"",
"UTF-8",
"\"",
")",
";",
"if",
"(",
"charset",
"==",
"null",
"||",
"!",
"Charset",
".",
"isSupported",
"(",
"charset",
")",
")",
"{",
"charset",
"=",
"\"",
"UTF-8",
"\"",
";",
"}",
"String",
"lineBreakStr",
"=",
"(",
"String",
")",
"parser",
".",
"getOptionValue",
"(",
"lineBreakOpt",
")",
";",
"if",
"(",
"lineBreakStr",
"!=",
"null",
")",
"{",
"try",
"{",
"lineBreakPos",
"=",
"Integer",
".",
"parseInt",
"(",
"lineBreakStr",
",",
"10",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"printUsage",
"(",
"System",
".",
"err",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}",
"String",
"[",
"]",
"fileNames",
"=",
"parser",
".",
"getRemainingArgs",
"(",
")",
";",
"if",
"(",
"fileNames",
".",
"length",
"==",
"0",
")",
"{",
"printUsage",
"(",
"System",
".",
"err",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"for",
"(",
"String",
"fileName",
":",
"fileNames",
")",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"fileName",
")",
";",
"compress",
"(",
"file",
")",
";",
"}",
"}",
"catch",
"(",
"NoClassDefFoundError",
"e",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"",
"\"",
"+",
"\"",
"ERROR: The additional jar files called htmlcompressor-1.4.3.jar",
"\\n",
"\"",
"+",
"\"",
"and yuicompressor-2.4.6.jar must be present in the same directory",
"\\n",
"\"",
"+",
"\"",
"as the websitecompressor jar file.",
"\"",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"catch",
"(",
"CmdLineParser",
".",
"OptionException",
"e",
")",
"{",
"printUsage",
"(",
"System",
".",
"err",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
"System",
".",
"err",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"System",
".",
"exit",
"(",
"0",
")",
";",
"}",
"private",
"static",
"class",
"CompressorCss",
"implements",
"Compressor",
"{",
"public",
"String",
"compress",
"(",
"String",
"input",
")",
"throws",
"IOException",
"{",
"CssCompressor",
"cssCompressor",
"=",
"new",
"CssCompressor",
"(",
"new",
"StringReader",
"(",
"input",
")",
")",
";",
"StringWriter",
"writer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"cssCompressor",
".",
"compress",
"(",
"writer",
",",
"lineBreakPos",
")",
";",
"return",
"writer",
".",
"toString",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"CompressorHtml",
"implements",
"Compressor",
"{",
"private",
"HtmlCompressor",
"htmlCompressor",
"=",
"new",
"HtmlCompressor",
"(",
")",
";",
"public",
"CompressorHtml",
"(",
")",
"{",
"htmlCompressor",
".",
"setCompressCss",
"(",
"parser",
".",
"getOptionValue",
"(",
"compressCssOpt",
")",
"!=",
"null",
")",
";",
"htmlCompressor",
".",
"setCompressJavaScript",
"(",
"parser",
".",
"getOptionValue",
"(",
"compressJsOpt",
")",
"!=",
"null",
")",
";",
"htmlCompressor",
".",
"setRemoveComments",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveCommentsOpt",
")",
"==",
"null",
")",
";",
"htmlCompressor",
".",
"setRemoveIntertagSpaces",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveIntertagSpacesOpt",
")",
"==",
"null",
")",
";",
"htmlCompressor",
".",
"setPreserveLineBreaks",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveLineBreaksOpt",
")",
"!=",
"null",
")",
";",
"htmlCompressor",
".",
"setRemoveMultiSpaces",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveMultiSpacesOpt",
")",
"==",
"null",
")",
";",
"htmlCompressor",
".",
"setRemoveQuotes",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveQuotesOpt",
")",
"==",
"null",
")",
";",
"htmlCompressor",
".",
"setYuiCssLineBreak",
"(",
"lineBreakPos",
")",
";",
"htmlCompressor",
".",
"setYuiJsDisableOptimizations",
"(",
"parser",
".",
"getOptionValue",
"(",
"disableOptimizationsOpt",
")",
"!=",
"null",
")",
";",
"htmlCompressor",
".",
"setYuiJsLineBreak",
"(",
"lineBreakPos",
")",
";",
"htmlCompressor",
".",
"setYuiJsNoMunge",
"(",
"parser",
".",
"getOptionValue",
"(",
"nomungeOpt",
")",
"!=",
"null",
")",
";",
"htmlCompressor",
".",
"setYuiJsPreserveAllSemiColons",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveSemiOpt",
")",
"!=",
"null",
")",
";",
"}",
"public",
"String",
"compress",
"(",
"String",
"input",
")",
"throws",
"IOException",
"{",
"return",
"htmlCompressor",
".",
"compress",
"(",
"input",
")",
";",
"}",
"}",
"private",
"static",
"class",
"CompressorJs",
"implements",
"Compressor",
"{",
"public",
"String",
"compress",
"(",
"String",
"input",
")",
"throws",
"IOException",
"{",
"JavaScriptCompressor",
"javaScriptCompressor",
"=",
"new",
"JavaScriptCompressor",
"(",
"new",
"StringReader",
"(",
"input",
")",
",",
"new",
"ErrorReporter",
"(",
")",
"{",
"public",
"void",
"warning",
"(",
"String",
"message",
",",
"String",
"sourceName",
",",
"int",
"line",
",",
"String",
"lineSource",
",",
"int",
"lineOffset",
")",
"{",
"if",
"(",
"line",
"<",
"0",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"",
"\\n",
"[WARNING] ",
"\"",
"+",
"message",
")",
";",
"}",
"else",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"",
"\\n",
"[WARNING] ",
"\"",
"+",
"line",
"+",
"':'",
"+",
"lineOffset",
"+",
"':'",
"+",
"message",
")",
";",
"}",
"}",
"public",
"void",
"error",
"(",
"String",
"message",
",",
"String",
"sourceName",
",",
"int",
"line",
",",
"String",
"lineSource",
",",
"int",
"lineOffset",
")",
"{",
"if",
"(",
"line",
"<",
"0",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"",
"\\n",
"[ERROR] ",
"\"",
"+",
"message",
")",
";",
"}",
"else",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"",
"\\n",
"[ERROR] ",
"\"",
"+",
"line",
"+",
"':'",
"+",
"lineOffset",
"+",
"':'",
"+",
"message",
")",
";",
"}",
"}",
"public",
"EvaluatorException",
"runtimeError",
"(",
"String",
"message",
",",
"String",
"sourceName",
",",
"int",
"line",
",",
"String",
"lineSource",
",",
"int",
"lineOffset",
")",
"{",
"error",
"(",
"message",
",",
"sourceName",
",",
"line",
",",
"lineSource",
",",
"lineOffset",
")",
";",
"return",
"new",
"EvaluatorException",
"(",
"message",
")",
";",
"}",
"}",
")",
";",
"boolean",
"nomunge",
"=",
"(",
"parser",
".",
"getOptionValue",
"(",
"nomungeOpt",
")",
"!=",
"null",
")",
";",
"boolean",
"preserveSemi",
"=",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveSemiOpt",
")",
"!=",
"null",
")",
";",
"boolean",
"disableOptimizations",
"=",
"(",
"parser",
".",
"getOptionValue",
"(",
"disableOptimizationsOpt",
")",
"!=",
"null",
")",
";",
"StringWriter",
"writer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"javaScriptCompressor",
".",
"compress",
"(",
"writer",
",",
"lineBreakPos",
",",
"!",
"nomunge",
",",
"false",
",",
"preserveSemi",
",",
"disableOptimizations",
")",
";",
"return",
"writer",
".",
"toString",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"CompressorXml",
"implements",
"Compressor",
"{",
"private",
"XmlCompressor",
"xmlCompressor",
"=",
"new",
"XmlCompressor",
"(",
")",
";",
"public",
"CompressorXml",
"(",
")",
"{",
"xmlCompressor",
".",
"setRemoveComments",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveCommentsOpt",
")",
"==",
"null",
")",
";",
"xmlCompressor",
".",
"setRemoveIntertagSpaces",
"(",
"parser",
".",
"getOptionValue",
"(",
"preserveIntertagSpacesOpt",
")",
"==",
"null",
")",
";",
"}",
"public",
"String",
"compress",
"(",
"String",
"input",
")",
"throws",
"IOException",
"{",
"return",
"xmlCompressor",
".",
"compress",
"(",
"input",
")",
";",
"}",
"}",
"private",
"static",
"CompressorCss",
"compressorCss",
"=",
"null",
";",
"private",
"static",
"CompressorHtml",
"compressorHtml",
"=",
"null",
";",
"private",
"static",
"CompressorJs",
"compressorJs",
"=",
"null",
";",
"private",
"static",
"CompressorXml",
"compressorXml",
"=",
"null",
";",
"private",
"static",
"void",
"compress",
"(",
"File",
"file",
")",
"throws",
"IOException",
"{",
"if",
"(",
"file",
".",
"isDirectory",
"(",
")",
")",
"{",
"File",
"[",
"]",
"files",
"=",
"file",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"files",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"++",
"i",
")",
"{",
"compress",
"(",
"files",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"else",
"{",
"String",
"fileName",
"=",
"file",
".",
"getName",
"(",
")",
";",
"int",
"fileDotIndex",
"=",
"fileName",
".",
"lastIndexOf",
"(",
"'.'",
")",
";",
"if",
"(",
"fileDotIndex",
">",
"0",
"&&",
"fileDotIndex",
"+",
"1",
"<",
"fileName",
".",
"length",
"(",
")",
")",
"{",
"String",
"fileExtension",
"=",
"fileName",
".",
"substring",
"(",
"fileDotIndex",
"+",
"1",
")",
";",
"Compressor",
"compressor",
"=",
"null",
";",
"if",
"(",
"\"",
"css",
"\"",
".",
"equalsIgnoreCase",
"(",
"fileExtension",
")",
")",
"{",
"if",
"(",
"compressorCss",
"==",
"null",
")",
"{",
"compressorCss",
"=",
"new",
"CompressorCss",
"(",
")",
";",
"}",
"compressor",
"=",
"compressorCss",
";",
"}",
"else",
"if",
"(",
"\"",
"html",
"\"",
".",
"equalsIgnoreCase",
"(",
"fileExtension",
")",
")",
"{",
"if",
"(",
"compressorHtml",
"==",
"null",
")",
"{",
"compressorHtml",
"=",
"new",
"CompressorHtml",
"(",
")",
";",
"}",
"compressor",
"=",
"compressorHtml",
";",
"}",
"else",
"if",
"(",
"\"",
"js",
"\"",
".",
"equalsIgnoreCase",
"(",
"fileExtension",
")",
")",
"{",
"if",
"(",
"compressorJs",
"==",
"null",
")",
"{",
"compressorJs",
"=",
"new",
"CompressorJs",
"(",
")",
";",
"}",
"compressor",
"=",
"compressorJs",
";",
"}",
"else",
"if",
"(",
"\"",
"xml",
"\"",
".",
"equalsIgnoreCase",
"(",
"fileExtension",
")",
")",
"{",
"if",
"(",
"compressorXml",
"==",
"null",
")",
"{",
"compressorXml",
"=",
"new",
"CompressorXml",
"(",
")",
";",
"}",
"compressor",
"=",
"compressorXml",
";",
"}",
"if",
"(",
"compressor",
"!=",
"null",
")",
"{",
"StringBuilder",
"input",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"InputStream",
"fileInputStream",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
";",
"BufferedReader",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"fileInputStream",
",",
"charset",
")",
")",
";",
"try",
"{",
"String",
"line",
";",
"String",
"lineSeparator",
"=",
"System",
".",
"getProperty",
"(",
"\"",
"line.separator",
"\"",
")",
";",
"while",
"(",
"(",
"line",
"=",
"reader",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"input",
".",
"append",
"(",
"line",
")",
";",
"input",
".",
"append",
"(",
"lineSeparator",
")",
";",
"}",
"}",
"finally",
"{",
"reader",
".",
"close",
"(",
")",
";",
"}",
"String",
"output",
"=",
"compressor",
".",
"compress",
"(",
"input",
".",
"toString",
"(",
")",
")",
";",
"OutputStreamWriter",
"writer",
"=",
"new",
"OutputStreamWriter",
"(",
"new",
"FileOutputStream",
"(",
"file",
")",
",",
"charset",
")",
";",
"try",
"{",
"writer",
".",
"write",
"(",
"output",
")",
";",
"}",
"finally",
"{",
"writer",
".",
"close",
"(",
")",
";",
"}",
"}",
"}",
"}",
"}",
"private",
"static",
"void",
"printUsage",
"(",
"PrintStream",
"s",
")",
"{",
"s",
".",
"println",
"(",
"\"",
"\"",
"+",
"\"",
"Usage: java -jar websitecompressor.jar [options] [files]",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"<files or folders> The files are compressed in-place",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"Global Options:",
"\\n",
"\"",
"+",
"\"",
" --charset <charset> Read the input files using <charset>",
"\\n",
"\"",
"+",
"\"",
" -h, --help Print this screen",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"CSS Compression Options:",
"\\n",
"\"",
"+",
"\"",
" --line-break <column> Insert a line break after the specified column number",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"HTML Compression Options:",
"\\n",
"\"",
"+",
"\"",
" --compress-css Enable inline CSS compression",
"\\n",
"\"",
"+",
"\"",
" --compress-js Enable inline JavaScript compression",
"\\n",
"\"",
"+",
"\"",
" --preserve-comments Preserve comments",
"\\n",
"\"",
"+",
"\"",
" --preserve-intertag-spaces Preserve intertag spaces",
"\\n",
"\"",
"+",
"\"",
" --preserve-line-breaks Preserve line breaks",
"\\n",
"\"",
"+",
"\"",
" --preserve-multi-spaces Preserve multiple spaces",
"\\n",
"\"",
"+",
"\"",
" --preserve-quotes Preserve unneeded quotes",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"JavaScript Compression Options:",
"\\n",
"\"",
"+",
"\"",
" --disable-optimizations Disable all micro optimizations",
"\\n",
"\"",
"+",
"\"",
" --line-break <column> Insert a line break after the specified column number",
"\\n",
"\"",
"+",
"\"",
" --nomunge Minify only, do not obfuscate",
"\\n",
"\"",
"+",
"\"",
" --preserve-semi Preserve all semicolons",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"XML Compression Options:",
"\\n",
"\"",
"+",
"\"",
" --preserve-comments Preserve comments",
"\\n",
"\"",
"+",
"\"",
" --preserve-intertag-spaces Preserve intertag spaces",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"Please note that additional HTML Compressor and YUI Compressor jar",
"\\n",
"\"",
"+",
"\"",
"files must be present in the same directory as this jar file.",
"\"",
"+",
"\"",
"\"",
")",
";",
"}",
"}"
] | Wrapper for website compression tools <code>htmlcompressor</code>
and <code>yuicompressor</code>. | [
"Wrapper",
"for",
"website",
"compression",
"tools",
"<code",
">",
"htmlcompressor<",
"/",
"code",
">",
"and",
"<code",
">",
"yuicompressor<",
"/",
"code",
">",
"."
] | [
"// help",
"// charset",
"// line-break",
"// Compress all files and folders",
"// Read the input from the file",
"// Compress the file content",
"// Write the output to the file"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
feb0fee55fc0acc523983b41ac74c4ab76fd454f | letatanhhuy/braintree_android | Braintree/src/main/java/com/braintreepayments/api/models/PayPalRequest.java | [
"MIT"
] | Java | PayPalRequest | /**
* Represents the parameters that are needed to start a Checkout with PayPal
*
* In the checkout flow, the user is presented with details about the order and only agrees to a
* single payment. The result is not eligible for being saved in the Vault; however, you will receive
* shipping information and the user will not be able to revoke the consent.
*
* @see <a href="https://developer.paypal.com/docs/api/#inputfields-object">PayPal REST API Reference</a>
*/ | Represents the parameters that are needed to start a Checkout with PayPal
In the checkout flow, the user is presented with details about the order and only agrees to a
single payment. The result is not eligible for being saved in the Vault; however, you will receive
shipping information and the user will not be able to revoke the consent.
@see PayPal REST API Reference | [
"Represents",
"the",
"parameters",
"that",
"are",
"needed",
"to",
"start",
"a",
"Checkout",
"with",
"PayPal",
"In",
"the",
"checkout",
"flow",
"the",
"user",
"is",
"presented",
"with",
"details",
"about",
"the",
"order",
"and",
"only",
"agrees",
"to",
"a",
"single",
"payment",
".",
"The",
"result",
"is",
"not",
"eligible",
"for",
"being",
"saved",
"in",
"the",
"Vault",
";",
"however",
"you",
"will",
"receive",
"shipping",
"information",
"and",
"the",
"user",
"will",
"not",
"be",
"able",
"to",
"revoke",
"the",
"consent",
".",
"@see",
"PayPal",
"REST",
"API",
"Reference"
] | public class PayPalRequest implements Parcelable {
@Retention(RetentionPolicy.SOURCE)
@StringDef({PayPalRequest.INTENT_ORDER, PayPalRequest.INTENT_SALE, PayPalRequest.INTENT_AUTHORIZE})
@interface PayPalPaymentIntent {}
public static final String INTENT_ORDER = "order";
public static final String INTENT_SALE = "sale";
public static final String INTENT_AUTHORIZE = "authorize";
@Retention(RetentionPolicy.SOURCE)
@StringDef({PayPalRequest.LANDING_PAGE_TYPE_BILLING, PayPalRequest.LANDING_PAGE_TYPE_LOGIN})
@interface PayPalLandingPageType {}
/**
* A non-PayPal account landing page is used.
*/
public static final String LANDING_PAGE_TYPE_BILLING = "billing";
/**
* A PayPal account login page is used.
*/
public static final String LANDING_PAGE_TYPE_LOGIN = "login";
@Retention(RetentionPolicy.SOURCE)
@StringDef({PayPalRequest.USER_ACTION_DEFAULT, PayPalRequest.USER_ACTION_COMMIT})
@interface PayPalPaymentUserAction {}
/**
* Shows the default call-to-action text on the PayPal Express Checkout page. This option indicates that a final
* confirmation will be shown on the merchant checkout site before the user's payment method is charged.
*/
public static final String USER_ACTION_DEFAULT = "";
/**
* Shows a deterministic call-to-action. This option indicates to the user that their payment method will be charged
* when they click the call-to-action button on the PayPal Checkout page, and that no final confirmation page will
* be shown on the merchant's checkout page. This option works for both checkout and vault flows.
*/
public static final String USER_ACTION_COMMIT = "commit";
private String mAmount;
private String mCurrencyCode;
private String mLocaleCode;
private String mBillingAgreementDescription;
private boolean mShippingAddressRequired;
private boolean mShippingAddressEditable = false;
private PostalAddress mShippingAddressOverride;
private String mIntent = INTENT_AUTHORIZE;
private String mLandingPageType;
private String mUserAction = USER_ACTION_DEFAULT;
private String mDisplayName;
private boolean mOfferCredit;
private String mMerchantAccountId;
private ArrayList<PayPalLineItem> mLineItems = new ArrayList<>();
/**
* Constructs a description of a PayPal checkout for Single Payment and Billing Agreements.
*
* @note This amount may differ slight from the transaction amount. The exact decline rules
* for mismatches between this client-side amount and the final amount in the Transaction
* are determined by the gateway.
*
* @param amount The transaction amount in currency units (as
* determined by setCurrencyCode). For example, "1.20" corresponds to one dollar and twenty cents.
* Amount must be a non-negative number, may optionally contain exactly 2 decimal places separated
* by '.', optional thousands separator ',', limited to 7 digits before the decimal point.
*/
public PayPalRequest(String amount) {
mAmount = amount;
mShippingAddressRequired = false;
mOfferCredit = false;
}
/**
* Constructs a {@link PayPalRequest} with a null amount.
*/
public PayPalRequest() {
mAmount = null;
mShippingAddressRequired = false;
mOfferCredit = false;
}
/**
* Optional: A valid ISO currency code to use for the transaction. Defaults to merchant currency
* code if not set.
*
* If unspecified, the currency code will be chosen based on the active merchant account in the
* client token.
*
* @param currencyCode A currency code, such as "USD"
*/
public PayPalRequest currencyCode(String currencyCode) {
mCurrencyCode = currencyCode;
return this;
}
/**
* Defaults to false. When set to true, the shipping address selector will be displayed.
*
* @param shippingAddressRequired Whether to hide the shipping address in the flow.
*/
public PayPalRequest shippingAddressRequired(boolean shippingAddressRequired) {
mShippingAddressRequired = shippingAddressRequired;
return this;
}
/**
* Defaults to false. Set to true to enable user editing of the shipping address.
* Only applies when {@link PayPalRequest#shippingAddressOverride(PostalAddress)} is set
* with a {@link PostalAddress}.
*
* @param shippingAddressEditable Whether to allow the the shipping address to be editable.
*/
public PayPalRequest shippingAddressEditable(boolean shippingAddressEditable) {
mShippingAddressEditable = shippingAddressEditable;
return this;
}
/**
* Whether to use a custom locale code.
* <br>
* Supported locales are:
* <br>
* <code>da_DK</code>,
* <code>de_DE</code>,
* <code>en_AU</code>,
* <code>en_GB</code>,
* <code>en_US</code>,
* <code>es_ES</code>,
* <code>es_XC</code>,
* <code>fr_CA</code>,
* <code>fr_FR</code>,
* <code>fr_XC</code>,
* <code>id_ID</code>,
* <code>it_IT</code>,
* <code>ja_JP</code>,
* <code>ko_KR</code>,
* <code>nl_NL</code>,
* <code>no_NO</code>,
* <code>pl_PL</code>,
* <code>pt_BR</code>,
* <code>pt_PT</code>,
* <code>ru_RU</code>,
* <code>sv_SE</code>,
* <code>th_TH</code>,
* <code>tr_TR</code>,
* <code>zh_CN</code>,
* <code>zh_HK</code>,
* <code>zh_TW</code>,
* <code>zh_XC</code>.
*
* @param localeCode Whether to use a custom locale code.
*/
public PayPalRequest localeCode(String localeCode) {
mLocaleCode = localeCode;
return this;
}
/**
* The merchant name displayed in the PayPal flow; defaults to the company name on your Braintree account.
*
* @param displayName The name to be displayed in the PayPal flow.
*/
public PayPalRequest displayName(String displayName) {
mDisplayName = displayName;
return this;
}
/**
* Display a custom description to the user for a billing agreement.
*
* @param description The description to display.
*/
public PayPalRequest billingAgreementDescription(String description) {
mBillingAgreementDescription = description;
return this;
}
/**
* A custom shipping address to be used for the checkout flow.
*
* @param shippingAddressOverride a custom {@link PostalAddress}
*/
public PayPalRequest shippingAddressOverride(PostalAddress shippingAddressOverride) {
mShippingAddressOverride = shippingAddressOverride;
return this;
}
/**
* Payment intent. Must be set to {@link #INTENT_SALE} for immediate payment,
* {@link #INTENT_AUTHORIZE} to authorize a payment for capture later, or
* {@link #INTENT_ORDER} to create an order.
*
* Defaults to authorize. Only works in the Single Payment flow.
*
* @param intent Must be a {@link PayPalPaymentIntent} value:
* <ul>
* <li>{@link PayPalRequest#INTENT_AUTHORIZE} to authorize a payment for capture later </li>
* <li>{@link PayPalRequest#INTENT_ORDER} to create an order </li>
* <li>{@link PayPalRequest#INTENT_SALE} for immediate payment </li>
* </ul>
*
* @see <a href="https://developer.paypal.com/docs/api/payments/v1/#definition-payment">"intent" under the "payment" definition</a>
* @see <a href="https://developer.paypal.com/docs/integration/direct/payments/create-process-order/">Create and process orders</a>
* for more information
*
*/
public PayPalRequest intent(@PayPalPaymentIntent String intent) {
mIntent = intent;
return this;
}
/**
* Use this option to specify the PayPal page to display when a user lands on the PayPal site to complete the payment.
*
* @param landingPageType Must be a {@link PayPalLandingPageType} value:
* <ul>
* <li>{@link #LANDING_PAGE_TYPE_BILLING}</li>
* <li>{@link #LANDING_PAGE_TYPE_LOGIN}</li>
*
* @see <a href="https://developer.paypal.com/docs/api/payments/v1/#definition-application_context">See "landing_page" under the "application_context" definition</a>
*/
public PayPalRequest landingPageType(@PayPalLandingPageType String landingPageType) {
mLandingPageType = landingPageType;
return this;
}
/**
* Set the checkout user action which determines the button text.
*
* @param userAction Must be a be {@link PayPalPaymentUserAction} value:
* <ul>
* <li>{@link #USER_ACTION_COMMIT}</li>
* <li>{@link #USER_ACTION_DEFAULT}</li>
* </ul>
*
* @see <a href="https://developer.paypal.com/docs/api/payments/v1/#definition-application_context">See "user_action" under the "application_context" definition</a>
*/
public PayPalRequest userAction(@PayPalPaymentUserAction String userAction) {
mUserAction = userAction;
return this;
}
/**
* Offers PayPal Credit prominently in the payment flow. Defaults to false. Only available with Billing Agreements
* and PayPal Checkout.
*
* @param offerCredit Whether to offer PayPal Credit.
*/
public PayPalRequest offerCredit(boolean offerCredit) {
mOfferCredit = offerCredit;
return this;
}
/**
* Specify a merchant account Id other than the default to use during tokenization.
*
* @param merchantAccountId the non-default merchant account Id.
*/
public PayPalRequest merchantAccountId(String merchantAccountId) {
mMerchantAccountId = merchantAccountId;
return this;
}
/**
* The line items for this transaction. It can include up to 249 line items.
*
* @param lineItems a collection of {@link PayPalLineItem}
*/
public PayPalRequest lineItems(Collection<PayPalLineItem> lineItems) {
mLineItems.clear();
mLineItems.addAll(lineItems);
return this;
}
public String getAmount() {
return mAmount;
}
public String getCurrencyCode() {
return mCurrencyCode;
}
public String getLocaleCode() {
return mLocaleCode;
}
public String getBillingAgreementDescription() {
return mBillingAgreementDescription;
}
public boolean isShippingAddressRequired() {
return mShippingAddressRequired;
}
public boolean isShippingAddressEditable() {
return mShippingAddressEditable;
}
public PostalAddress getShippingAddressOverride() {
return mShippingAddressOverride;
}
public String getDisplayName() {
return mDisplayName;
}
public boolean shouldOfferCredit() {
return mOfferCredit;
}
public String getMerchantAccountId() {
return mMerchantAccountId;
}
public ArrayList<PayPalLineItem> getLineItems() {
return mLineItems;
}
@PayPalPaymentIntent
public String getIntent() {
return mIntent;
}
@PayPalLandingPageType
public String getLandingPageType() {
return mLandingPageType;
}
@PayPalPaymentUserAction
public String getUserAction() {
return mUserAction;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mAmount);
parcel.writeString(mCurrencyCode);
parcel.writeString(mLocaleCode);
parcel.writeString(mBillingAgreementDescription);
parcel.writeByte(mShippingAddressRequired ? (byte) 1:0);
parcel.writeByte(mShippingAddressEditable ? (byte) 1:0);
parcel.writeParcelable(mShippingAddressOverride, i);
parcel.writeString(mIntent);
parcel.writeString(mLandingPageType);
parcel.writeString(mUserAction);
parcel.writeString(mDisplayName);
parcel.writeByte(mOfferCredit ? (byte) 1:0);
parcel.writeString(mMerchantAccountId);
parcel.writeList(mLineItems);
}
public PayPalRequest(Parcel in) {
mAmount = in.readString();
mCurrencyCode = in.readString();
mLocaleCode = in.readString();
mBillingAgreementDescription = in.readString();
mShippingAddressRequired = in.readByte() > 0;
mShippingAddressEditable = in.readByte() > 0;
mShippingAddressOverride = in.readParcelable(PostalAddress.class.getClassLoader());
mIntent = in.readString();
mLandingPageType = in.readString();
mUserAction = in.readString();
mDisplayName = in.readString();
mOfferCredit = in.readByte() > 0;
mMerchantAccountId = in.readString();
mLineItems = in.readArrayList(PayPalLineItem.class.getClassLoader());
}
public static final Creator<PayPalRequest> CREATOR = new Creator<PayPalRequest>() {
@Override
public PayPalRequest createFromParcel(Parcel in) {
return new PayPalRequest(in);
}
@Override
public PayPalRequest[] newArray(int size) {
return new PayPalRequest[size];
}
};
} | [
"public",
"class",
"PayPalRequest",
"implements",
"Parcelable",
"{",
"@",
"Retention",
"(",
"RetentionPolicy",
".",
"SOURCE",
")",
"@",
"StringDef",
"(",
"{",
"PayPalRequest",
".",
"INTENT_ORDER",
",",
"PayPalRequest",
".",
"INTENT_SALE",
",",
"PayPalRequest",
".",
"INTENT_AUTHORIZE",
"}",
")",
"@interface",
"PayPalPaymentIntent",
"{",
"}",
"public",
"static",
"final",
"String",
"INTENT_ORDER",
"=",
"\"",
"order",
"\"",
";",
"public",
"static",
"final",
"String",
"INTENT_SALE",
"=",
"\"",
"sale",
"\"",
";",
"public",
"static",
"final",
"String",
"INTENT_AUTHORIZE",
"=",
"\"",
"authorize",
"\"",
";",
"@",
"Retention",
"(",
"RetentionPolicy",
".",
"SOURCE",
")",
"@",
"StringDef",
"(",
"{",
"PayPalRequest",
".",
"LANDING_PAGE_TYPE_BILLING",
",",
"PayPalRequest",
".",
"LANDING_PAGE_TYPE_LOGIN",
"}",
")",
"@interface",
"PayPalLandingPageType",
"{",
"}",
"/**\n * A non-PayPal account landing page is used.\n */",
"public",
"static",
"final",
"String",
"LANDING_PAGE_TYPE_BILLING",
"=",
"\"",
"billing",
"\"",
";",
"/**\n * A PayPal account login page is used.\n */",
"public",
"static",
"final",
"String",
"LANDING_PAGE_TYPE_LOGIN",
"=",
"\"",
"login",
"\"",
";",
"@",
"Retention",
"(",
"RetentionPolicy",
".",
"SOURCE",
")",
"@",
"StringDef",
"(",
"{",
"PayPalRequest",
".",
"USER_ACTION_DEFAULT",
",",
"PayPalRequest",
".",
"USER_ACTION_COMMIT",
"}",
")",
"@interface",
"PayPalPaymentUserAction",
"{",
"}",
"/**\n * Shows the default call-to-action text on the PayPal Express Checkout page. This option indicates that a final\n * confirmation will be shown on the merchant checkout site before the user's payment method is charged.\n */",
"public",
"static",
"final",
"String",
"USER_ACTION_DEFAULT",
"=",
"\"",
"\"",
";",
"/**\n * Shows a deterministic call-to-action. This option indicates to the user that their payment method will be charged\n * when they click the call-to-action button on the PayPal Checkout page, and that no final confirmation page will\n * be shown on the merchant's checkout page. This option works for both checkout and vault flows.\n */",
"public",
"static",
"final",
"String",
"USER_ACTION_COMMIT",
"=",
"\"",
"commit",
"\"",
";",
"private",
"String",
"mAmount",
";",
"private",
"String",
"mCurrencyCode",
";",
"private",
"String",
"mLocaleCode",
";",
"private",
"String",
"mBillingAgreementDescription",
";",
"private",
"boolean",
"mShippingAddressRequired",
";",
"private",
"boolean",
"mShippingAddressEditable",
"=",
"false",
";",
"private",
"PostalAddress",
"mShippingAddressOverride",
";",
"private",
"String",
"mIntent",
"=",
"INTENT_AUTHORIZE",
";",
"private",
"String",
"mLandingPageType",
";",
"private",
"String",
"mUserAction",
"=",
"USER_ACTION_DEFAULT",
";",
"private",
"String",
"mDisplayName",
";",
"private",
"boolean",
"mOfferCredit",
";",
"private",
"String",
"mMerchantAccountId",
";",
"private",
"ArrayList",
"<",
"PayPalLineItem",
">",
"mLineItems",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"/**\n * Constructs a description of a PayPal checkout for Single Payment and Billing Agreements.\n *\n * @note This amount may differ slight from the transaction amount. The exact decline rules\n * for mismatches between this client-side amount and the final amount in the Transaction\n * are determined by the gateway.\n *\n * @param amount The transaction amount in currency units (as\n * determined by setCurrencyCode). For example, \"1.20\" corresponds to one dollar and twenty cents.\n * Amount must be a non-negative number, may optionally contain exactly 2 decimal places separated\n * by '.', optional thousands separator ',', limited to 7 digits before the decimal point.\n */",
"public",
"PayPalRequest",
"(",
"String",
"amount",
")",
"{",
"mAmount",
"=",
"amount",
";",
"mShippingAddressRequired",
"=",
"false",
";",
"mOfferCredit",
"=",
"false",
";",
"}",
"/**\n * Constructs a {@link PayPalRequest} with a null amount.\n */",
"public",
"PayPalRequest",
"(",
")",
"{",
"mAmount",
"=",
"null",
";",
"mShippingAddressRequired",
"=",
"false",
";",
"mOfferCredit",
"=",
"false",
";",
"}",
"/**\n * Optional: A valid ISO currency code to use for the transaction. Defaults to merchant currency\n * code if not set.\n *\n * If unspecified, the currency code will be chosen based on the active merchant account in the\n * client token.\n *\n * @param currencyCode A currency code, such as \"USD\"\n */",
"public",
"PayPalRequest",
"currencyCode",
"(",
"String",
"currencyCode",
")",
"{",
"mCurrencyCode",
"=",
"currencyCode",
";",
"return",
"this",
";",
"}",
"/**\n * Defaults to false. When set to true, the shipping address selector will be displayed.\n *\n * @param shippingAddressRequired Whether to hide the shipping address in the flow.\n */",
"public",
"PayPalRequest",
"shippingAddressRequired",
"(",
"boolean",
"shippingAddressRequired",
")",
"{",
"mShippingAddressRequired",
"=",
"shippingAddressRequired",
";",
"return",
"this",
";",
"}",
"/**\n * Defaults to false. Set to true to enable user editing of the shipping address.\n * Only applies when {@link PayPalRequest#shippingAddressOverride(PostalAddress)} is set\n * with a {@link PostalAddress}.\n *\n * @param shippingAddressEditable Whether to allow the the shipping address to be editable.\n */",
"public",
"PayPalRequest",
"shippingAddressEditable",
"(",
"boolean",
"shippingAddressEditable",
")",
"{",
"mShippingAddressEditable",
"=",
"shippingAddressEditable",
";",
"return",
"this",
";",
"}",
"/**\n * Whether to use a custom locale code.\n * <br>\n * Supported locales are:\n * <br>\n * <code>da_DK</code>,\n * <code>de_DE</code>,\n * <code>en_AU</code>,\n * <code>en_GB</code>,\n * <code>en_US</code>,\n * <code>es_ES</code>,\n * <code>es_XC</code>,\n * <code>fr_CA</code>,\n * <code>fr_FR</code>,\n * <code>fr_XC</code>,\n * <code>id_ID</code>,\n * <code>it_IT</code>,\n * <code>ja_JP</code>,\n * <code>ko_KR</code>,\n * <code>nl_NL</code>,\n * <code>no_NO</code>,\n * <code>pl_PL</code>,\n * <code>pt_BR</code>,\n * <code>pt_PT</code>,\n * <code>ru_RU</code>,\n * <code>sv_SE</code>,\n * <code>th_TH</code>,\n * <code>tr_TR</code>,\n * <code>zh_CN</code>,\n * <code>zh_HK</code>,\n * <code>zh_TW</code>,\n * <code>zh_XC</code>.\n *\n * @param localeCode Whether to use a custom locale code.\n */",
"public",
"PayPalRequest",
"localeCode",
"(",
"String",
"localeCode",
")",
"{",
"mLocaleCode",
"=",
"localeCode",
";",
"return",
"this",
";",
"}",
"/**\n * The merchant name displayed in the PayPal flow; defaults to the company name on your Braintree account.\n *\n * @param displayName The name to be displayed in the PayPal flow.\n */",
"public",
"PayPalRequest",
"displayName",
"(",
"String",
"displayName",
")",
"{",
"mDisplayName",
"=",
"displayName",
";",
"return",
"this",
";",
"}",
"/**\n * Display a custom description to the user for a billing agreement.\n *\n * @param description The description to display.\n */",
"public",
"PayPalRequest",
"billingAgreementDescription",
"(",
"String",
"description",
")",
"{",
"mBillingAgreementDescription",
"=",
"description",
";",
"return",
"this",
";",
"}",
"/**\n * A custom shipping address to be used for the checkout flow.\n *\n * @param shippingAddressOverride a custom {@link PostalAddress}\n */",
"public",
"PayPalRequest",
"shippingAddressOverride",
"(",
"PostalAddress",
"shippingAddressOverride",
")",
"{",
"mShippingAddressOverride",
"=",
"shippingAddressOverride",
";",
"return",
"this",
";",
"}",
"/**\n * Payment intent. Must be set to {@link #INTENT_SALE} for immediate payment,\n * {@link #INTENT_AUTHORIZE} to authorize a payment for capture later, or\n * {@link #INTENT_ORDER} to create an order.\n *\n * Defaults to authorize. Only works in the Single Payment flow.\n *\n * @param intent Must be a {@link PayPalPaymentIntent} value:\n * <ul>\n * <li>{@link PayPalRequest#INTENT_AUTHORIZE} to authorize a payment for capture later </li>\n * <li>{@link PayPalRequest#INTENT_ORDER} to create an order </li>\n * <li>{@link PayPalRequest#INTENT_SALE} for immediate payment </li>\n * </ul>\n *\n * @see <a href=\"https://developer.paypal.com/docs/api/payments/v1/#definition-payment\">\"intent\" under the \"payment\" definition</a>\n * @see <a href=\"https://developer.paypal.com/docs/integration/direct/payments/create-process-order/\">Create and process orders</a>\n * for more information\n *\n */",
"public",
"PayPalRequest",
"intent",
"(",
"@",
"PayPalPaymentIntent",
"String",
"intent",
")",
"{",
"mIntent",
"=",
"intent",
";",
"return",
"this",
";",
"}",
"/**\n * Use this option to specify the PayPal page to display when a user lands on the PayPal site to complete the payment.\n *\n * @param landingPageType Must be a {@link PayPalLandingPageType} value:\n * <ul>\n * <li>{@link #LANDING_PAGE_TYPE_BILLING}</li>\n * <li>{@link #LANDING_PAGE_TYPE_LOGIN}</li>\n *\n * @see <a href=\"https://developer.paypal.com/docs/api/payments/v1/#definition-application_context\">See \"landing_page\" under the \"application_context\" definition</a>\n */",
"public",
"PayPalRequest",
"landingPageType",
"(",
"@",
"PayPalLandingPageType",
"String",
"landingPageType",
")",
"{",
"mLandingPageType",
"=",
"landingPageType",
";",
"return",
"this",
";",
"}",
"/**\n * Set the checkout user action which determines the button text.\n *\n * @param userAction Must be a be {@link PayPalPaymentUserAction} value:\n * <ul>\n * <li>{@link #USER_ACTION_COMMIT}</li>\n * <li>{@link #USER_ACTION_DEFAULT}</li>\n * </ul>\n *\n * @see <a href=\"https://developer.paypal.com/docs/api/payments/v1/#definition-application_context\">See \"user_action\" under the \"application_context\" definition</a>\n */",
"public",
"PayPalRequest",
"userAction",
"(",
"@",
"PayPalPaymentUserAction",
"String",
"userAction",
")",
"{",
"mUserAction",
"=",
"userAction",
";",
"return",
"this",
";",
"}",
"/**\n * Offers PayPal Credit prominently in the payment flow. Defaults to false. Only available with Billing Agreements\n * and PayPal Checkout.\n *\n * @param offerCredit Whether to offer PayPal Credit.\n */",
"public",
"PayPalRequest",
"offerCredit",
"(",
"boolean",
"offerCredit",
")",
"{",
"mOfferCredit",
"=",
"offerCredit",
";",
"return",
"this",
";",
"}",
"/**\n * Specify a merchant account Id other than the default to use during tokenization.\n *\n * @param merchantAccountId the non-default merchant account Id.\n */",
"public",
"PayPalRequest",
"merchantAccountId",
"(",
"String",
"merchantAccountId",
")",
"{",
"mMerchantAccountId",
"=",
"merchantAccountId",
";",
"return",
"this",
";",
"}",
"/**\n * The line items for this transaction. It can include up to 249 line items.\n *\n * @param lineItems a collection of {@link PayPalLineItem}\n */",
"public",
"PayPalRequest",
"lineItems",
"(",
"Collection",
"<",
"PayPalLineItem",
">",
"lineItems",
")",
"{",
"mLineItems",
".",
"clear",
"(",
")",
";",
"mLineItems",
".",
"addAll",
"(",
"lineItems",
")",
";",
"return",
"this",
";",
"}",
"public",
"String",
"getAmount",
"(",
")",
"{",
"return",
"mAmount",
";",
"}",
"public",
"String",
"getCurrencyCode",
"(",
")",
"{",
"return",
"mCurrencyCode",
";",
"}",
"public",
"String",
"getLocaleCode",
"(",
")",
"{",
"return",
"mLocaleCode",
";",
"}",
"public",
"String",
"getBillingAgreementDescription",
"(",
")",
"{",
"return",
"mBillingAgreementDescription",
";",
"}",
"public",
"boolean",
"isShippingAddressRequired",
"(",
")",
"{",
"return",
"mShippingAddressRequired",
";",
"}",
"public",
"boolean",
"isShippingAddressEditable",
"(",
")",
"{",
"return",
"mShippingAddressEditable",
";",
"}",
"public",
"PostalAddress",
"getShippingAddressOverride",
"(",
")",
"{",
"return",
"mShippingAddressOverride",
";",
"}",
"public",
"String",
"getDisplayName",
"(",
")",
"{",
"return",
"mDisplayName",
";",
"}",
"public",
"boolean",
"shouldOfferCredit",
"(",
")",
"{",
"return",
"mOfferCredit",
";",
"}",
"public",
"String",
"getMerchantAccountId",
"(",
")",
"{",
"return",
"mMerchantAccountId",
";",
"}",
"public",
"ArrayList",
"<",
"PayPalLineItem",
">",
"getLineItems",
"(",
")",
"{",
"return",
"mLineItems",
";",
"}",
"@",
"PayPalPaymentIntent",
"public",
"String",
"getIntent",
"(",
")",
"{",
"return",
"mIntent",
";",
"}",
"@",
"PayPalLandingPageType",
"public",
"String",
"getLandingPageType",
"(",
")",
"{",
"return",
"mLandingPageType",
";",
"}",
"@",
"PayPalPaymentUserAction",
"public",
"String",
"getUserAction",
"(",
")",
"{",
"return",
"mUserAction",
";",
"}",
"@",
"Override",
"public",
"int",
"describeContents",
"(",
")",
"{",
"return",
"0",
";",
"}",
"@",
"Override",
"public",
"void",
"writeToParcel",
"(",
"Parcel",
"parcel",
",",
"int",
"i",
")",
"{",
"parcel",
".",
"writeString",
"(",
"mAmount",
")",
";",
"parcel",
".",
"writeString",
"(",
"mCurrencyCode",
")",
";",
"parcel",
".",
"writeString",
"(",
"mLocaleCode",
")",
";",
"parcel",
".",
"writeString",
"(",
"mBillingAgreementDescription",
")",
";",
"parcel",
".",
"writeByte",
"(",
"mShippingAddressRequired",
"?",
"(",
"byte",
")",
"1",
":",
"0",
")",
";",
"parcel",
".",
"writeByte",
"(",
"mShippingAddressEditable",
"?",
"(",
"byte",
")",
"1",
":",
"0",
")",
";",
"parcel",
".",
"writeParcelable",
"(",
"mShippingAddressOverride",
",",
"i",
")",
";",
"parcel",
".",
"writeString",
"(",
"mIntent",
")",
";",
"parcel",
".",
"writeString",
"(",
"mLandingPageType",
")",
";",
"parcel",
".",
"writeString",
"(",
"mUserAction",
")",
";",
"parcel",
".",
"writeString",
"(",
"mDisplayName",
")",
";",
"parcel",
".",
"writeByte",
"(",
"mOfferCredit",
"?",
"(",
"byte",
")",
"1",
":",
"0",
")",
";",
"parcel",
".",
"writeString",
"(",
"mMerchantAccountId",
")",
";",
"parcel",
".",
"writeList",
"(",
"mLineItems",
")",
";",
"}",
"public",
"PayPalRequest",
"(",
"Parcel",
"in",
")",
"{",
"mAmount",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mCurrencyCode",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mLocaleCode",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mBillingAgreementDescription",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mShippingAddressRequired",
"=",
"in",
".",
"readByte",
"(",
")",
">",
"0",
";",
"mShippingAddressEditable",
"=",
"in",
".",
"readByte",
"(",
")",
">",
"0",
";",
"mShippingAddressOverride",
"=",
"in",
".",
"readParcelable",
"(",
"PostalAddress",
".",
"class",
".",
"getClassLoader",
"(",
")",
")",
";",
"mIntent",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mLandingPageType",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mUserAction",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mDisplayName",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mOfferCredit",
"=",
"in",
".",
"readByte",
"(",
")",
">",
"0",
";",
"mMerchantAccountId",
"=",
"in",
".",
"readString",
"(",
")",
";",
"mLineItems",
"=",
"in",
".",
"readArrayList",
"(",
"PayPalLineItem",
".",
"class",
".",
"getClassLoader",
"(",
")",
")",
";",
"}",
"public",
"static",
"final",
"Creator",
"<",
"PayPalRequest",
">",
"CREATOR",
"=",
"new",
"Creator",
"<",
"PayPalRequest",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"PayPalRequest",
"createFromParcel",
"(",
"Parcel",
"in",
")",
"{",
"return",
"new",
"PayPalRequest",
"(",
"in",
")",
";",
"}",
"@",
"Override",
"public",
"PayPalRequest",
"[",
"]",
"newArray",
"(",
"int",
"size",
")",
"{",
"return",
"new",
"PayPalRequest",
"[",
"size",
"]",
";",
"}",
"}",
";",
"}"
] | Represents the parameters that are needed to start a Checkout with PayPal
In the checkout flow, the user is presented with details about the order and only agrees to a
single payment. | [
"Represents",
"the",
"parameters",
"that",
"are",
"needed",
"to",
"start",
"a",
"Checkout",
"with",
"PayPal",
"In",
"the",
"checkout",
"flow",
"the",
"user",
"is",
"presented",
"with",
"details",
"about",
"the",
"order",
"and",
"only",
"agrees",
"to",
"a",
"single",
"payment",
"."
] | [] | [
{
"param": "Parcelable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Parcelable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
feb3d7642d652aaeb9ecc4e3ba4fd2957fdc5026 | BenFradet/LO23 | src/com/sudoku/grid/preview/StarsBox.java | [
"MIT"
] | Java | StarsBox | /**
* @author marco, groudame, lleichtn
*/ | @author marco, groudame, lleichtn | [
"@author",
"marco",
"groudame",
"lleichtn"
] | public class StarsBox extends HBox implements EventHandler<MouseEvent> {
protected final int maxNumberOfStars;
protected List<StarView> stars = new ArrayList<>();
protected double valueAtClick = 0;
/**
* Constructeur de l'objet liste d etoile pour l' affichage de la note moyenne
* d' une grille ou pour faire une notation
*
* @param numberOfStars
*/
public StarsBox(int numberOfStars) {
maxNumberOfStars = numberOfStars;
for (int i = 0; i < maxNumberOfStars; i++) {
stars.add(new StarView());
getChildren().add(stars.get(i));
}
}
@Override
public void handle(MouseEvent t) {
if (t.isConsumed()) {
return;
}
if (t.getEventType() == MouseEvent.MOUSE_MOVED) {
t.consume();
setValue((double) (t.getX() * maxNumberOfStars) / (double) getWidth() + 0.5);
} else if (t.getEventType() == MouseEvent.MOUSE_CLICKED) {
valueAtClick = (double) (t.getX() * maxNumberOfStars) / (double) getWidth() + 0.5;
} else if (t.getEventType() == MouseEvent.MOUSE_EXITED) {
setValue(valueAtClick);
}
}
/**
* Cette fonction permet de
*
* @param value
*/
public void setValue(double value) {
double newValue = value;
if (value < 0) {
newValue = 0;
}
if (value > maxNumberOfStars) {
newValue = maxNumberOfStars;
}
int i = 0;
for (; i < Math.floor(newValue); i++) {
stars.get(i).setType(StarView.StarTypes.FILLED);
}
if (Math.round(newValue) != Math.floor(newValue)) {
stars.get(i++).setType(StarView.StarTypes.HALF);
}
//add complements empty stars
for (; i < maxNumberOfStars; i++) {
stars.get(i).setType(StarView.StarTypes.EMPTY);
}
}
/*
* Permet de rendre l objet dynamique et autoriser les handlers.
* @param hoverable
*/
public void setHoverable(boolean hoverable) {
if (hoverable) {
addEventHandler(MouseEvent.MOUSE_MOVED, this);
addEventHandler(MouseEvent.MOUSE_CLICKED, this);
addEventHandler(MouseEvent.MOUSE_EXITED, this);
} else {
removeEventHandler(MouseEvent.MOUSE_MOVED, this);
removeEventHandler(MouseEvent.MOUSE_CLICKED, this);
removeEventHandler(MouseEvent.MOUSE_EXITED, this);
}
}
/**
* Retourne la valeur selectionne lors du clic de souris
*
* @return valueAtClick
*/
public double getValueAtClick() {
return valueAtClick;
}
/**
* Reset la valeur de valueAtClick ^pour permettre une nouvelle selection.
*/
public void reset() {
setValue(0);
valueAtClick = 0;
}
} | [
"public",
"class",
"StarsBox",
"extends",
"HBox",
"implements",
"EventHandler",
"<",
"MouseEvent",
">",
"{",
"protected",
"final",
"int",
"maxNumberOfStars",
";",
"protected",
"List",
"<",
"StarView",
">",
"stars",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"protected",
"double",
"valueAtClick",
"=",
"0",
";",
"/**\n * Constructeur de l'objet liste d etoile pour l' affichage de la note moyenne\n * d' une grille ou pour faire une notation\n *\n * @param numberOfStars\n */",
"public",
"StarsBox",
"(",
"int",
"numberOfStars",
")",
"{",
"maxNumberOfStars",
"=",
"numberOfStars",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"maxNumberOfStars",
";",
"i",
"++",
")",
"{",
"stars",
".",
"add",
"(",
"new",
"StarView",
"(",
")",
")",
";",
"getChildren",
"(",
")",
".",
"add",
"(",
"stars",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"handle",
"(",
"MouseEvent",
"t",
")",
"{",
"if",
"(",
"t",
".",
"isConsumed",
"(",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"t",
".",
"getEventType",
"(",
")",
"==",
"MouseEvent",
".",
"MOUSE_MOVED",
")",
"{",
"t",
".",
"consume",
"(",
")",
";",
"setValue",
"(",
"(",
"double",
")",
"(",
"t",
".",
"getX",
"(",
")",
"*",
"maxNumberOfStars",
")",
"/",
"(",
"double",
")",
"getWidth",
"(",
")",
"+",
"0.5",
")",
";",
"}",
"else",
"if",
"(",
"t",
".",
"getEventType",
"(",
")",
"==",
"MouseEvent",
".",
"MOUSE_CLICKED",
")",
"{",
"valueAtClick",
"=",
"(",
"double",
")",
"(",
"t",
".",
"getX",
"(",
")",
"*",
"maxNumberOfStars",
")",
"/",
"(",
"double",
")",
"getWidth",
"(",
")",
"+",
"0.5",
";",
"}",
"else",
"if",
"(",
"t",
".",
"getEventType",
"(",
")",
"==",
"MouseEvent",
".",
"MOUSE_EXITED",
")",
"{",
"setValue",
"(",
"valueAtClick",
")",
";",
"}",
"}",
"/**\n * Cette fonction permet de\n *\n * @param value\n */",
"public",
"void",
"setValue",
"(",
"double",
"value",
")",
"{",
"double",
"newValue",
"=",
"value",
";",
"if",
"(",
"value",
"<",
"0",
")",
"{",
"newValue",
"=",
"0",
";",
"}",
"if",
"(",
"value",
">",
"maxNumberOfStars",
")",
"{",
"newValue",
"=",
"maxNumberOfStars",
";",
"}",
"int",
"i",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"Math",
".",
"floor",
"(",
"newValue",
")",
";",
"i",
"++",
")",
"{",
"stars",
".",
"get",
"(",
"i",
")",
".",
"setType",
"(",
"StarView",
".",
"StarTypes",
".",
"FILLED",
")",
";",
"}",
"if",
"(",
"Math",
".",
"round",
"(",
"newValue",
")",
"!=",
"Math",
".",
"floor",
"(",
"newValue",
")",
")",
"{",
"stars",
".",
"get",
"(",
"i",
"++",
")",
".",
"setType",
"(",
"StarView",
".",
"StarTypes",
".",
"HALF",
")",
";",
"}",
"for",
"(",
";",
"i",
"<",
"maxNumberOfStars",
";",
"i",
"++",
")",
"{",
"stars",
".",
"get",
"(",
"i",
")",
".",
"setType",
"(",
"StarView",
".",
"StarTypes",
".",
"EMPTY",
")",
";",
"}",
"}",
"/* \n * Permet de rendre l objet dynamique et autoriser les handlers. \n * @param hoverable \n */",
"public",
"void",
"setHoverable",
"(",
"boolean",
"hoverable",
")",
"{",
"if",
"(",
"hoverable",
")",
"{",
"addEventHandler",
"(",
"MouseEvent",
".",
"MOUSE_MOVED",
",",
"this",
")",
";",
"addEventHandler",
"(",
"MouseEvent",
".",
"MOUSE_CLICKED",
",",
"this",
")",
";",
"addEventHandler",
"(",
"MouseEvent",
".",
"MOUSE_EXITED",
",",
"this",
")",
";",
"}",
"else",
"{",
"removeEventHandler",
"(",
"MouseEvent",
".",
"MOUSE_MOVED",
",",
"this",
")",
";",
"removeEventHandler",
"(",
"MouseEvent",
".",
"MOUSE_CLICKED",
",",
"this",
")",
";",
"removeEventHandler",
"(",
"MouseEvent",
".",
"MOUSE_EXITED",
",",
"this",
")",
";",
"}",
"}",
"/**\n * Retourne la valeur selectionne lors du clic de souris\n *\n * @return valueAtClick\n */",
"public",
"double",
"getValueAtClick",
"(",
")",
"{",
"return",
"valueAtClick",
";",
"}",
"/**\n * Reset la valeur de valueAtClick ^pour permettre une nouvelle selection.\n */",
"public",
"void",
"reset",
"(",
")",
"{",
"setValue",
"(",
"0",
")",
";",
"valueAtClick",
"=",
"0",
";",
"}",
"}"
] | @author marco, groudame, lleichtn | [
"@author",
"marco",
"groudame",
"lleichtn"
] | [
"//add complements empty stars"
] | [
{
"param": "HBox",
"type": null
},
{
"param": "EventHandler<MouseEvent>",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "HBox",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "EventHandler<MouseEvent>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
feb6847bd834a53023294fc3dc4691ea9e52ebf2 | razajafri/javacpp-presets | cuspatial/src/gen/java/org/bytedeco/cuspatial/gdf_context.java | [
"Apache-2.0"
] | Java | gdf_context | /**
* \brief This struct holds various information about how an operation should be
* performed as well as additional information about the input data.
*/ | \brief This struct holds various information about how an operation should be
performed as well as additional information about the input data. | [
"\\",
"brief",
"This",
"struct",
"holds",
"various",
"information",
"about",
"how",
"an",
"operation",
"should",
"be",
"performed",
"as",
"well",
"as",
"additional",
"information",
"about",
"the",
"input",
"data",
"."
] | @Properties(inherit = org.bytedeco.cuspatial.presets.cuspatial.class)
public class gdf_context extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public gdf_context() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public gdf_context(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public gdf_context(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public gdf_context position(long position) {
return (gdf_context)super.position(position);
}
/** Indicates if the input data is sorted. 0 = No, 1 = yes */
public native int flag_sorted(); public native gdf_context flag_sorted(int setter);
/** The method to be used for the operation (e.g., sort vs hash) */
public native @Cast("gdf_method") int flag_method(); public native gdf_context flag_method(int setter);
/** for COUNT: DISTINCT = 1, else = 0 */
public native int flag_distinct(); public native gdf_context flag_distinct(int setter);
/** When method is GDF_HASH, 0 = result is not sorted, 1 = result is sorted */
public native int flag_sort_result(); public native gdf_context flag_sort_result(int setter);
/** 0 = No sort in place allowed, 1 = else */
public native int flag_sort_inplace(); public native gdf_context flag_sort_inplace(int setter);
/** false = Nulls are ignored in group by keys (Pandas style),
true = Nulls are treated as values in group by keys where NULL == NULL (SQL style)*/
public native @Cast("bool") boolean flag_groupby_include_nulls(); public native gdf_context flag_groupby_include_nulls(boolean setter);
/** Indicates how nulls are treated in group_by/order_by operations */
public native @Cast("gdf_null_sort_behavior") int flag_null_sort_behavior(); public native gdf_context flag_null_sort_behavior(int setter);
} | [
"@",
"Properties",
"(",
"inherit",
"=",
"org",
".",
"bytedeco",
".",
"cuspatial",
".",
"presets",
".",
"cuspatial",
".",
"class",
")",
"public",
"class",
"gdf_context",
"extends",
"Pointer",
"{",
"static",
"{",
"Loader",
".",
"load",
"(",
")",
";",
"}",
"/** Default native constructor. */",
"public",
"gdf_context",
"(",
")",
"{",
"super",
"(",
"(",
"Pointer",
")",
"null",
")",
";",
"allocate",
"(",
")",
";",
"}",
"/** Native array allocator. Access with {@link Pointer#position(long)}. */",
"public",
"gdf_context",
"(",
"long",
"size",
")",
"{",
"super",
"(",
"(",
"Pointer",
")",
"null",
")",
";",
"allocateArray",
"(",
"size",
")",
";",
"}",
"/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */",
"public",
"gdf_context",
"(",
"Pointer",
"p",
")",
"{",
"super",
"(",
"p",
")",
";",
"}",
"private",
"native",
"void",
"allocate",
"(",
")",
";",
"private",
"native",
"void",
"allocateArray",
"(",
"long",
"size",
")",
";",
"@",
"Override",
"public",
"gdf_context",
"position",
"(",
"long",
"position",
")",
"{",
"return",
"(",
"gdf_context",
")",
"super",
".",
"position",
"(",
"position",
")",
";",
"}",
"/** Indicates if the input data is sorted. 0 = No, 1 = yes */",
"public",
"native",
"int",
"flag_sorted",
"(",
")",
";",
"public",
"native",
"gdf_context",
"flag_sorted",
"(",
"int",
"setter",
")",
";",
"/** The method to be used for the operation (e.g., sort vs hash) */",
"public",
"native",
"@",
"Cast",
"(",
"\"",
"gdf_method",
"\"",
")",
"int",
"flag_method",
"(",
")",
";",
"public",
"native",
"gdf_context",
"flag_method",
"(",
"int",
"setter",
")",
";",
"/** for COUNT: DISTINCT = 1, else = 0 */",
"public",
"native",
"int",
"flag_distinct",
"(",
")",
";",
"public",
"native",
"gdf_context",
"flag_distinct",
"(",
"int",
"setter",
")",
";",
"/** When method is GDF_HASH, 0 = result is not sorted, 1 = result is sorted */",
"public",
"native",
"int",
"flag_sort_result",
"(",
")",
";",
"public",
"native",
"gdf_context",
"flag_sort_result",
"(",
"int",
"setter",
")",
";",
"/** 0 = No sort in place allowed, 1 = else */",
"public",
"native",
"int",
"flag_sort_inplace",
"(",
")",
";",
"public",
"native",
"gdf_context",
"flag_sort_inplace",
"(",
"int",
"setter",
")",
";",
"/** false = Nulls are ignored in group by keys (Pandas style), \n true = Nulls are treated as values in group by keys where NULL == NULL (SQL style)*/",
"public",
"native",
"@",
"Cast",
"(",
"\"",
"bool",
"\"",
")",
"boolean",
"flag_groupby_include_nulls",
"(",
")",
";",
"public",
"native",
"gdf_context",
"flag_groupby_include_nulls",
"(",
"boolean",
"setter",
")",
";",
"/** Indicates how nulls are treated in group_by/order_by operations */",
"public",
"native",
"@",
"Cast",
"(",
"\"",
"gdf_null_sort_behavior",
"\"",
")",
"int",
"flag_null_sort_behavior",
"(",
")",
";",
"public",
"native",
"gdf_context",
"flag_null_sort_behavior",
"(",
"int",
"setter",
")",
";",
"}"
] | \brief This struct holds various information about how an operation should be
performed as well as additional information about the input data. | [
"\\",
"brief",
"This",
"struct",
"holds",
"various",
"information",
"about",
"how",
"an",
"operation",
"should",
"be",
"performed",
"as",
"well",
"as",
"additional",
"information",
"about",
"the",
"input",
"data",
"."
] | [] | [
{
"param": "Pointer",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Pointer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
feb8ce5265d15f6c55361158a06b05244c7c583c | xzel23/utility | utility/src/test/java/com/dua3/utility/text/RichTextTest.java | [
"MIT"
] | Java | RichTextTest | /**
* @author Axel Howind
*/ | @author Axel Howind | [
"@author",
"Axel",
"Howind"
] | @SuppressWarnings("UnnecessaryLocalVariable")
public class RichTextTest {
@Test
public void testValueOf() {
String s = "hello world!";
RichText text = RichText.valueOf(s);
String expected = s;
String actual = text.toString();
assertEquals(expected, actual);
}
@Test
public void testEquals() {
// tests all sorts if equals comparisons
String s = "hello world!";
RichText a = RichText.valueOf(s);
RichText b = RichText.valueOf(s);
RichText c = RichText.valueOf(s);
RichText d = RichText.valueOf(s);
RichText e = RichText.valueOf("Hello World!");
RichText f = RichText.valueOf("Hello World!");
assertEquals(s, a.toString());
assertEquals(a, a);
assertEquals(b, b);
assertEquals(c, c);
assertEquals(d, c);
assertEquals(a, b);
assertEquals(a, c);
assertEquals(a, d);
assertEquals(b, c);
assertEquals(b, d);
assertEquals(c, d);
assertEquals(b, a);
assertEquals(c, a);
assertEquals(d, a);
assertEquals(c, b);
assertEquals(d, b);
assertEquals(d, c);
assertEquals(e, e);
assertEquals(f, f);
assertEquals(e, f);
assertEquals(f, e);
assertNotEquals(a, e);
assertNotEquals(b, e);
assertNotEquals(c, e);
assertNotEquals(d, e);
assertNotEquals(a, f);
assertNotEquals(b, f);
assertNotEquals(c, f);
assertNotEquals(d, f);
assertNotEquals(e, a);
assertNotEquals(e, b);
assertNotEquals(e, c);
assertNotEquals(e, d);
assertNotEquals(f, a);
assertNotEquals(f, b);
assertNotEquals(f, c);
assertNotEquals(f, d);
}
@Test
public void testEqualsText() {
// tests all sorts if equals comparisons
RichText text = RichText.valueOf("text");
RichText blue = text.wrap(Style.BLUE);
RichText red = text.wrap(Style.RED);
RichText upper = RichText.valueOf("TEXT");
RichText texts = RichText.valueOf("texts");
RichText blues = texts.wrap(Style.BLUE);
RichText blue2 = blues.subSequence(0,4);
assertFalse(text.equalsText(upper));
assertTrue(text.equalsText(text));
assertTrue(text.equalsText(blue));
assertTrue(text.equalsText(red));
assertFalse(text.equalsText(texts));
assertTrue(RichText.textAndFontEquals(blue, blue2));
assertFalse(RichText.textAndFontEquals(blue, blues));
assertTrue(blue.equalsTextAndFont(blue2));
assertTrue(blue.equalsTextAndFont(blue2));
assertFalse(blue.equalsTextAndFont(red));
assertTrue(text.equalsTextIgnoreCase(upper));
assertTrue(text.equalsTextIgnoreCase(text));
assertTrue(text.equalsTextIgnoreCase(blue));
assertTrue(text.equalsTextIgnoreCase(red));
assertFalse(text.equalsTextIgnoreCase(texts));
}
@Test
public void testsubSequence() {
RichTextBuilder builder = new RichTextBuilder();
builder.append("Hello ");
builder.push(Style.FONT_WEIGHT, Style.FONT_WEIGHT_VALUE_BOLD);
builder.append("world");
builder.pop(Style.FONT_WEIGHT);
builder.append("!");
RichText rt = builder.toRichText();
assertEquals("Hello", rt.subSequence(0,5).toString());
assertEquals("Hello ", rt.subSequence(0,6).toString());
assertEquals("ello", rt.subSequence(1,5).toString());
assertEquals("ello ", rt.subSequence(1,6).toString());
assertEquals("ello w", rt.subSequence(1,7).toString());
assertEquals("Hello world", rt.subSequence(0,11).toString());
assertEquals("Hello world!", rt.subSequence(0,12).toString());
assertEquals("", rt.subSequence(0,0).toString());
RichText sub = rt.subSequence(5,10);
assertEquals(" worl", sub.toString());
assertEquals("wo", sub.subSequence(1,3).toString());
}
@Test
public void testsingleCharSubSequence() {
String s = "Hello world!";
RichTextBuilder builder = new RichTextBuilder();
builder.append("Hello ");
builder.push(Style.FONT_WEIGHT, Style.FONT_WEIGHT_VALUE_BOLD);
builder.append("world");
builder.pop(Style.FONT_WEIGHT);
builder.append("!");
RichText r = builder.toRichText();
for (int i=0;i<s.length()-1; i++) {
assertEquals(s.subSequence(i,i+1), r.subSequence(i,i+1).toString());
}
}
@Test
public void testSubsequenceRegression() {
Style style1 = Style.create("style1", Map.entry("attr", "1"));
Style style2 = Style.create("style2", Map.entry("attr", "2"));
Style style3 = Style.create("style3", Map.entry("attr", "3"));
RichTextBuilder rtb = new RichTextBuilder();
rtb.push(style1);
rtb.append("A Short History of Git");
rtb.pop(style1);
rtb.push(style2);
rtb.append(" ");
rtb.pop(style2);
rtb.push(style3);
rtb.append("\n");
rtb.pop(style3);
RichText s = rtb.toRichText();
assertEquals("A Short History of Git \n", s.toString());
RichText actual = s.subSequence(19, 22);
RichText expected = RichText.valueOf("Git").apply(style1);
assertEquals(expected, actual);
}
@Test
public void testReplaceAll() {
String s = "Hello world\n\nThis is a\ttest!\r\n";
assertEquals(s.replaceAll("\\s+", " "), RichText.valueOf(s).replaceAll("\\s+", RichText.valueOf(" ")).toString());
String s1 = "As with many great things in life, Git began with a bit of creative destruction and fiery controversy.";
RichText r1 = RichText.valueOf(s1);
assertEquals(s1.replaceAll("\\s+", " "), r1.replaceAll("\\s+", RichText.valueOf(" ")).toString());
assertEquals(RichText.valueOf(s1.replaceAll("\\s+", " ")), r1.replaceAll("\\s+", RichText.valueOf(" ")));
RichText r2 = r1.subSequence(13, 33);
String s2 = r2.toString();
assertEquals(s2.replaceAll("\\s+", " "), r2.replaceAll("\\s+", RichText.valueOf(" ")).toString());
assertEquals(RichText.valueOf(s2.replaceAll("\\s+", " ")), r2.replaceAll("\\s+", RichText.valueOf(" ")));
}
@Test
public void testLines() {
RichTextBuilder builder = new RichTextBuilder();
builder.append("Hello ");
builder.push(Style.FONT_WEIGHT, Style.FONT_WEIGHT_VALUE_BOLD);
builder.append("w\nor\nld");
builder.pop(Style.FONT_WEIGHT);
builder.append("!");
RichText rt = builder.toRichText();
StringBuilder sb = new StringBuilder();
rt.lines().forEach(s -> sb.append(s.toString()).append(";"));
assertEquals("Hello w;or;ld!;", sb.toString());
}
@Test
public void testAttributedChars() {
RichTextBuilder builder = new RichTextBuilder();
builder.append("Hello ");
builder.push(Style.FONT_WEIGHT, Style.FONT_WEIGHT_VALUE_BOLD);
builder.append("world");
builder.pop(Style.FONT_WEIGHT);
builder.append("!");
RichText rt = builder.toRichText();
// test extracting the characters using attributedCharAt()
String s = rt.toString();
assertEquals("Hello world!", s);
for (int i=0; i<rt.length(); i++) {
assertEquals(s.charAt(i), rt.charAt(i));
assertEquals(s.charAt(i), rt.attributedCharAt(i).character());
}
// test the attributed character iterator
StringBuilder sb = new StringBuilder();
rt.attributedChars().map(AttributedCharacter::character).forEach(sb::append);
assertEquals("Hello world!", sb.toString());
}
// regression: java.lang.IndexOutOfBoundsException was thrown when iterating over attributed chars of a subSequence
@Test
public void testAttributedCharsOfSubString() {
RichTextBuilder builder = new RichTextBuilder();
builder.append("I said: Hello ");
builder.push(Style.FONT_WEIGHT, Style.FONT_WEIGHT_VALUE_BOLD);
builder.append("world");
builder.pop(Style.FONT_WEIGHT);
builder.append("!");
RichText rt_ = builder.toRichText();
RichText rt = rt_.subSequence(8);
// test extracting the characters using attributedCharAt()
String s = rt.toString();
assertEquals("Hello world!", s);
for (int i=0; i<rt.length(); i++) {
assertEquals(s.charAt(i), rt.charAt(i));
assertEquals(s.charAt(i), rt.attributedCharAt(i).character());
}
// test the attributed character iterator
StringBuilder sb = new StringBuilder();
rt.attributedChars().map(AttributedCharacter::character).forEach(sb::append);
assertEquals("Hello world!", sb.toString());
}
// Test that Runs containing same text and attributes but with different offsets to the same base compare equal.
@Test
public void testRunEquals() {
RichText txt= RichText.valueOf("1 2 3");
RichText a = txt.subSequence(1,2);
RichText b = txt.subSequence(3,4);
assertEquals(" ", a.toString());
assertEquals(" ", b.toString());
assertEquals(b, a);
}
@Test
public void tesstJoiner() {
RichText actual = Stream.of("This","should","be","easy").map(RichText::valueOf).collect(RichText.joiner(" "));
RichText expected = RichText.valueOf("This should be easy");
assertEquals(expected, actual);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"",
"UnnecessaryLocalVariable",
"\"",
")",
"public",
"class",
"RichTextTest",
"{",
"@",
"Test",
"public",
"void",
"testValueOf",
"(",
")",
"{",
"String",
"s",
"=",
"\"",
"hello world!",
"\"",
";",
"RichText",
"text",
"=",
"RichText",
".",
"valueOf",
"(",
"s",
")",
";",
"String",
"expected",
"=",
"s",
";",
"String",
"actual",
"=",
"text",
".",
"toString",
"(",
")",
";",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testEquals",
"(",
")",
"{",
"String",
"s",
"=",
"\"",
"hello world!",
"\"",
";",
"RichText",
"a",
"=",
"RichText",
".",
"valueOf",
"(",
"s",
")",
";",
"RichText",
"b",
"=",
"RichText",
".",
"valueOf",
"(",
"s",
")",
";",
"RichText",
"c",
"=",
"RichText",
".",
"valueOf",
"(",
"s",
")",
";",
"RichText",
"d",
"=",
"RichText",
".",
"valueOf",
"(",
"s",
")",
";",
"RichText",
"e",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"Hello World!",
"\"",
")",
";",
"RichText",
"f",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"Hello World!",
"\"",
")",
";",
"assertEquals",
"(",
"s",
",",
"a",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"a",
",",
"a",
")",
";",
"assertEquals",
"(",
"b",
",",
"b",
")",
";",
"assertEquals",
"(",
"c",
",",
"c",
")",
";",
"assertEquals",
"(",
"d",
",",
"c",
")",
";",
"assertEquals",
"(",
"a",
",",
"b",
")",
";",
"assertEquals",
"(",
"a",
",",
"c",
")",
";",
"assertEquals",
"(",
"a",
",",
"d",
")",
";",
"assertEquals",
"(",
"b",
",",
"c",
")",
";",
"assertEquals",
"(",
"b",
",",
"d",
")",
";",
"assertEquals",
"(",
"c",
",",
"d",
")",
";",
"assertEquals",
"(",
"b",
",",
"a",
")",
";",
"assertEquals",
"(",
"c",
",",
"a",
")",
";",
"assertEquals",
"(",
"d",
",",
"a",
")",
";",
"assertEquals",
"(",
"c",
",",
"b",
")",
";",
"assertEquals",
"(",
"d",
",",
"b",
")",
";",
"assertEquals",
"(",
"d",
",",
"c",
")",
";",
"assertEquals",
"(",
"e",
",",
"e",
")",
";",
"assertEquals",
"(",
"f",
",",
"f",
")",
";",
"assertEquals",
"(",
"e",
",",
"f",
")",
";",
"assertEquals",
"(",
"f",
",",
"e",
")",
";",
"assertNotEquals",
"(",
"a",
",",
"e",
")",
";",
"assertNotEquals",
"(",
"b",
",",
"e",
")",
";",
"assertNotEquals",
"(",
"c",
",",
"e",
")",
";",
"assertNotEquals",
"(",
"d",
",",
"e",
")",
";",
"assertNotEquals",
"(",
"a",
",",
"f",
")",
";",
"assertNotEquals",
"(",
"b",
",",
"f",
")",
";",
"assertNotEquals",
"(",
"c",
",",
"f",
")",
";",
"assertNotEquals",
"(",
"d",
",",
"f",
")",
";",
"assertNotEquals",
"(",
"e",
",",
"a",
")",
";",
"assertNotEquals",
"(",
"e",
",",
"b",
")",
";",
"assertNotEquals",
"(",
"e",
",",
"c",
")",
";",
"assertNotEquals",
"(",
"e",
",",
"d",
")",
";",
"assertNotEquals",
"(",
"f",
",",
"a",
")",
";",
"assertNotEquals",
"(",
"f",
",",
"b",
")",
";",
"assertNotEquals",
"(",
"f",
",",
"c",
")",
";",
"assertNotEquals",
"(",
"f",
",",
"d",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testEqualsText",
"(",
")",
"{",
"RichText",
"text",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"text",
"\"",
")",
";",
"RichText",
"blue",
"=",
"text",
".",
"wrap",
"(",
"Style",
".",
"BLUE",
")",
";",
"RichText",
"red",
"=",
"text",
".",
"wrap",
"(",
"Style",
".",
"RED",
")",
";",
"RichText",
"upper",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"TEXT",
"\"",
")",
";",
"RichText",
"texts",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"texts",
"\"",
")",
";",
"RichText",
"blues",
"=",
"texts",
".",
"wrap",
"(",
"Style",
".",
"BLUE",
")",
";",
"RichText",
"blue2",
"=",
"blues",
".",
"subSequence",
"(",
"0",
",",
"4",
")",
";",
"assertFalse",
"(",
"text",
".",
"equalsText",
"(",
"upper",
")",
")",
";",
"assertTrue",
"(",
"text",
".",
"equalsText",
"(",
"text",
")",
")",
";",
"assertTrue",
"(",
"text",
".",
"equalsText",
"(",
"blue",
")",
")",
";",
"assertTrue",
"(",
"text",
".",
"equalsText",
"(",
"red",
")",
")",
";",
"assertFalse",
"(",
"text",
".",
"equalsText",
"(",
"texts",
")",
")",
";",
"assertTrue",
"(",
"RichText",
".",
"textAndFontEquals",
"(",
"blue",
",",
"blue2",
")",
")",
";",
"assertFalse",
"(",
"RichText",
".",
"textAndFontEquals",
"(",
"blue",
",",
"blues",
")",
")",
";",
"assertTrue",
"(",
"blue",
".",
"equalsTextAndFont",
"(",
"blue2",
")",
")",
";",
"assertTrue",
"(",
"blue",
".",
"equalsTextAndFont",
"(",
"blue2",
")",
")",
";",
"assertFalse",
"(",
"blue",
".",
"equalsTextAndFont",
"(",
"red",
")",
")",
";",
"assertTrue",
"(",
"text",
".",
"equalsTextIgnoreCase",
"(",
"upper",
")",
")",
";",
"assertTrue",
"(",
"text",
".",
"equalsTextIgnoreCase",
"(",
"text",
")",
")",
";",
"assertTrue",
"(",
"text",
".",
"equalsTextIgnoreCase",
"(",
"blue",
")",
")",
";",
"assertTrue",
"(",
"text",
".",
"equalsTextIgnoreCase",
"(",
"red",
")",
")",
";",
"assertFalse",
"(",
"text",
".",
"equalsTextIgnoreCase",
"(",
"texts",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testsubSequence",
"(",
")",
"{",
"RichTextBuilder",
"builder",
"=",
"new",
"RichTextBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"Hello ",
"\"",
")",
";",
"builder",
".",
"push",
"(",
"Style",
".",
"FONT_WEIGHT",
",",
"Style",
".",
"FONT_WEIGHT_VALUE_BOLD",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"world",
"\"",
")",
";",
"builder",
".",
"pop",
"(",
"Style",
".",
"FONT_WEIGHT",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"!",
"\"",
")",
";",
"RichText",
"rt",
"=",
"builder",
".",
"toRichText",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"Hello",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"0",
",",
"5",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"Hello ",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"0",
",",
"6",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"ello",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"1",
",",
"5",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"ello ",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"1",
",",
"6",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"ello w",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"1",
",",
"7",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"Hello world",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"0",
",",
"11",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"Hello world!",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"0",
",",
"12",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"\"",
",",
"rt",
".",
"subSequence",
"(",
"0",
",",
"0",
")",
".",
"toString",
"(",
")",
")",
";",
"RichText",
"sub",
"=",
"rt",
".",
"subSequence",
"(",
"5",
",",
"10",
")",
";",
"assertEquals",
"(",
"\"",
" worl",
"\"",
",",
"sub",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
"wo",
"\"",
",",
"sub",
".",
"subSequence",
"(",
"1",
",",
"3",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testsingleCharSubSequence",
"(",
")",
"{",
"String",
"s",
"=",
"\"",
"Hello world!",
"\"",
";",
"RichTextBuilder",
"builder",
"=",
"new",
"RichTextBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"Hello ",
"\"",
")",
";",
"builder",
".",
"push",
"(",
"Style",
".",
"FONT_WEIGHT",
",",
"Style",
".",
"FONT_WEIGHT_VALUE_BOLD",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"world",
"\"",
")",
";",
"builder",
".",
"pop",
"(",
"Style",
".",
"FONT_WEIGHT",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"!",
"\"",
")",
";",
"RichText",
"r",
"=",
"builder",
".",
"toRichText",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"s",
".",
"length",
"(",
")",
"-",
"1",
";",
"i",
"++",
")",
"{",
"assertEquals",
"(",
"s",
".",
"subSequence",
"(",
"i",
",",
"i",
"+",
"1",
")",
",",
"r",
".",
"subSequence",
"(",
"i",
",",
"i",
"+",
"1",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testSubsequenceRegression",
"(",
")",
"{",
"Style",
"style1",
"=",
"Style",
".",
"create",
"(",
"\"",
"style1",
"\"",
",",
"Map",
".",
"entry",
"(",
"\"",
"attr",
"\"",
",",
"\"",
"1",
"\"",
")",
")",
";",
"Style",
"style2",
"=",
"Style",
".",
"create",
"(",
"\"",
"style2",
"\"",
",",
"Map",
".",
"entry",
"(",
"\"",
"attr",
"\"",
",",
"\"",
"2",
"\"",
")",
")",
";",
"Style",
"style3",
"=",
"Style",
".",
"create",
"(",
"\"",
"style3",
"\"",
",",
"Map",
".",
"entry",
"(",
"\"",
"attr",
"\"",
",",
"\"",
"3",
"\"",
")",
")",
";",
"RichTextBuilder",
"rtb",
"=",
"new",
"RichTextBuilder",
"(",
")",
";",
"rtb",
".",
"push",
"(",
"style1",
")",
";",
"rtb",
".",
"append",
"(",
"\"",
"A Short History of Git",
"\"",
")",
";",
"rtb",
".",
"pop",
"(",
"style1",
")",
";",
"rtb",
".",
"push",
"(",
"style2",
")",
";",
"rtb",
".",
"append",
"(",
"\"",
" ",
"\"",
")",
";",
"rtb",
".",
"pop",
"(",
"style2",
")",
";",
"rtb",
".",
"push",
"(",
"style3",
")",
";",
"rtb",
".",
"append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"rtb",
".",
"pop",
"(",
"style3",
")",
";",
"RichText",
"s",
"=",
"rtb",
".",
"toRichText",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"A Short History of Git ",
"\\n",
"\"",
",",
"s",
".",
"toString",
"(",
")",
")",
";",
"RichText",
"actual",
"=",
"s",
".",
"subSequence",
"(",
"19",
",",
"22",
")",
";",
"RichText",
"expected",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"Git",
"\"",
")",
".",
"apply",
"(",
"style1",
")",
";",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testReplaceAll",
"(",
")",
"{",
"String",
"s",
"=",
"\"",
"Hello world",
"\\n",
"\\n",
"This is a",
"\\t",
"test!",
"\\r",
"\\n",
"\"",
";",
"assertEquals",
"(",
"s",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"\"",
" ",
"\"",
")",
",",
"RichText",
".",
"valueOf",
"(",
"s",
")",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"RichText",
".",
"valueOf",
"(",
"\"",
" ",
"\"",
")",
")",
".",
"toString",
"(",
")",
")",
";",
"String",
"s1",
"=",
"\"",
"As with many great things in life, Git began with a bit of creative destruction and fiery controversy.",
"\"",
";",
"RichText",
"r1",
"=",
"RichText",
".",
"valueOf",
"(",
"s1",
")",
";",
"assertEquals",
"(",
"s1",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"\"",
" ",
"\"",
")",
",",
"r1",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"RichText",
".",
"valueOf",
"(",
"\"",
" ",
"\"",
")",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"RichText",
".",
"valueOf",
"(",
"s1",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"\"",
" ",
"\"",
")",
")",
",",
"r1",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"RichText",
".",
"valueOf",
"(",
"\"",
" ",
"\"",
")",
")",
")",
";",
"RichText",
"r2",
"=",
"r1",
".",
"subSequence",
"(",
"13",
",",
"33",
")",
";",
"String",
"s2",
"=",
"r2",
".",
"toString",
"(",
")",
";",
"assertEquals",
"(",
"s2",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"\"",
" ",
"\"",
")",
",",
"r2",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"RichText",
".",
"valueOf",
"(",
"\"",
" ",
"\"",
")",
")",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"RichText",
".",
"valueOf",
"(",
"s2",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"\"",
" ",
"\"",
")",
")",
",",
"r2",
".",
"replaceAll",
"(",
"\"",
"\\\\",
"s+",
"\"",
",",
"RichText",
".",
"valueOf",
"(",
"\"",
" ",
"\"",
")",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testLines",
"(",
")",
"{",
"RichTextBuilder",
"builder",
"=",
"new",
"RichTextBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"Hello ",
"\"",
")",
";",
"builder",
".",
"push",
"(",
"Style",
".",
"FONT_WEIGHT",
",",
"Style",
".",
"FONT_WEIGHT_VALUE_BOLD",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"w",
"\\n",
"or",
"\\n",
"ld",
"\"",
")",
";",
"builder",
".",
"pop",
"(",
"Style",
".",
"FONT_WEIGHT",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"!",
"\"",
")",
";",
"RichText",
"rt",
"=",
"builder",
".",
"toRichText",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"rt",
".",
"lines",
"(",
")",
".",
"forEach",
"(",
"s",
"->",
"sb",
".",
"append",
"(",
"s",
".",
"toString",
"(",
")",
")",
".",
"append",
"(",
"\"",
";",
"\"",
")",
")",
";",
"assertEquals",
"(",
"\"",
"Hello w;or;ld!;",
"\"",
",",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testAttributedChars",
"(",
")",
"{",
"RichTextBuilder",
"builder",
"=",
"new",
"RichTextBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"Hello ",
"\"",
")",
";",
"builder",
".",
"push",
"(",
"Style",
".",
"FONT_WEIGHT",
",",
"Style",
".",
"FONT_WEIGHT_VALUE_BOLD",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"world",
"\"",
")",
";",
"builder",
".",
"pop",
"(",
"Style",
".",
"FONT_WEIGHT",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"!",
"\"",
")",
";",
"RichText",
"rt",
"=",
"builder",
".",
"toRichText",
"(",
")",
";",
"String",
"s",
"=",
"rt",
".",
"toString",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"Hello world!",
"\"",
",",
"s",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"rt",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"assertEquals",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
",",
"rt",
".",
"charAt",
"(",
"i",
")",
")",
";",
"assertEquals",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
",",
"rt",
".",
"attributedCharAt",
"(",
"i",
")",
".",
"character",
"(",
")",
")",
";",
"}",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"rt",
".",
"attributedChars",
"(",
")",
".",
"map",
"(",
"AttributedCharacter",
"::",
"character",
")",
".",
"forEach",
"(",
"sb",
"::",
"append",
")",
";",
"assertEquals",
"(",
"\"",
"Hello world!",
"\"",
",",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testAttributedCharsOfSubString",
"(",
")",
"{",
"RichTextBuilder",
"builder",
"=",
"new",
"RichTextBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"I said: Hello ",
"\"",
")",
";",
"builder",
".",
"push",
"(",
"Style",
".",
"FONT_WEIGHT",
",",
"Style",
".",
"FONT_WEIGHT_VALUE_BOLD",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"world",
"\"",
")",
";",
"builder",
".",
"pop",
"(",
"Style",
".",
"FONT_WEIGHT",
")",
";",
"builder",
".",
"append",
"(",
"\"",
"!",
"\"",
")",
";",
"RichText",
"rt_",
"=",
"builder",
".",
"toRichText",
"(",
")",
";",
"RichText",
"rt",
"=",
"rt_",
".",
"subSequence",
"(",
"8",
")",
";",
"String",
"s",
"=",
"rt",
".",
"toString",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"Hello world!",
"\"",
",",
"s",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"rt",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"assertEquals",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
",",
"rt",
".",
"charAt",
"(",
"i",
")",
")",
";",
"assertEquals",
"(",
"s",
".",
"charAt",
"(",
"i",
")",
",",
"rt",
".",
"attributedCharAt",
"(",
"i",
")",
".",
"character",
"(",
")",
")",
";",
"}",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"rt",
".",
"attributedChars",
"(",
")",
".",
"map",
"(",
"AttributedCharacter",
"::",
"character",
")",
".",
"forEach",
"(",
"sb",
"::",
"append",
")",
";",
"assertEquals",
"(",
"\"",
"Hello world!",
"\"",
",",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testRunEquals",
"(",
")",
"{",
"RichText",
"txt",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"1 2 3",
"\"",
")",
";",
"RichText",
"a",
"=",
"txt",
".",
"subSequence",
"(",
"1",
",",
"2",
")",
";",
"RichText",
"b",
"=",
"txt",
".",
"subSequence",
"(",
"3",
",",
"4",
")",
";",
"assertEquals",
"(",
"\"",
" ",
"\"",
",",
"a",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"\"",
" ",
"\"",
",",
"b",
".",
"toString",
"(",
")",
")",
";",
"assertEquals",
"(",
"b",
",",
"a",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"tesstJoiner",
"(",
")",
"{",
"RichText",
"actual",
"=",
"Stream",
".",
"of",
"(",
"\"",
"This",
"\"",
",",
"\"",
"should",
"\"",
",",
"\"",
"be",
"\"",
",",
"\"",
"easy",
"\"",
")",
".",
"map",
"(",
"RichText",
"::",
"valueOf",
")",
".",
"collect",
"(",
"RichText",
".",
"joiner",
"(",
"\"",
" ",
"\"",
")",
")",
";",
"RichText",
"expected",
"=",
"RichText",
".",
"valueOf",
"(",
"\"",
"This should be easy",
"\"",
")",
";",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"}"
] | @author Axel Howind | [
"@author",
"Axel",
"Howind"
] | [
"// tests all sorts if equals comparisons",
"// tests all sorts if equals comparisons",
"// test extracting the characters using attributedCharAt()",
"// test the attributed character iterator",
"// regression: java.lang.IndexOutOfBoundsException was thrown when iterating over attributed chars of a subSequence",
"// test extracting the characters using attributedCharAt()",
"// test the attributed character iterator",
"// Test that Runs containing same text and attributes but with different offsets to the same base compare equal."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
feb9c3bcb94d4d9bf815ade7a8ac3ad64b7d5adb | tlucas30/b2-sdk-java | core/src/test/java/com/backblaze/b2/json/B2JsonTest.java | [
"MIT"
] | Java | B2JsonTest | /**
* Unit tests for B2Json.
*/ | Unit tests for B2Json. | [
"Unit",
"tests",
"for",
"B2Json",
"."
] | @SuppressWarnings({
"unused", // A lot of the test classes have things that aren't used, but we don't care.
"WeakerAccess" // A lot of the test classes could have weaker access, but we don't care.
})
public class B2JsonTest extends B2BaseTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private static final class Container {
@B2Json.required
public final int a;
@B2Json.optional
public final String b;
@B2Json.ignored
public int c;
@B2Json.constructor(params = "a, b")
public Container(int a, String b) {
this.a = a;
this.b = b;
this.c = 5;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Container)) {
return false;
}
Container other = (Container) o;
return a == other.a && (b == null ? other.b == null : b.equals(other.b));
}
}
private static final B2Json b2Json = B2Json.get();
@Test
public void testBoolean() throws IOException, B2JsonException {
checkDeserializeSerialize("false", Boolean.class);
checkDeserializeSerialize("true", Boolean.class);
}
@Test
public void testBigDecimal() throws IOException, B2JsonException {
checkDeserializeSerialize("13", BigDecimal.class);
checkDeserializeSerialize("127.5243872835782375823758273582735", BigDecimal.class);
}
@Test
public void testBigInteger() throws IOException, B2JsonException {
checkDeserializeSerialize("13", BigInteger.class);
checkDeserializeSerialize("31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470", BigDecimal.class);
checkDeserializeSerialize("-271828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746", BigDecimal.class);
}
@Test
public void testByte() throws IOException, B2JsonException {
checkDeserializeSerialize("13", Byte.class);
checkDeserializeSerialize("-37", Byte.class);
}
@Test
public void testChar() throws IOException, B2JsonException {
checkDeserializeSerialize("13", Character.class);
checkDeserializeSerialize("65000", Character.class);
}
@Test
public void testInteger() throws IOException, B2JsonException {
checkDeserializeSerialize("-1234567", Integer.class);
}
@Test
public void testLong() throws IOException, B2JsonException {
checkDeserializeSerialize("123456789000", Long.class);
}
@Test
public void testFloat() throws IOException, B2JsonException {
checkDeserializeSerialize("3.5", Float.class);
}
@Test
public void testDouble() throws IOException, B2JsonException {
checkDeserializeSerialize("2.0E10", Double.class);
}
@Test
public void testLocalDate() throws IOException, B2JsonException {
checkDeserializeSerialize("\"20150401\"", LocalDate.class);
}
@Test
public void testLocalDateTime() throws IOException, B2JsonException {
checkDeserializeSerialize("\"d20150401_m123456\"", LocalDateTime.class);
}
@Test
public void testDuration() throws IOException, B2JsonException {
checkDeserializeSerialize("\"4d3h2m1s\"", Duration.class);
}
@Test
public void testObject() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\"\n" +
"}";
Container obj = new Container(41, "hello");
assertEquals(json, b2Json.toJson(obj));
assertEquals(obj, b2Json.fromJson(json, Container.class));
}
@Test
public void testUnionWithTypeFieldLast() throws IOException, B2JsonException {
final String json =
"{\n" +
" \"a\": 5,\n" +
" \"b\": null,\n" +
" \"type\": \"a\"\n" +
"}";
checkDeserializeSerialize(json, UnionAZ.class);
}
@Test
public void testUnionWithTypeFieldNotLast() throws IOException, B2JsonException {
final String json =
"{\n" +
" \"type\": \"z\",\n" +
" \"z\": \"hello\"\n" +
"}";
checkDeserializeSerialize(json, UnionAZ.class);
}
/**
* Regression test to make sure that when handlers are created from
* B2JsonUnionHandler they work properly.
*
* This test makes a new B2Json, and de-serializes the union type, so
* it's sure that the B2JsonUnionBaseHandler gets initialized first,
* which is what triggered the bug.
*/
@Test
public void testUnionCreatesHandlers() throws B2JsonException {
(new B2Json()).fromJson("{\n" +
" \"type\": \"a\",\n" +
" \"a\": 5,\n" +
" \"b\": [10]" +
"}",
UnionAZ.class
);
}
@Test
public void testComment() throws B2JsonException {
String json =
"{ // this is a comment\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\"\n" +
"} // comment to eof";
String jsonWithoutComment =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\"\n" +
"}";
Container obj = new Container(41, "hello");
assertEquals(jsonWithoutComment, b2Json.toJson(obj));
assertEquals(obj, b2Json.fromJson(json, Container.class));
}
@Test
public void testNoCommentInString() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"he//o\"\n" +
"}";
Container obj = new Container(41, "he//o");
assertEquals(json, b2Json.toJson(obj));
assertEquals(obj, b2Json.fromJson(json, Container.class));
}
@Test
public void testBadComment() throws B2JsonException {
String json =
"{ / \n" +
" \"a\": 41,\n" +
" \"b\": \"hello\"\n" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("invalid comment: single slash");
b2Json.fromJson(json, Container.class);
}
@Test
public void testMissingComma() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41\n" +
" \"b\": \"hello\"\n" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("object should end with brace but found: \"");
b2Json.fromJson(json, Container.class);
}
@Test
public void testExtraComma() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\",\n" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("string does not start with quote");
b2Json.fromJson(json, Container.class);
}
@Test
public void testDuplicateField() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41,\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\"\n" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("duplicate field: a");
b2Json.fromJson(json, Container.class);
}
@Test
public void testDisallowIgnored() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\",\n" +
" \"c\": 7" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("unknown field");
b2Json.fromJson(json, Container.class);
}
@Test
public void testDisallowUnknown() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\",\n" +
" \"x\": 7" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("unknown field");
b2Json.fromJson(json, Container.class);
}
private static class Discarder {
@B2Json.required
public final int a;
@B2Json.required
public final int c;
@B2Json.constructor(params = "a,c", discards = "b")
private Discarder(int a, int c) {
this.a = a;
this.c = c;
}
}
private static class DiscardingIgnoredFieldIsOk {
@B2Json.required
public final int a;
@B2Json.ignored
public final int c;
@B2Json.constructor(params = "a", discards = "b,c")
private DiscardingIgnoredFieldIsOk(int a) {
this.a = a;
this.c = 42;
}
}
private static class DiscardingNonIgnoredFieldIsIllegal {
@B2Json.required
public final int a;
@B2Json.required
public final int c;
@B2Json.constructor(params = "a,c", discards = "b,c")
private DiscardingNonIgnoredFieldIsIllegal(int a, int c) {
this.a = a;
this.c = c;
}
}
@Test
public void testAllowUnknown() throws B2JsonException {
String json =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\",\n" +
" \"x\": 7" +
"}";
Container c = b2Json.fromJson(json, Container.class, B2JsonOptions.DEFAULT_AND_ALLOW_EXTRA_FIELDS);
String expectedJson =
"{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\"\n" +
"}";
assertEquals(expectedJson, b2Json.toJson(c));
}
@Test
public void testAllowButSkipDiscarded() throws B2JsonException {
final String jsonWithExtra = "{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\",\n" +
" \"c\": 7" +
"}";
final Discarder discarder = b2Json.fromJson(jsonWithExtra, Discarder.class);
assertEquals(41, discarder.a);
assertEquals(7, discarder.c);
final String expectedJson = "{\n" +
" \"a\": 41,\n" +
" \"c\": 7\n" +
"}";
assertEquals(expectedJson, b2Json.toJson(discarder));
}
@Test
public void testDiscardingIgnoredFieldIsOk() throws B2JsonException {
final String jsonWithExtra = "{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\",\n" +
" \"c\": 7" +
"}";
final DiscardingIgnoredFieldIsOk discarder = b2Json.fromJson(jsonWithExtra, DiscardingIgnoredFieldIsOk.class);
assertEquals(41, discarder.a);
assertEquals(42, discarder.c); // 'cuz ignored from json and set by constructor.
final String expectedJson = "{\n" +
" \"a\": 41\n" +
"}";
assertEquals(expectedJson, b2Json.toJson(discarder));
}
@Test
public void testDiscardingNonIgnoredFieldIsIllegal() throws B2JsonException {
thrown.expect(B2JsonException.class);
thrown.expectMessage("DiscardingNonIgnoredFieldIsIllegal's field 'c' cannot be discarded: it's REQUIRED. only non-existent or IGNORED fields can be discarded.");
final String jsonWithExtra = "{\n" +
" \"a\": 41,\n" +
" \"b\": \"hello\",\n" +
" \"c\": 7" +
"}";
b2Json.fromJson(jsonWithExtra, DiscardingNonIgnoredFieldIsIllegal.class);
}
@Test
public void testMissingRequired() throws B2JsonException {
String json = "{ \"b\" : \"hello\" }";
thrown.expect(B2JsonException.class);
thrown.expectMessage("required field a is missing");
b2Json.fromJson(json, Container.class);
}
private static class Empty {
@B2Json.constructor(params = "") Empty() {}
}
private static class AllOptionalTypes {
@B2Json.optional boolean v_boolean;
@B2Json.optional byte v_byte;
@B2Json.optional int v_int;
@B2Json.optional char v_char;
@B2Json.optional long v_long;
@B2Json.optional float v_float;
@B2Json.optional double v_double;
@B2Json.optional String v_string;
@B2Json.optional Empty v_empty;
@B2Json.optional Color v_color;
@B2Json.constructor(params = "v_boolean, v_byte, v_char, v_int, v_long, v_float, v_double, v_string, v_empty, v_color")
public AllOptionalTypes(boolean v_boolean,
byte v_byte,
char v_char,
int v_int,
long v_long,
float v_float,
double v_double,
String v_string,
Empty v_empty,
Color v_color) {
this.v_boolean = v_boolean;
this.v_byte = v_byte;
this.v_int = v_int;
this.v_char = v_char;
this.v_long = v_long;
this.v_float = v_float;
this.v_double = v_double;
this.v_string = v_string;
this.v_empty = v_empty;
this.v_color = v_color;
}
}
@Test
public void testOptionalNotPresent() throws IOException, B2JsonException {
String json = "{}";
AllOptionalTypes obj = b2Json.fromJson(json, AllOptionalTypes.class);
assertFalse(obj.v_boolean);
assertEquals(0, obj.v_byte);
assertEquals(0, obj.v_char);
assertEquals(0, obj.v_int);
assertEquals(0, obj.v_long);
assertEquals(0.0, obj.v_float, 0.0);
assertEquals(0.0, obj.v_double, 0.0);
assertNull(obj.v_string);
assertNull(obj.v_empty);
String expectedJson =
"{\n" +
" \"v_boolean\": false,\n" +
" \"v_byte\": 0,\n" +
" \"v_char\": 0,\n" +
" \"v_color\": null,\n" +
" \"v_double\": 0.0,\n" +
" \"v_empty\": null,\n" +
" \"v_float\": 0.0,\n" +
" \"v_int\": 0,\n" +
" \"v_long\": 0,\n" +
" \"v_string\": null\n" +
"}";
assertEquals(expectedJson, b2Json.toJson(obj));
checkDeserializeSerialize(expectedJson, AllOptionalTypes.class);
}
@Test
public void testOptionalsPresentInUrl() throws IOException, B2JsonException {
Map<String, String> parameterMap = makeParameterMap(
"v_boolean", "true",
"v_byte", "5",
"v_char", "6",
"v_color", "BLUE",
"v_double", "7.0",
"v_float", "8.0",
"v_int", "9",
"v_long", "10",
"v_string", "abc"
);
AllOptionalTypes obj = b2Json.fromUrlParameterMap(parameterMap, AllOptionalTypes.class);
assertTrue(obj.v_boolean);
assertEquals(5, obj.v_byte);
assertEquals(6, obj.v_char);
assertEquals(Color.BLUE, obj.v_color);
assertEquals(7.0, obj.v_double, 0.0001);
assertEquals(8.0, obj.v_float, 0.0001);
assertEquals(9, obj.v_int);
assertEquals(10, obj.v_long);
assertEquals("abc", obj.v_string);
}
private Map<String, String> makeParameterMap(String ... args) {
if (args.length % 2 != 0) {
throw new IllegalArgumentException("odd number of arguments");
}
Map<String, String> parameterMap = new HashMap<>();
for (int i = 0; i < args.length; i += 2) {
parameterMap.put(args[i], args[i + 1]);
}
return parameterMap;
}
@Test
public void testOptionalNull()throws B2JsonException {
String json =
"{" +
" \"v_string\" : null,\n" +
" \"v_empty\" : null\n" +
"}";
AllOptionalTypes obj = b2Json.fromJson(json, AllOptionalTypes.class);
assertNull(obj.v_string);
assertNull(obj.v_empty);
}
private static class RequiredObject {
@B2Json.required Empty a;
@B2Json.constructor(params = "a")
public RequiredObject(Empty a) {
this.a = a;
}
}
@Test
public void testSerializeNullTopLevel() throws B2JsonException {
thrown.expect(B2JsonException.class);
thrown.expectMessage("top level object must not be null");
b2Json.toJson(null);
}
@Test
public void testSerializeNullRequired() throws B2JsonException {
RequiredObject obj = new RequiredObject(null);
thrown.expect(B2JsonException.class);
thrown.expectMessage("required field a cannot be null");
b2Json.toJson(obj);
}
@Test
public void testDeserializeNullRequired() throws B2JsonException {
String json = "{ \"a\" : null }";
thrown.expect(B2JsonException.class);
thrown.expectMessage("required field a cannot be null");
b2Json.fromJson(json, RequiredObject.class);
}
private static class ListHolder {
@B2Json.optional
List<List<Integer>> intListList;
@B2Json.constructor(params = "intListList")
ListHolder(List<List<Integer>> intListList) {
this.intListList = intListList;
}
}
@Test
public void testList() throws IOException, B2JsonException {
String json1 =
"{\n" +
" \"intListList\": [\n" +
" [ 1, null, 3 ]\n" +
" ]\n" +
"}";
checkDeserializeSerialize(json1, ListHolder.class);
String json2 =
"{\n" +
" \"intListList\": null\n" +
"}";
checkDeserializeSerialize(json2, ListHolder.class);
}
private <T> void checkDeserializeSerialize(String json, Class<T> clazz) throws IOException, B2JsonException {
T obj = b2Json.fromJson(json, clazz);
assertEquals(json, b2Json.toJson(obj));
byte [] bytes = getUtf8Bytes(json);
T obj2 = b2Json.fromJson(bytes, clazz);
assertArrayEquals(bytes, b2Json.toJsonUtf8Bytes(obj2));
T obj3 = b2Json.fromJson(bytes, clazz);
byte [] bytesWithNewline = getUtf8Bytes(json + "\n");
assertArrayEquals(bytesWithNewline, b2Json.toJsonUtf8BytesWithNewline(obj3));
}
private <T> void checkDeserializeSerialize(String json, Class<T> clazz, String expectedJson) throws IOException, B2JsonException {
T obj = b2Json.fromJson(json, clazz);
assertEquals(expectedJson, b2Json.toJson(obj));
byte [] bytes = getUtf8Bytes(json);
T obj2 = b2Json.fromJson(bytes, clazz);
assertArrayEquals(getUtf8Bytes(expectedJson), b2Json.toJsonUtf8Bytes(obj2));
}
private static class MapHolder {
@B2Json.optional
public Map<LocalDate, Integer> map;
@B2Json.constructor(params = "map")
public MapHolder(Map<LocalDate, Integer> map) {
this.map = map;
}
}
@Test
public void testMap() throws IOException, B2JsonException {
String json1 =
"{\n" +
" \"map\": {\n" +
" \"20150101\": 37,\n" +
" \"20150207\": null\n" +
" }\n" +
"}" ;
checkDeserializeSerialize(json1, MapHolder.class);
String json2 =
"{\n" +
" \"map\": null\n" +
"}";
checkDeserializeSerialize(json2, MapHolder.class);
}
private static class MapWithNullKeyHolder {
@B2Json.optional
Map<String, String> map;
@B2Json.constructor(params = "map")
public MapWithNullKeyHolder(Map<String, String> map) {
this.map = map;
}
}
@Test
public void testSerializationOfMapWithNullKeyGeneratesException() {
Map<String, String> map = new HashMap<>();
map.put(null, "Text");
MapWithNullKeyHolder mapWithNullKeyHolder = new MapWithNullKeyHolder(map);
try {
b2Json.toJson(mapWithNullKeyHolder);
assertTrue("Map with null key should not be allowed to be serialized", false);
} catch (B2JsonException ex) {
assertEquals("Map key is null", ex.getMessage());
}
}
private static class TreeMapHolder {
@B2Json.optional
TreeMap<LocalDate, Integer> treeMap;
@B2Json.constructor(params = "treeMap")
public TreeMapHolder(TreeMap<LocalDate, Integer> treeMap) {
this.treeMap = treeMap;
}
}
@Test
public void testTreeMap() throws IOException, B2JsonException {
String json1 =
"{\n" +
" \"treeMap\": {\n" +
" \"20150101\": 37,\n" +
" \"20150207\": null\n" +
" }\n" +
"}" ;
checkDeserializeSerialize(json1, TreeMapHolder.class);
String json2 =
"{\n" +
" \"treeMap\": null\n" +
"}";
checkDeserializeSerialize(json2, TreeMapHolder.class);
}
private static class SortedMapHolder {
@B2Json.optional
SortedMap<LocalDate, Integer> sortedMap;
@B2Json.constructor(params = "sortedMap")
public SortedMapHolder(SortedMap<LocalDate, Integer> sortedMap) {
this.sortedMap = sortedMap;
}
}
@Test
public void testSortedMap() throws IOException, B2JsonException {
String json1 =
"{\n" +
" \"sortedMap\": {\n" +
" \"20150101\": 37,\n" +
" \"20150207\": null\n" +
" }\n" +
"}" ;
checkDeserializeSerialize(json1, SortedMapHolder.class);
String json2 =
"{\n" +
" \"sortedMap\": null\n" +
"}";
checkDeserializeSerialize(json2, SortedMapHolder.class);
}
private static class ConcurrentMapHolder {
@B2Json.optional
public ConcurrentMap<LocalDate, Integer> map;
@B2Json.constructor(params = "map")
public ConcurrentMapHolder(ConcurrentMap<LocalDate, Integer> map) {
this.map = map;
}
}
@Test
public void testConcurrentMap() throws B2JsonException {
ConcurrentMap<LocalDate, Integer> map = new ConcurrentHashMap<>();
map.put(LocalDate.of(2015, 5, 2), 7);
ConcurrentMapHolder holder = new ConcurrentMapHolder(map);
String json =
"{\n" +
" \"map\": {\n" +
" \"20150502\": 7\n" +
" }\n" +
"}" ;
assertEquals(json, b2Json.toJson(holder));
}
@Test
public void testDirectMap() throws B2JsonException {
Map<String, Integer> map = new HashMap<>();
map.put("a", 5);
map.put("b", 6);
String json =
"{\n" +
" \"a\": 5,\n" +
" \"b\": 6\n" +
"}";
assertEquals(json, b2Json.mapToJson(map, String.class, Integer.class));
assertEquals(map, b2Json.mapFromJson(json, String.class, Integer.class));
}
@Test
public void testDirectList() throws B2JsonException {
List<String> list = new ArrayList<>();
list.add("alfa");
list.add("bravo");
String json =
"[\n" +
" \"alfa\",\n" +
" \"bravo\"\n" +
"]";
assertEquals(json, b2Json.listToJson(list, String.class));
assertEquals(list, b2Json.listFromJson(json, String.class));
}
@Test
public void testUtf8() throws IOException, B2JsonException {
// These test cases are from: http://www.oracle.com/us/technologies/java/supplementary-142654.html
StringBuilder builder = new StringBuilder();
builder.appendCodePoint(0xA);
builder.appendCodePoint(0x41);
builder.appendCodePoint(0xDF);
builder.appendCodePoint(0x6771);
builder.appendCodePoint(0x10400);
String str = builder.toString();
String json = "\"\\u000a" + str.substring(1) + "\"";
byte [] utf8Json = new byte [] {
(byte) 0x22,
(byte) 0x5C,
(byte) 0x75,
(byte) 0x30,
(byte) 0x30,
(byte) 0x30,
(byte) 0x61,
(byte) 0x41,
(byte) 0xC3,
(byte) 0x9F,
(byte) 0xE6,
(byte) 0x9D,
(byte) 0xB1,
(byte) 0xF0,
(byte) 0x90,
(byte) 0x90,
(byte) 0x80,
(byte) 0x22
};
// Check de-serializing from string
assertEquals(str, b2Json.fromJson(json, String.class));
// Check de-serializing from bytes
assertEquals(str, b2Json.fromJson(new ByteArrayInputStream(utf8Json), String.class));
// Check serializing to string
assertEquals(json, b2Json.toJson(str));
// Check serializing to bytes
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
b2Json.toJson(str, out);
assertArrayEquals(utf8Json, out.toByteArray());
}
}
private static class Private {
@B2Json.required
private int age;
@B2Json.constructor(params = "age")
private Private(int age) {
this.age = age;
}
}
@Test
public void testPrivate() throws B2JsonException, IOException {
final Private orig = new Private(6);
assertEquals(6, orig.age);
// ensure we can serialize a private member.
final String json = b2Json.toJson(orig);
final String expectedJson =
"{\n" +
" \"age\": 6\n" +
"}";
assertEquals(expectedJson, json);
// ensure we can create with a private constructor and set a private member.
checkDeserializeSerialize(json, Private.class);
}
// an enum with no @B2Json.defaultForInvalidValue
private enum Color { BLUE, GREEN, RED }
private static class ColorHolder {
@B2Json.required
Color color;
@B2Json.constructor(params = "color")
public ColorHolder(Color color) {
this.color = color;
}
}
@Test
public void testEnum() throws IOException, B2JsonException {
String json =
"{\n" +
" \"color\": \"RED\"\n" +
"}";
checkDeserializeSerialize(json, ColorHolder.class);
}
@Test
public void testUnknownEnum_noDefaultForInvalidEnumValue() throws IOException, B2JsonException {
String json =
"{\n" +
" \"color\": \"CHARTREUSE\"\n" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("CHARTREUSE is not a valid value. Valid values are: BLUE, GREEN, RED");
checkDeserializeSerialize(json, ColorHolder.class);
}
// an enum with too many @B2Json.defaultForInvalidValues
private enum Spin {
@B2Json.defaultForInvalidEnumValue()
LEFT,
@B2Json.defaultForInvalidEnumValue()
RIGHT
}
private static class SpinHolder {
@B2Json.optional
final Spin spin;
@B2Json.constructor(params = "spin")
private SpinHolder(Spin spin) {
this.spin = spin;
}
}
@Test
public void testUnknownEnum_tooManyDefaultInvalidEnumValue() throws IOException, B2JsonException {
String json =
"{\n" +
" \"spin\": \"CHARTREUSE\"\n" +
"}";
thrown.expect(B2JsonException.class);
thrown.expectMessage("more than one @B2Json.defaultForInvalidEnumValue annotation in enum class com.backblaze.b2.json.B2JsonTest.Spin");
checkDeserializeSerialize(json, SpinHolder.class);
}
// an enum with one @B2Json.defaultForInvalidEnumValue
private enum Flavor {
UP,
DOWN,
@B2Json.defaultForInvalidEnumValue
STRANGE,
CHARM,
TOP,
BOTTOM
}
private static class FlavorHolder {
@B2Json.optional
final Flavor flavor;
@B2Json.constructor(params = "flavor")
private FlavorHolder(Flavor flavor) {
this.flavor = flavor;
}
}
@Test
public void testUnknownEnum_usesDefaultInvalidEnumValue() throws B2JsonException {
String json =
"{\n" +
" \"flavor\": \"CHARTREUSE\"\n" +
"}";
final FlavorHolder holder = B2Json.get().fromJson(json, FlavorHolder.class);
assertEquals(Flavor.STRANGE, holder.flavor);
}
private static class EvenNumber {
@SuppressWarnings("unused")
@B2Json.required
private final int number;
@B2Json.constructor(params = "number")
public EvenNumber(int number) {
if (number % 2 != 0) {
throw new IllegalArgumentException("not even: " + number);
}
this.number = number;
}
}
@Test
public void testConstructorThrowsIllegalArgument() throws B2JsonException {
String json = "{ \"number\" : 7 }";
thrown.expect(B2JsonBadValueException.class);
thrown.expectMessage("not even: 7");
b2Json.fromJson(json, EvenNumber.class);
}
private static class PrimitiveArrayContainer {
@B2Json.required
final boolean[] booleans;
@B2Json.required
final char[] chars;
@B2Json.required
final byte[] bytes;
@B2Json.required
final int[] ints;
@B2Json.required
final long[] longs;
@B2Json.required
final float[] floats;
@B2Json.required
final double[] doubles;
@B2Json.constructor(params = "booleans,chars,bytes,ints,longs,floats,doubles")
public PrimitiveArrayContainer(boolean[] booleans,
char[] chars,
byte[] bytes,
int[] ints,
long[] longs,
float[] floats,
double[] doubles) {
this.booleans = booleans;
this.chars = chars;
this.bytes = bytes;
this.ints = ints;
this.longs = longs;
this.floats = floats;
this.doubles = doubles;
}
}
private static class OptionalPrimitiveArrayContainer {
@B2Json.optional
final boolean[] booleans;
@B2Json.optional
final char[] chars;
@B2Json.optional
final byte[] bytes;
@B2Json.optional
final int[] ints;
@B2Json.optional
final long[] longs;
@B2Json.optional
final float[] floats;
@B2Json.optional
final double[] doubles;
@B2Json.constructor(params = "booleans,chars,bytes,ints,longs,floats,doubles")
public OptionalPrimitiveArrayContainer(boolean[] booleans,
char[] chars,
byte[] bytes,
int[] ints,
long[] longs,
float[] floats,
double[] doubles) {
this.booleans = booleans;
this.chars = chars;
this.bytes = bytes;
this.ints = ints;
this.longs = longs;
this.floats = floats;
this.doubles = doubles;
}
}
@Test
public void testEmptyArrays() throws B2JsonException, IOException {
final String json = "{\n" +
" \"booleans\": [],\n" +
" \"bytes\": [],\n" +
" \"chars\": [],\n" +
" \"doubles\": [],\n" +
" \"floats\": [],\n" +
" \"ints\": [],\n" +
" \"longs\": []\n" +
"}";
checkDeserializeSerialize(json, PrimitiveArrayContainer.class);
}
@Test
public void testArraysWithValues() throws B2JsonException, IOException {
final String json = "{\n" +
" \"booleans\": [ true, false ],\n" +
" \"bytes\": [ 1, 2, 3 ],\n" +
" \"chars\": [ 65, 0, 128, 255 ],\n" +
" \"doubles\": [ 1.1, -2.2 ],\n" +
" \"floats\": [ 1.0, 2.0, 3.0 ],\n" +
" \"ints\": [ -2147483648, 0, 2147483647 ],\n" +
" \"longs\": [ 9223372036854775807, -9223372036854775808 ]\n" +
"}";
checkDeserializeSerialize(json, PrimitiveArrayContainer.class);
}
@Test
public void testOptionalArraysWithValues() throws B2JsonException, IOException {
final String json = "{\n" +
" \"booleans\": [ true ],\n" +
" \"bytes\": [ 1 ],\n" +
" \"chars\": [ 65 ],\n" +
" \"doubles\": [ 1.0 ],\n" +
" \"floats\": [ 2.0 ],\n" +
" \"ints\": [ 257 ],\n" +
" \"longs\": [ 12345 ]\n" +
"}";
checkDeserializeSerialize(json, OptionalPrimitiveArrayContainer.class);
}
@Test
public void testOptionalArraysWithMissing() throws B2JsonException, IOException {
final String json = "{}";
final String expectedJson = "{\n" +
" \"booleans\": null,\n" +
" \"bytes\": null,\n" +
" \"chars\": null,\n" +
" \"doubles\": null,\n" +
" \"floats\": null,\n" +
" \"ints\": null,\n" +
" \"longs\": null\n" +
"}";
checkDeserializeSerialize(json, OptionalPrimitiveArrayContainer.class, expectedJson);
}
@Test
public void testOptionalArraysThatAreNulls() throws B2JsonException, IOException {
final String json = "{\n" +
" \"booleans\": null,\n" +
" \"bytes\": null,\n" +
" \"chars\": null,\n" +
" \"doubles\": null,\n" +
" \"floats\": null,\n" +
" \"ints\": null,\n" +
" \"longs\": null\n" +
"}";
checkDeserializeSerialize(json, OptionalPrimitiveArrayContainer.class);
}
private void checkNullInArray(String fieldType) throws IOException {
final String json = "{\n" +
" \"" + fieldType + "s\": [ null ]\n" +
"}";
try {
checkDeserializeSerialize(json, OptionalPrimitiveArrayContainer.class);
fail("should've thrown");
} catch (B2JsonException e) {
assertEquals("can't put null in a " + fieldType + "[].", e.getMessage());
}
}
@Test
public void testNullInPrimitiveArray() throws IOException {
checkNullInArray("boolean");
checkNullInArray("byte");
checkNullInArray("char");
checkNullInArray("double");
checkNullInArray("float");
checkNullInArray("int");
checkNullInArray("boolean");
checkNullInArray("long");
}
private static class ObjectArrayContainer {
@B2Json.required
final OptionalPrimitiveArrayContainer[] containers;
@B2Json.required
final Color[] colors;
@B2Json.required
final long[][] arrays;
@B2Json.constructor(params = "containers, colors, arrays")
public ObjectArrayContainer(OptionalPrimitiveArrayContainer[] containers,
Color[] colors,
long[][] arrays) {
this.containers = containers;
this.colors = colors;
this.arrays = arrays;
}
}
@Test
public void testEmptyObjectArrays() throws IOException, B2JsonException {
final String json = "{\n" +
" \"arrays\": [],\n" +
" \"colors\": [],\n" +
" \"containers\": []\n" +
"}";
checkDeserializeSerialize(json, ObjectArrayContainer.class);
}
@Test
public void testObjectArrays() throws IOException, B2JsonException {
final String json = "{\n" +
" \"arrays\": [\n" +
" [ 1, 2, 3 ],\n" +
" null,\n" +
" [ 4, 5, 6 ]\n" +
" ],\n" +
" \"colors\": [\n" +
" \"RED\",\n" +
" null,\n" +
" \"BLUE\"\n" +
" ],\n" +
" \"containers\": [\n" +
" {\n" +
" \"booleans\": [ true ],\n" +
" \"bytes\": null,\n" +
" \"chars\": null,\n" +
" \"doubles\": null,\n" +
" \"floats\": null,\n" +
" \"ints\": null,\n" +
" \"longs\": null\n" +
" },\n" +
" null,\n" +
" {\n" +
" \"booleans\": null,\n" +
" \"bytes\": null,\n" +
" \"chars\": null,\n" +
" \"doubles\": null,\n" +
" \"floats\": null,\n" +
" \"ints\": null,\n" +
" \"longs\": [ 7, 8, 9 ]\n" +
" }\n" +
" ]\n" +
"}";
checkDeserializeSerialize(json, ObjectArrayContainer.class);
}
private byte [] getUtf8Bytes(String str) {
try {
return str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("No UTF-8 charset");
}
}
private static class GoodCustomHandler {
@SuppressWarnings("unused") // used by reflection
private static B2JsonTypeHandler<GoodCustomHandler> getJsonTypeHandler() {
return new JsonHandler();
}
private static class JsonHandler implements B2JsonTypeHandler<GoodCustomHandler> {
public Type getHandledType() {
return GoodCustomHandler.class;
}
public void serialize(GoodCustomHandler obj, B2JsonOptions options, B2JsonWriter out) throws IOException {
out.writeString("GoodCustomHandler");
}
public GoodCustomHandler deserialize(B2JsonReader in, B2JsonOptions options) throws B2JsonException, IOException {
return deserialize(in.readString());
}
public GoodCustomHandler deserializeUrlParam(String urlValue) throws B2JsonException {
return deserialize(urlValue);
}
private GoodCustomHandler deserialize(String value) throws B2JsonBadValueException {
if (!value.equals("GoodCustomHandler")) {
throw new B2JsonBadValueException("string isn't a GoodCustomHandler (" + value + ")");
}
return new GoodCustomHandler();
}
public GoodCustomHandler defaultValueForOptional() {
return null;
}
public boolean isStringInJson() {
return true;
}
}
}
@Test
public void customHandlerGood() throws IOException, B2JsonException {
checkDeserializeSerialize("\"GoodCustomHandler\"", GoodCustomHandler.class);
}
private static class WrongTypeHandler {
@SuppressWarnings("unused")
private static Double getJsonTypeHandler() {
return 6.66;
}
}
@Test
public void customHandlerWrongType() throws IOException {
try {
checkDeserializeSerialize("{}", WrongTypeHandler.class);
fail("should've thrown!");
} catch (B2JsonException e) {
assertEquals("WrongTypeHandler.getJsonTypeHandler() returned an unexpected type of object (java.lang.Double)", e.getMessage());
}
}
private static class NullHandler {
@SuppressWarnings("unused") // used by reflection
private static B2JsonTypeHandler<NullHandler> getJsonTypeHandler() {
return null;
}
}
@Test
public void customHandlerNull() throws IOException {
try {
checkDeserializeSerialize("{}", NullHandler.class);
fail("should've thrown!");
} catch (B2JsonException e) {
assertEquals("NullHandler.getJsonTypeHandler() returned an unexpected type of object (null)", e.getMessage());
}
}
private static class OptionalWithDefaultHolder {
@B2Json.optional
public final int a;
@B2Json.optionalWithDefault(defaultValue = "5")
public final int b;
@B2Json.optionalWithDefault(defaultValue = "\"hello\"")
public final String c;
@B2Json.constructor(params = "a, b, c")
private OptionalWithDefaultHolder(int a, int b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OptionalWithDefaultHolder that = (OptionalWithDefaultHolder) o;
return Objects.equals(a, that.a) &&
Objects.equals(b, that.b) &&
Objects.equals(c, that.c);
}
@Override
public String toString() {
return "OptionalWithDefaultHolder{" +
"a=" + a +
", b=" + b +
", c='" + c + '\'' +
'}';
}
}
@Test
public void testOptionalWithDefault() throws B2JsonException {
{
OptionalWithDefaultHolder expected = new OptionalWithDefaultHolder(0, 5, "hello");
OptionalWithDefaultHolder actual = b2Json.fromJson("{}", OptionalWithDefaultHolder.class);
assertEquals(expected, actual);
}
{
OptionalWithDefaultHolder expected = new OptionalWithDefaultHolder(2, 3, "4");
OptionalWithDefaultHolder actual = b2Json.fromJson("{\"a\": 2, \"b\": 3, \"c\": \"4\"}", OptionalWithDefaultHolder.class);
assertEquals(expected, actual);
}
}
private static class OptionalWithDefaultInvalidValue {
@B2Json.optionalWithDefault(defaultValue = "xxx")
private final int count;
@B2Json.constructor(params = "count")
private OptionalWithDefaultInvalidValue(int count) {
this.count = count;
}
}
@Test
public void testInvalidValueInOptionalWithDefault() throws B2JsonException {
// Any use of the class with B2Json should trigger the exception. Even
// serializing will need to initialize the handler, which should trigger
// an error.
thrown.expectMessage("error in default value for OptionalWithDefaultInvalidValue.count: Bad number");
B2Json.get().toJson(new OptionalWithDefaultInvalidValue(0));
}
@Test
public void testVersionRangeBackwards() throws B2JsonException {
thrown.expectMessage("last version 1 is before first version 2 in class com.backblaze.b2.json.B2JsonTest$VersionRangeBackwardsClass");
b2Json.toJson(new VersionRangeBackwardsClass(5));
}
private static class VersionRangeBackwardsClass {
@B2Json.required
@B2Json.versionRange(firstVersion = 2, lastVersion = 1)
private final int n;
@B2Json.constructor(params = "n")
private VersionRangeBackwardsClass(int n) {
this.n = n;
}
}
@Test
public void testConflictingVersions() throws B2JsonException {
thrown.expectMessage("must not specify both 'firstVersion' and 'versionRange' in class com.backblaze.b2.json.B2JsonTest$VersionConflictClass");
b2Json.toJson(new VersionConflictClass(5));
}
private static class VersionConflictClass {
@B2Json.required
@B2Json.firstVersion(firstVersion = 5)
@B2Json.versionRange(firstVersion = 2, lastVersion = 1)
private final int n;
@B2Json.constructor(params = "n")
private VersionConflictClass(int n) {
this.n = n;
}
}
private static final class Node {
@B2Json.optional
public String name;
@B2Json.optional
List<Node> childNodes;
@B2Json.constructor(params = "name, childNodes")
public Node(String name, List<Node> childNodes) {
this.name = name;
this.childNodes = childNodes;
}
}
@Test
public void testRecursiveTree() throws IOException, B2JsonException {
String tree1 =
"{\n" +
" \"childNodes\": null,\n" +
" \"name\": \"Degenerative\"\n" +
"}";
checkDeserializeSerialize(tree1, Node.class);
String tree2 =
"{\n" +
" \"childNodes\": [],\n" +
" \"name\": \"With Empty Children\"\n" +
"}";
checkDeserializeSerialize(tree2, Node.class);
String tree3 =
"{\n" +
" \"childNodes\": [\n" +
" {\n" +
" \"childNodes\": null,\n" +
" \"name\": \"Level 2 Child 1\"\n" +
" },\n" +
" {\n" +
" \"childNodes\": [\n" +
" {\n" +
" \"childNodes\": null,\n" +
" \"name\": \"Level 3 Child 1\"\n" +
" }\n" +
" ],\n" +
" \"name\": \"Level 2 Child 2\"\n" +
" }\n" +
" ],\n" +
" \"name\": \"Top\"\n" +
"}";
checkDeserializeSerialize(tree3, Node.class);
}
@Test
public void testEnumWithSpecialHandler() throws B2JsonException {
String json = "{\"letter\": \"b\"}";
LetterHolder holder = B2Json.get().fromJson(json, LetterHolder.class);
assertEquals(Letter.BEE, holder.letter);
}
private static class LetterHolder {
@B2Json.required
private final Letter letter;
@B2Json.constructor(params = "letter")
private LetterHolder(Letter letter) {
this.letter = letter;
}
}
private enum Letter {
BEE;
public static class JsonHandler implements B2JsonTypeHandler<Letter> {
@Override
public Type getHandledType() {
return Letter.class;
}
@Override
public void serialize(Letter obj, B2JsonOptions options, B2JsonWriter out) throws IOException {
out.writeString("b");
}
@Override
public Letter deserialize(B2JsonReader in, B2JsonOptions options) throws B2JsonException, IOException {
return deserializeUrlParam(in.readString());
}
@Override
public Letter deserializeUrlParam(String urlValue) {
B2Preconditions.checkArgument(urlValue.equals("b"));
return BEE;
}
@Override
public Letter defaultValueForOptional() {
return null;
}
@Override
public boolean isStringInJson() {
return true;
}
}
@SuppressWarnings("unused") // used by reflection
private static B2JsonTypeHandler<Letter> getJsonTypeHandler() {
return new Letter.JsonHandler();
}
}
@Test
public void testSerializeUnion() throws B2JsonException {
thrown.expectMessage("is a union base class, and cannot be serialized");
B2Json.get().toJson(new UnionAZ());
}
@Test
public void testFieldFromWrongTypeInUnion() throws B2JsonException {
final String json = "{ \"z\" : \"hello\", \"type\" : \"a\" }";
thrown.expectMessage("unknown field in com.backblaze.b2.json.B2JsonTest$SubclassA: z");
B2Json.get().fromJson(json, UnionAZ.class);
}
@Test
public void testMissingTypeInUnion() throws B2JsonException {
final String json = "{ \"a\" : 5 }";
thrown.expectMessage("missing 'type' in UnionAZ");
B2Json.get().fromJson(json, UnionAZ.class);
}
@Test
public void testUnknownTypeInUnion() throws B2JsonException {
final String json = "{ \"type\" : \"bad\" }";
thrown.expectMessage("unknown 'type' in UnionAZ: 'bad'");
B2Json.get().fromJson(json, UnionAZ.class);
}
@Test
public void testUnknownFieldInUnion() throws B2JsonException {
final String json = "{ \"badField\" : 5, \"type\": \"a\" }";
thrown.expectMessage("unknown field 'badField' in union type UnionAZ");
B2Json.get().fromJson(json, UnionAZ.class);
}
@Test
public void testSerializeUnionSubType() throws B2JsonException, IOException {
final String origJson = "{\n" +
" \"contained\": {\n" +
" \"a\": 1,\n" +
" \"b\": null,\n" +
" \"type\": \"a\"\n" +
" }\n" +
"}";
checkDeserializeSerialize(origJson, ContainsUnion.class);
}
@Test
public void testSerializeOptionalAndMissingUnion() throws B2JsonException, IOException {
final String origJson = "{\n" +
" \"contained\": null\n" +
"}";
checkDeserializeSerialize(origJson, ContainsOptionalUnion.class);
}
@Test
public void testSerializeUnregisteredUnionSubType() throws B2JsonException {
final SubclassUnregistered unregistered = new SubclassUnregistered("zzz");
final ContainsUnion container = new ContainsUnion(unregistered);
thrown.expectMessage("class com.backblaze.b2.json.B2JsonTest$SubclassUnregistered isn't a registered part of union class com.backblaze.b2.json.B2JsonTest$UnionAZ");
B2Json.get().toJson(container);
}
@B2Json.union(typeField = "type")
@B2Json.defaultForUnknownType(value = "{\"type\": \"a\", \"n\": 5}")
private static class UnionWithDefault {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("a", UnionWithDefaultClassA.class)
.build();
}
}
private static class UnionWithDefaultClassA extends UnionWithDefault {
@B2Json.required
private final int n;
@B2Json.constructor(params = "n")
private UnionWithDefaultClassA(int n) {
this.n = n;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UnionWithDefaultClassA that = (UnionWithDefaultClassA) o;
return n == that.n;
}
@Override
public int hashCode() {
return Objects.hash(n);
}
}
@Test
public void testUnionWithDefault() throws B2JsonException {
assertEquals(
new UnionWithDefaultClassA(5), // the default value
B2Json.get().fromJson("{\"type\": \"unknown\"}", UnionWithDefault.class)
);
assertEquals(
new UnionWithDefaultClassA(5), // the default value
B2Json.get().fromJson("{\"type\": \"unknown\", \"unknownField\": 5}", UnionWithDefault.class)
);
assertEquals(
new UnionWithDefaultClassA(99), // NOT the default value; the value provided
B2Json.get().fromJson("{\"type\": \"a\", \"n\": 99}", UnionWithDefault.class)
);
}
@B2Json.union(typeField = "type")
@B2Json.defaultForUnknownType(value = "{\"type\": \"a\", \"n\": 5}")
private static class UnionWithInvalidDefault {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("a", UnionWithInvalidDefaultClassA.class)
.build();
}
}
private static class UnionWithInvalidDefaultClassA extends UnionWithInvalidDefault {
@B2Json.constructor(params = "")
UnionWithInvalidDefaultClassA() {}
}
@Test
public void testUnionWithInvalidDefault() throws B2JsonException {
// The error should be caught when the class is first used, even if the default
// isn't used.
thrown.expectMessage("error in default value for union UnionWithInvalidDefault: unknown field 'n' in union type UnionWithInvalidDefault");
B2Json.get().toJson(new UnionWithInvalidDefaultClassA());
}
@B2Json.union(typeField = "type")
private static class UnionAZ {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("a", SubclassA.class)
.put("z", SubclassZ.class)
.build();
}
}
private static class SubclassA extends UnionAZ {
@B2Json.required
public final int a;
@B2Json.optional
public final Set<Integer> b;
@B2Json.constructor(params = "a, b")
private SubclassA(int a, Set<Integer> b) {
this.a = a;
this.b = b;
}
}
private static class SubclassZ extends UnionAZ {
@B2Json.required
public final String z;
@B2Json.constructor(params = "z")
private SubclassZ(String z) {
this.z = z;
}
}
private static class SubclassUnregistered extends UnionAZ {
@B2Json.required
public final String u;
@B2Json.constructor(params = "u")
private SubclassUnregistered(String u) {
this.u = u;
}
}
// i *soooo* wanted to call this class "North",
// but the more boring name "ContainsUnion" is clearer.
private static class ContainsUnion {
@B2Json.required
private final UnionAZ contained;
@B2Json.constructor(params = "contained")
private ContainsUnion(UnionAZ contained) {
this.contained = contained;
}
}
private static class ContainsOptionalUnion {
@B2Json.optional
private final UnionAZ contained;
@B2Json.constructor(params = "contained")
private ContainsOptionalUnion(UnionAZ contained) {
this.contained = contained;
}
}
@Test
public void testUnionWithFieldAnnotation() throws B2JsonException {
thrown.expectMessage("field annotations not allowed in union class");
B2Json.get().fromJson("{}", BadUnionWithFieldAnnotation.class);
}
@B2Json.union(typeField = "foo")
private static class BadUnionWithFieldAnnotation {
@B2Json.required
public int x;
}
@Test
public void testUnionWithConstructorAnnotation() throws B2JsonException {
thrown.expectMessage("constructor annotations not allowed in union class");
B2Json.get().fromJson("{}", BadUnionWithConstructorAnnotation.class);
}
@B2Json.union(typeField = "foo")
private static class BadUnionWithConstructorAnnotation {
@B2Json.constructor(params = "")
public BadUnionWithConstructorAnnotation() {}
}
@Test
public void testUnionWithoutGetMap() throws B2JsonException {
thrown.expectMessage("does not have a method getUnionTypeMap");
B2Json.get().fromJson("{}", UnionWithoutGetMap.class);
}
@B2Json.union(typeField = "type")
private static class UnionWithoutGetMap {}
@Test
public void testUnionTypeMapNotAMap() throws B2JsonException {
thrown.expectMessage("UnionWithNonMap.getUnionTypeMap() did not return a B2JsonUnionTypeMap");
B2Json.get().fromJson("{}", UnionWithNonMap.class);
}
@B2Json.union(typeField = "type")
private static class UnionWithNonMap {
public static String getUnionTypeMap() {
return "foo";
}
}
@Test
public void testUnionInheritsFromUnion() throws B2JsonException {
thrown.expectMessage("inherits from another class with a B2Json annotation");
B2Json.get().fromJson("{}", UnionThatInheritsFromUnion.class);
}
@B2Json.union(typeField = "type")
private static class UnionThatInheritsFromUnion extends UnionAZ {}
@Test
public void testUnionMemberIsNotSubclass() throws B2JsonException {
thrown.expectMessage("is not a subclass of");
B2Json.get().fromJson("{}", UnionWithMemberThatIsNotSubclass.class);
}
@B2Json.union(typeField = "type")
private static class UnionWithMemberThatIsNotSubclass {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("doesNotInherit", SubclassDoesNotInherit.class)
.build();
}
}
private static class SubclassDoesNotInherit {
@B2Json.constructor(params = "")
private SubclassDoesNotInherit(int a) { }
}
@Test
public void testUnionFieldHasDifferentTypes() throws B2JsonException {
thrown.expectMessage("field sameName has two different types");
B2Json.get().fromJson("{}", UnionXY.class);
}
@B2Json.union(typeField = "type")
private static class UnionXY {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("x", SubclassX.class)
.put("y", SubclassY.class)
.build();
}
}
private static class SubclassX extends UnionXY {
@B2Json.required
public final int sameName;
@B2Json.constructor(params = "sameName")
private SubclassX(int sameName) {
this.sameName = sameName;
}
}
private static class SubclassY extends UnionXY {
@B2Json.required
public final String sameName;
@B2Json.constructor(params = "sameName")
private SubclassY(String sameName) {
this.sameName = sameName;
}
}
@Test
public void testUnionSubclassNotInTypeMap() throws B2JsonException {
thrown.expectMessage("is not in the type map");
B2Json.get().toJson(new SubclassM());
}
@B2Json.union(typeField = "type")
private static class UnionM {
public static B2JsonUnionTypeMap getUnionTypeMap() {
return B2JsonUnionTypeMap.builder().build();
}
}
private static class SubclassM extends UnionM {
}
@Test
public void testUnionMapHasDuplicateName() throws B2JsonException {
thrown.expectMessage("duplicate type name in union type map: 'd'");
B2Json.get().toJson(new SubclassD1());
}
@B2Json.union(typeField = "type")
private static class UnionD {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("d", SubclassD1.class)
.put("d", SubclassD2.class)
.build();
}
}
private static class SubclassD1 extends UnionD {
}
private static class SubclassD2 extends UnionD {
}
@Test
public void testUnionMapHasDuplicateClass() throws B2JsonException {
thrown.expectMessage("duplicate class in union type map: class com.backblaze.b2.json.B2JsonTest$SubclassF");
B2Json.get().toJson(new SubclassF());
}
@B2Json.union(typeField = "type")
private static class UnionF {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("f1", SubclassF.class)
.put("f2", SubclassF.class)
.build();
}
}
private static class SubclassF extends UnionF {
}
@Test
public void testUnionSubclassHasNullOptionalField() throws B2JsonException, IOException {
final String json = "{\n" +
" \"name\": null,\n" +
" \"type\": \"g\"\n" +
"}";
checkDeserializeSerialize(json, UnionG.class);
}
@B2Json.union(typeField = "type")
private static class UnionG {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("g", SubclassG.class)
.build();
}
}
private static class SubclassG extends UnionG {
@B2Json.optional
final String name;
@B2Json.constructor(params = "name")
private SubclassG(String name) {
this.name = name;
}
}
@Test
public void testUnionSubclassHasNullRequiredField() throws B2JsonException, IOException {
final String json = "{\n" +
" \"name\": null,\n" +
" \"type\": \"h\"\n" +
"}";
thrown.expectMessage("required field name cannot be null");
checkDeserializeSerialize(json, UnionH.class);
}
@B2Json.union(typeField = "type")
private static class UnionH {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("h", SubclassH.class)
.build();
}
}
private static class SubclassH extends UnionH {
@B2Json.required
final String name;
@B2Json.constructor(params = "name")
private SubclassH(String name) {
this.name = name;
}
}
@Test
public void testRequiredFieldNotInVersion() throws B2JsonException {
final String json = "{}";
final B2JsonOptions options = B2JsonOptions.builder().setVersion(1).build();
final VersionedContainer obj = b2Json.fromJson(json, VersionedContainer.class, options);
assertEquals(0, obj.x);
assertEquals(1, obj.version);
}
@Test
public void testRequiredFieldMissingInVersion() throws B2JsonException {
final String json = "{}";
final B2JsonOptions options = B2JsonOptions.builder().setVersion(5).build();
thrown.expectMessage("required field x is missing");
b2Json.fromJson(json, VersionedContainer.class, options);
}
@Test
public void testFieldPresentButNotInVersion() throws B2JsonException {
final String json = "{ \"x\": 5 }";
final B2JsonOptions options = B2JsonOptions.builder().setVersion(1).build();
thrown.expectMessage("field x is not in version 1");
b2Json.fromJson(json, VersionedContainer.class, options);
}
@Test
public void testFieldPresentAndInVersion() throws B2JsonException {
final String json = "{ \"x\": 7 }";
final B2JsonOptions options = B2JsonOptions.builder().setVersion(5).build();
final VersionedContainer obj = b2Json.fromJson(json, VersionedContainer.class, options);
assertEquals(7, obj.x);
assertEquals(5, obj.version);
}
@Test
public void testSerializeSkipFieldNotInVersion() throws B2JsonException {
// Version 3 is too soon
{
final B2JsonOptions options = B2JsonOptions.builder().setVersion(3).build();
assertEquals(
"{}",
b2Json.toJson(new VersionedContainer(3, 5), options)
);
}
// Version 4 is the first version where it's present
{
final B2JsonOptions options = B2JsonOptions.builder().setVersion(4).build();
assertEquals(
"{\n \"x\": 3\n}",
b2Json.toJson(new VersionedContainer(3, 5), options)
);
}
// Version 6 is the last version where it's present
{
final B2JsonOptions options = B2JsonOptions.builder().setVersion(4).build();
assertEquals(
"{\n \"x\": 3\n}",
b2Json.toJson(new VersionedContainer(3, 5), options)
);
}
// Version 7 is too late.
{
final B2JsonOptions options = B2JsonOptions.builder().setVersion(7).build();
assertEquals(
"{}",
b2Json.toJson(new VersionedContainer(3, 5), options)
);
}
}
@Test
public void testSerializeIncludeFieldInVersion() throws B2JsonException {
final B2JsonOptions options = B2JsonOptions.builder().setVersion(5).build();
assertEquals(
"{\n" +
" \"x\": 3\n" +
"}",
b2Json.toJson(new VersionedContainer(3, 5), options)
);
}
private static class VersionedContainer {
@B2Json.versionRange(firstVersion = 4, lastVersion = 6)
@B2Json.required
public final int x;
@B2Json.ignored
public final int version;
@B2Json.constructor(params = "x, v", versionParam = "v")
public VersionedContainer(int x, int v) {
this.x = x;
this.version = v;
}
}
@Test
public void testParamListedTwice() throws B2JsonException {
final B2JsonOptions options = B2JsonOptions.builder().build();
thrown.expectMessage("com.backblaze.b2.json.B2JsonTest$ConstructorParamListedTwice constructor parameter 'a' listed twice");
b2Json.fromJson("{}", ConstructorParamListedTwice.class, options);
}
private static class TestClassOne {
@B2Json.versionRange(firstVersion = 1, lastVersion = 3)
@B2Json.required
final String name;
@B2Json.required
final int number;
@B2Json.constructor(params = "name, number")
private TestClassOne(String name, int number) {
this.name = name;
this.number = number;
}
}
@Test
public void testToJson() {
final TestClassOne testClassOne = new TestClassOne("testABC", 1);
final String testClassOneStr = B2Json.toJsonOrThrowRuntime(testClassOne);
assertEquals("{\n \"name\": \"testABC\",\n \"number\": 1\n}", testClassOneStr);
}
@Test
public void testToJsonWithDefaultOptions() {
final B2JsonOptions options = B2JsonOptions.builder().build();
final TestClassOne testClassOne = new TestClassOne("testABC", 1);
final String testClassOneStr = B2Json.toJsonOrThrowRuntime(testClassOne, options);
assertEquals("{\n \"name\": \"testABC\",\n \"number\": 1\n}", testClassOneStr);
}
@Test
public void testToJsonWithOptions() {
// name is only in first 3 versions
final B2JsonOptions options = B2JsonOptions.builder().setVersion(4).build();
final TestClassOne testClassOne = new TestClassOne("testABC", 1);
final String testClassOneStr = B2Json.toJsonOrThrowRuntime(testClassOne, options);
assertEquals("{\n \"number\": 1\n}", testClassOneStr);
}
@Test
public void testToJsonThrows() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("failed to convert to json: required field a cannot be null");
RequiredObject obj = new RequiredObject(null);
B2Json.toJsonOrThrowRuntime(obj);
}
private static class SecureContainer {
@B2Json.required
@B2Json.sensitive
private final String sensitiveString;
@B2Json.required
private final String insensitiveString;
@B2Json.constructor(params = "sensitiveString,insensitiveString")
public SecureContainer(String secureString, String insecureString) {
this.sensitiveString = secureString;
this.insensitiveString = insecureString;
}
}
@Test
public void testSensitiveRedactedWhenOptionSet() {
final B2JsonOptions options = B2JsonOptions.builder().setRedactSensitive(true).build();
final SecureContainer secureContainer = new SecureContainer("foo", "bar");
assertEquals("{\n \"insensitiveString\": \"bar\",\n \"sensitiveString\": \"***REDACTED***\"\n}",
B2Json.toJsonOrThrowRuntime(secureContainer, options));
}
@Test
public void testSensitiveWrittenWhenOptionNotSet() {
final B2JsonOptions options = B2JsonOptions.builder().setRedactSensitive(false).build();
final SecureContainer secureContainer = new SecureContainer("foo", "bar");
assertEquals("{\n \"insensitiveString\": \"bar\",\n \"sensitiveString\": \"foo\"\n}",
B2Json.toJsonOrThrowRuntime(secureContainer, options));
}
private static class OmitNullBadTestClass {
@B2Json.optional(omitNull = true)
private final int omitNullInt;
@B2Json.constructor(params = "omitNullInt")
public OmitNullBadTestClass(int omitNullInt) {
this.omitNullInt = omitNullInt;
}
}
private static class OmitNullTestClass {
@B2Json.optional(omitNull = true)
private final String omitNullString;
@B2Json.optional
private final String regularString;
@B2Json.optional(omitNull = true)
private final Integer omitNullInteger;
@B2Json.optional
private final Integer regularInteger;
@B2Json.constructor(params = "omitNullString, regularString, omitNullInteger, regularInteger")
public OmitNullTestClass(String omitNullString, String regularString, Integer omitNullInteger, Integer regularInteger) {
this.omitNullString = omitNullString;
this.regularString = regularString;
this.omitNullInteger = omitNullInteger;
this.regularInteger = regularInteger;
}
}
@Test
public void testOmitNullWithNullInputs() {
final OmitNullTestClass object = new OmitNullTestClass(null, null, null, null);
final String actual = B2Json.toJsonOrThrowRuntime(object);
// The omitNullString and omitNullInteger fields should not be present in the output
assertEquals("{\n" +
" \"regularInteger\": null,\n" +
" \"regularString\": null\n" +
"}", actual);
}
@Test
public void testOmitNullWithNonNullInputs() {
final OmitNullTestClass object = new OmitNullTestClass("foo", "bar", 1, 1);
final String actual = B2Json.toJsonOrThrowRuntime(object);
// All the fields should be in the output
assertEquals("{\n" +
" \"omitNullInteger\": 1,\n" +
" \"omitNullString\": \"foo\",\n" +
" \"regularInteger\": 1,\n" +
" \"regularString\": \"bar\"\n" +
"}", actual);
}
@Test
public void testOmitNullCreateFromEmpty() {
final OmitNullTestClass actual = B2Json.fromJsonOrThrowRuntime("{}", OmitNullTestClass.class);
assertNull(actual.omitNullString);
assertNull(actual.regularString);
assertNull(actual.omitNullInteger);
assertNull(actual.regularInteger);
}
@Test
public void testOmitNullOnPrimitive() throws B2JsonException {
thrown.expectMessage("Field OmitNullBadTestClass.omitNullInt declared with 'omitNull = true' but is a primitive type");
final OmitNullBadTestClass bad = new OmitNullBadTestClass(123);
B2Json.toJsonOrThrowRuntime(bad);
}
/**
* Because of serialization, the object returned from B2Json will never be the same object as an
* instantiated one.
*
* So we just look at and test the members.
*/
@Test
public void testFromJson() {
final String testClassOneStr = "{\n \"name\": \"testABC\",\n \"number\": 1\n}";
final TestClassOne testClassOne = B2Json.fromJsonOrThrowRuntime(testClassOneStr, TestClassOne.class);
assertEquals("testABC", testClassOne.name);
assertEquals(1, testClassOne.number);
}
@Test
public void testFromJsonWithDefaultOptions() {
final B2JsonOptions options = B2JsonOptions.builder().build();
final String testClassOneStr = "{\n \"name\": \"testABC\",\n \"number\": 1\n}";
final TestClassOne testClassOne = B2Json.fromJsonOrThrowRuntime(testClassOneStr, TestClassOne.class, options);
assertEquals("testABC", testClassOne.name);
assertEquals(1, testClassOne.number);
}
@Test
public void testFromJsonWithOptions() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("failed to convert from json: field name is not in version 6");
final B2JsonOptions options = B2JsonOptions.builder().setVersion(6).build();
final String testClassOneStr = "{\n \"name\": \"testABC\",\n \"number\": 1\n}";
final TestClassOne testClassOne = B2Json.fromJsonOrThrowRuntime(testClassOneStr, TestClassOne.class, options);
}
@Test
public void testFromJsonThrows() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("failed to convert from json: required field number is missing");
final String testClassOneStr = "{\n \"name\": \"testABC\"\n}";
B2Json.fromJsonOrThrowRuntime(testClassOneStr, TestClassOne.class);
}
private static class ConstructorParamListedTwice {
@B2Json.required
public final int a;
@B2Json.optional
public final int b;
@B2Json.constructor(params = "a, a")
public ConstructorParamListedTwice(int a, int b) {
this.a = a;
this.b = b;
}
}
@Test
public void testRecursiveUnion() {
final String json = B2Json.toJsonOrThrowRuntime(new RecursiveUnionNode(new RecursiveUnionNode(null)));
B2Json.fromJsonOrThrowRuntime(json, RecursiveUnion.class);
}
@B2Json.union(typeField = "type")
private static class RecursiveUnion {
public static B2JsonUnionTypeMap getUnionTypeMap() throws B2JsonException {
return B2JsonUnionTypeMap
.builder()
.put("node", RecursiveUnionNode.class)
.build();
}
}
private static class RecursiveUnionNode extends RecursiveUnion {
@B2Json.optional
private final RecursiveUnion recursiveUnion;
@B2Json.constructor(params = "recursiveUnion")
private RecursiveUnionNode(RecursiveUnion recursiveUnion) {
this.recursiveUnion = recursiveUnion;
}
}
/**
* A regression test for a case where a class has a field with a default value,
* and the class of the default value has a class initializer.
*/
@Test
public void testClassInitializationInDefaultValue() {
B2Json.fromJsonOrThrowRuntime("{}", TestClassInit_ClassWithDefaultValue.class);
}
private static class TestClassInit_ClassWithDefaultValue {
@B2Json.optionalWithDefault(defaultValue = "{}")
private final TestClassInit_ClassThatDoesInitializition objThatDoesInit;
@B2Json.constructor(params = "objThatDoesInit")
private TestClassInit_ClassWithDefaultValue(TestClassInit_ClassThatDoesInitializition objThatDoesInit) {
this.objThatDoesInit = objThatDoesInit;
}
}
private static class TestClassInit_ClassThatDoesInitializition {
private static TestClassInit_ClassThatDoesInitializition defaultValue =
B2Json.fromJsonOrThrowRuntime("{}", TestClassInit_ClassThatDoesInitializition.class);
@B2Json.constructor(params = "")
TestClassInit_ClassThatDoesInitializition() {}
}
private static class CharSquenceTestClass {
@B2Json.required
CharSequence sequence;
@B2Json.constructor(params = "sequence")
public CharSquenceTestClass(CharSequence sequence) {
this.sequence = sequence;
}
}
@Test
public void testCharSequenceSerialization() {
final CharSequence sequence ="foobarbaz".subSequence(3, 6);
final CharSquenceTestClass obj = new CharSquenceTestClass(sequence);
final String actual = B2Json.toJsonOrThrowRuntime(obj);
final String expected = "{\n" +
" \"sequence\": \"bar\"\n" +
"}";
assertEquals(expected, actual);
}
@Test
public void testCharSequenceDeserialization() {
final String input = "{\n" +
" \"sequence\": \"bar\"\n" +
"}";
final CharSquenceTestClass obj = B2Json.fromJsonOrThrowRuntime(input, CharSquenceTestClass.class);
assertEquals("bar", obj.sequence);
// the underlying implementation of CharSequence that we deserialize is String
assertEquals(String.class, obj.sequence.getClass());
}
private static class SerializationTestClass {
@B2Json.required
final String stringVal;
@B2Json.required
final int intVal;
@B2Json.required
final boolean booleanVal;
@B2Json.required
final Map<String, Integer> mapVal;
@B2Json.required
final List<String> arrayVal;
@B2Json.constructor(params = "stringVal, intVal, booleanVal, mapVal, arrayVal")
public SerializationTestClass(String stringVal, int intVal, boolean booleanVal, Map<String, Integer> mapVal, List<String> arrayVal) {
this.stringVal = stringVal;
this.intVal = intVal;
this.booleanVal = booleanVal;
this.mapVal = mapVal;
this.arrayVal = arrayVal;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SerializationTestClass that = (SerializationTestClass) o;
return intVal == that.intVal &&
booleanVal == that.booleanVal &&
Objects.equals(stringVal, that.stringVal) &&
Objects.equals(mapVal, that.mapVal) &&
Objects.equals(arrayVal, that.arrayVal);
}
@Override
public int hashCode() {
return Objects.hash(stringVal, intVal, booleanVal, mapVal, arrayVal);
}
}
/**
* Compact serialization is not an original feature of B2Json and thus
* is being explicitly tested here. All the above tests were created
* before the compact option became available and thus all implicitly
* test the pretty serialization output (which is still the default).
*/
@Test
public void testCompactSerialization() throws B2JsonException {
// setup my test object
final Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
final List<String> array = new ArrayList<>();
array.add("a");
array.add("b");
array.add("c");
final SerializationTestClass original = new SerializationTestClass(
"original string value",
123,
true,
map,
array);
// convert test object to JSON string
final B2JsonOptions options = B2JsonOptions.builder()
.setSerializationOption(B2JsonOptions.SerializationOption.COMPACT)
.build();
final String actual = B2Json.get().toJson(original, options);
final String expected = "{\"arrayVal\":[\"a\",\"b\",\"c\"],\"booleanVal\":true,\"intVal\":123,\"mapVal\":{\"one\":1,\"two\":2,\"three\":3},\"stringVal\":\"original string value\"}";
assertEquals(expected, actual);
// Convert JSON string back to SerializationTestClass to ensure that
// the produced json can round-trip properly.
final SerializationTestClass derived = B2Json.get().fromJson(actual, SerializationTestClass.class);
assertEquals(original, derived);
}
@Test
public void testTopLevelObjectIsParameterizedType() throws NoSuchFieldException, IOException, B2JsonException {
final Item<Integer> item = new Item<>(123);
// Get a reference to a type object that describes an Item<Integer>...
final Type type = ClassThatUsesGenerics.class.getDeclaredField("integerItem").getGenericType();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
B2Json.get().toJson(item, B2JsonOptions.DEFAULT, out, type);
final String json = out.toString(B2StringUtil.UTF8);
assertEquals("{\n" +
" \"value\": 123\n" +
"}",
json);
// Now try without the type information
thrown.expect(B2JsonException.class);
thrown.expectMessage("actualTypeArguments must be same length as class' type parameters");
B2Json.get().toJson(item, B2JsonOptions.DEFAULT, out);
}
@Test
public void testGenerics() throws B2JsonException {
final ClassThatUsesGenerics classThatUsesGenerics = new ClassThatUsesGenerics(
999,
new Item<>("the string"),
new Item<>(123),
new Item<>(new Item<>(456L))
);
final String expected = "{\n" +
" \"id\": 999,\n" +
" \"integerItem\": {\n" +
" \"value\": 123\n" +
" },\n" +
" \"longItemItem\": {\n" +
" \"value\": {\n" +
" \"value\": 456\n" +
" }\n" +
" },\n" +
" \"stringItem\": {\n" +
" \"value\": \"the string\"\n" +
" }\n" +
"}";
assertEquals(expected, b2Json.toJson(classThatUsesGenerics));
final ClassThatUsesGenerics classThatUsesGenericsFromJson = b2Json.fromJson(expected, ClassThatUsesGenerics.class);
assertEquals(999, classThatUsesGenericsFromJson.id);
assertEquals("the string", classThatUsesGenericsFromJson.stringItem.value);
assertEquals(new Long(456), classThatUsesGenericsFromJson.longItemItem.value.value);
assertEquals(new Integer(123), classThatUsesGenericsFromJson.integerItem.value);
}
@Test
public void testGenericArraySupport() throws B2JsonException {
final ClassWithGenericArrays objectWithGenericArrays =
new ClassWithGenericArrays(
new ItemArray<>(new Integer[] {0, 1, 2, 3}),
new ItemArray<>(new String[] {"a", "b"}));
final String expected = "" +
"{\n" +
" \"intArray\": {\n" +
" \"values\": [\n" +
" 0,\n" +
" 1,\n" +
" 2,\n" +
" 3\n" +
" ]\n" +
" },\n" +
" \"stringArray\": {\n" +
" \"values\": [\n" +
" \"a\",\n" +
" \"b\"\n" +
" ]\n" +
" }\n" +
"}";
assertEquals(expected, b2Json.toJson(objectWithGenericArrays));
}
private static class ClassThatUsesGenerics {
@B2Json.required
private int id;
@B2Json.required
private final Item<String> stringItem;
@B2Json.required
private final Item<Integer> integerItem;
@B2Json.required
private final Item<Item<Long>> longItemItem;
@B2Json.constructor(params = "id, stringItem, integerItem, longItemItem")
public ClassThatUsesGenerics(
int id,
Item<String> stringItem,
Item<Integer> integerItem,
Item<Item<Long>> longItemItem) {
this.id = id;
this.stringItem = stringItem;
this.integerItem = integerItem;
this.longItemItem = longItemItem;
}
}
private static class Item<T> {
@B2Json.required
private final T value;
@B2Json.constructor(params = "value")
public Item(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
private static class ClassWithGenericArrays {
@B2Json.required
private final ItemArray<Integer> intArray;
@B2Json.required
private final ItemArray<String> stringArray;
@B2Json.constructor(params = "intArray, stringArray")
public ClassWithGenericArrays(ItemArray<Integer> intArray, ItemArray<String> stringArray) {
this.intArray = intArray;
this.stringArray = stringArray;
}
}
private static class ItemArray<T> {
@B2Json.required
private final T[] values;
@B2Json.constructor(params = "values")
public ItemArray(T[] values) {
this.values = values;
}
}
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"",
"unused",
"\"",
",",
"\"",
"WeakerAccess",
"\"",
"}",
")",
"public",
"class",
"B2JsonTest",
"extends",
"B2BaseTest",
"{",
"@",
"Rule",
"public",
"ExpectedException",
"thrown",
"=",
"ExpectedException",
".",
"none",
"(",
")",
";",
"private",
"static",
"final",
"class",
"Container",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"a",
";",
"@",
"B2Json",
".",
"optional",
"public",
"final",
"String",
"b",
";",
"@",
"B2Json",
".",
"ignored",
"public",
"int",
"c",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a, b",
"\"",
")",
"public",
"Container",
"(",
"int",
"a",
",",
"String",
"b",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"this",
".",
"b",
"=",
"b",
";",
"this",
".",
"c",
"=",
"5",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"Container",
")",
")",
"{",
"return",
"false",
";",
"}",
"Container",
"other",
"=",
"(",
"Container",
")",
"o",
";",
"return",
"a",
"==",
"other",
".",
"a",
"&&",
"(",
"b",
"==",
"null",
"?",
"other",
".",
"b",
"==",
"null",
":",
"b",
".",
"equals",
"(",
"other",
".",
"b",
")",
")",
";",
"}",
"}",
"private",
"static",
"final",
"B2Json",
"b2Json",
"=",
"B2Json",
".",
"get",
"(",
")",
";",
"@",
"Test",
"public",
"void",
"testBoolean",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"false",
"\"",
",",
"Boolean",
".",
"class",
")",
";",
"checkDeserializeSerialize",
"(",
"\"",
"true",
"\"",
",",
"Boolean",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testBigDecimal",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"13",
"\"",
",",
"BigDecimal",
".",
"class",
")",
";",
"checkDeserializeSerialize",
"(",
"\"",
"127.5243872835782375823758273582735",
"\"",
",",
"BigDecimal",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testBigInteger",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"13",
"\"",
",",
"BigInteger",
".",
"class",
")",
";",
"checkDeserializeSerialize",
"(",
"\"",
"31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470",
"\"",
",",
"BigDecimal",
".",
"class",
")",
";",
"checkDeserializeSerialize",
"(",
"\"",
"-271828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642742746",
"\"",
",",
"BigDecimal",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testByte",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"13",
"\"",
",",
"Byte",
".",
"class",
")",
";",
"checkDeserializeSerialize",
"(",
"\"",
"-37",
"\"",
",",
"Byte",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testChar",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"13",
"\"",
",",
"Character",
".",
"class",
")",
";",
"checkDeserializeSerialize",
"(",
"\"",
"65000",
"\"",
",",
"Character",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testInteger",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"-1234567",
"\"",
",",
"Integer",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testLong",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"123456789000",
"\"",
",",
"Long",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testFloat",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"3.5",
"\"",
",",
"Float",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDouble",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"2.0E10",
"\"",
",",
"Double",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testLocalDate",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"\\\"",
"20150401",
"\\\"",
"\"",
",",
"LocalDate",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testLocalDateTime",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"\\\"",
"d20150401_m123456",
"\\\"",
"\"",
",",
"LocalDateTime",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDuration",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"\\\"",
"4d3h2m1s",
"\\\"",
"\"",
",",
"Duration",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testObject",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"Container",
"obj",
"=",
"new",
"Container",
"(",
"41",
",",
"\"",
"hello",
"\"",
")",
";",
"assertEquals",
"(",
"json",
",",
"b2Json",
".",
"toJson",
"(",
"obj",
")",
")",
";",
"assertEquals",
"(",
"obj",
",",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testUnionWithTypeFieldLast",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 5,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"a",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"UnionAZ",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testUnionWithTypeFieldNotLast",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"z",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"z",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"UnionAZ",
".",
"class",
")",
";",
"}",
"/**\n * Regression test to make sure that when handlers are created from\n * B2JsonUnionHandler they work properly.\n *\n * This test makes a new B2Json, and de-serializes the union type, so\n * it's sure that the B2JsonUnionBaseHandler gets initialized first,\n * which is what triggered the bug.\n */",
"@",
"Test",
"public",
"void",
"testUnionCreatesHandlers",
"(",
")",
"throws",
"B2JsonException",
"{",
"(",
"new",
"B2Json",
"(",
")",
")",
".",
"fromJson",
"(",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"a",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 5,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": [10]",
"\"",
"+",
"\"",
"}",
"\"",
",",
"UnionAZ",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testComment",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{ // this is a comment",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"} // comment to eof",
"\"",
";",
"String",
"jsonWithoutComment",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"Container",
"obj",
"=",
"new",
"Container",
"(",
"41",
",",
"\"",
"hello",
"\"",
")",
";",
"assertEquals",
"(",
"jsonWithoutComment",
",",
"b2Json",
".",
"toJson",
"(",
"obj",
")",
")",
";",
"assertEquals",
"(",
"obj",
",",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testNoCommentInString",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"he//o",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"Container",
"obj",
"=",
"new",
"Container",
"(",
"41",
",",
"\"",
"he//o",
"\"",
")",
";",
"assertEquals",
"(",
"json",
",",
"b2Json",
".",
"toJson",
"(",
"obj",
")",
")",
";",
"assertEquals",
"(",
"obj",
",",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testBadComment",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{ / ",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"invalid comment: single slash",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testMissingComma",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"object should end with brace but found: ",
"\\\"",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testExtraComma",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"string does not start with quote",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDuplicateField",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"duplicate field: a",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDisallowIgnored",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"c",
"\\\"",
": 7",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"unknown field",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDisallowUnknown",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"x",
"\\\"",
": 7",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"unknown field",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"Discarder",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"a",
";",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"c",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a,c",
"\"",
",",
"discards",
"=",
"\"",
"b",
"\"",
")",
"private",
"Discarder",
"(",
"int",
"a",
",",
"int",
"c",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"this",
".",
"c",
"=",
"c",
";",
"}",
"}",
"private",
"static",
"class",
"DiscardingIgnoredFieldIsOk",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"a",
";",
"@",
"B2Json",
".",
"ignored",
"public",
"final",
"int",
"c",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a",
"\"",
",",
"discards",
"=",
"\"",
"b,c",
"\"",
")",
"private",
"DiscardingIgnoredFieldIsOk",
"(",
"int",
"a",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"this",
".",
"c",
"=",
"42",
";",
"}",
"}",
"private",
"static",
"class",
"DiscardingNonIgnoredFieldIsIllegal",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"a",
";",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"c",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a,c",
"\"",
",",
"discards",
"=",
"\"",
"b,c",
"\"",
")",
"private",
"DiscardingNonIgnoredFieldIsIllegal",
"(",
"int",
"a",
",",
"int",
"c",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"this",
".",
"c",
"=",
"c",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testAllowUnknown",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"x",
"\\\"",
": 7",
"\"",
"+",
"\"",
"}",
"\"",
";",
"Container",
"c",
"=",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
",",
"B2JsonOptions",
".",
"DEFAULT_AND_ALLOW_EXTRA_FIELDS",
")",
";",
"String",
"expectedJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expectedJson",
",",
"b2Json",
".",
"toJson",
"(",
"c",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testAllowButSkipDiscarded",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"jsonWithExtra",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"c",
"\\\"",
": 7",
"\"",
"+",
"\"",
"}",
"\"",
";",
"final",
"Discarder",
"discarder",
"=",
"b2Json",
".",
"fromJson",
"(",
"jsonWithExtra",
",",
"Discarder",
".",
"class",
")",
";",
"assertEquals",
"(",
"41",
",",
"discarder",
".",
"a",
")",
";",
"assertEquals",
"(",
"7",
",",
"discarder",
".",
"c",
")",
";",
"final",
"String",
"expectedJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"c",
"\\\"",
": 7",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expectedJson",
",",
"b2Json",
".",
"toJson",
"(",
"discarder",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDiscardingIgnoredFieldIsOk",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"jsonWithExtra",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"c",
"\\\"",
": 7",
"\"",
"+",
"\"",
"}",
"\"",
";",
"final",
"DiscardingIgnoredFieldIsOk",
"discarder",
"=",
"b2Json",
".",
"fromJson",
"(",
"jsonWithExtra",
",",
"DiscardingIgnoredFieldIsOk",
".",
"class",
")",
";",
"assertEquals",
"(",
"41",
",",
"discarder",
".",
"a",
")",
";",
"assertEquals",
"(",
"42",
",",
"discarder",
".",
"c",
")",
";",
"final",
"String",
"expectedJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expectedJson",
",",
"b2Json",
".",
"toJson",
"(",
"discarder",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDiscardingNonIgnoredFieldIsIllegal",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"DiscardingNonIgnoredFieldIsIllegal's field 'c' cannot be discarded: it's REQUIRED. only non-existent or IGNORED fields can be discarded.",
"\"",
")",
";",
"final",
"String",
"jsonWithExtra",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 41,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": ",
"\\\"",
"hello",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"c",
"\\\"",
": 7",
"\"",
"+",
"\"",
"}",
"\"",
";",
"b2Json",
".",
"fromJson",
"(",
"jsonWithExtra",
",",
"DiscardingNonIgnoredFieldIsIllegal",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testMissingRequired",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"b",
"\\\"",
" : ",
"\\\"",
"hello",
"\\\"",
" }",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"required field a is missing",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"Container",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"Empty",
"{",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"\"",
")",
"Empty",
"(",
")",
"{",
"}",
"}",
"private",
"static",
"class",
"AllOptionalTypes",
"{",
"@",
"B2Json",
".",
"optional",
"boolean",
"v_boolean",
";",
"@",
"B2Json",
".",
"optional",
"byte",
"v_byte",
";",
"@",
"B2Json",
".",
"optional",
"int",
"v_int",
";",
"@",
"B2Json",
".",
"optional",
"char",
"v_char",
";",
"@",
"B2Json",
".",
"optional",
"long",
"v_long",
";",
"@",
"B2Json",
".",
"optional",
"float",
"v_float",
";",
"@",
"B2Json",
".",
"optional",
"double",
"v_double",
";",
"@",
"B2Json",
".",
"optional",
"String",
"v_string",
";",
"@",
"B2Json",
".",
"optional",
"Empty",
"v_empty",
";",
"@",
"B2Json",
".",
"optional",
"Color",
"v_color",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"v_boolean, v_byte, v_char, v_int, v_long, v_float, v_double, v_string, v_empty, v_color",
"\"",
")",
"public",
"AllOptionalTypes",
"(",
"boolean",
"v_boolean",
",",
"byte",
"v_byte",
",",
"char",
"v_char",
",",
"int",
"v_int",
",",
"long",
"v_long",
",",
"float",
"v_float",
",",
"double",
"v_double",
",",
"String",
"v_string",
",",
"Empty",
"v_empty",
",",
"Color",
"v_color",
")",
"{",
"this",
".",
"v_boolean",
"=",
"v_boolean",
";",
"this",
".",
"v_byte",
"=",
"v_byte",
";",
"this",
".",
"v_int",
"=",
"v_int",
";",
"this",
".",
"v_char",
"=",
"v_char",
";",
"this",
".",
"v_long",
"=",
"v_long",
";",
"this",
".",
"v_float",
"=",
"v_float",
";",
"this",
".",
"v_double",
"=",
"v_double",
";",
"this",
".",
"v_string",
"=",
"v_string",
";",
"this",
".",
"v_empty",
"=",
"v_empty",
";",
"this",
".",
"v_color",
"=",
"v_color",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testOptionalNotPresent",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{}",
"\"",
";",
"AllOptionalTypes",
"obj",
"=",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"AllOptionalTypes",
".",
"class",
")",
";",
"assertFalse",
"(",
"obj",
".",
"v_boolean",
")",
";",
"assertEquals",
"(",
"0",
",",
"obj",
".",
"v_byte",
")",
";",
"assertEquals",
"(",
"0",
",",
"obj",
".",
"v_char",
")",
";",
"assertEquals",
"(",
"0",
",",
"obj",
".",
"v_int",
")",
";",
"assertEquals",
"(",
"0",
",",
"obj",
".",
"v_long",
")",
";",
"assertEquals",
"(",
"0.0",
",",
"obj",
".",
"v_float",
",",
"0.0",
")",
";",
"assertEquals",
"(",
"0.0",
",",
"obj",
".",
"v_double",
",",
"0.0",
")",
";",
"assertNull",
"(",
"obj",
".",
"v_string",
")",
";",
"assertNull",
"(",
"obj",
".",
"v_empty",
")",
";",
"String",
"expectedJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_boolean",
"\\\"",
": false,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_byte",
"\\\"",
": 0,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_char",
"\\\"",
": 0,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_color",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_double",
"\\\"",
": 0.0,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_empty",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_float",
"\\\"",
": 0.0,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_int",
"\\\"",
": 0,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_long",
"\\\"",
": 0,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_string",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expectedJson",
",",
"b2Json",
".",
"toJson",
"(",
"obj",
")",
")",
";",
"checkDeserializeSerialize",
"(",
"expectedJson",
",",
"AllOptionalTypes",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOptionalsPresentInUrl",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"parameterMap",
"=",
"makeParameterMap",
"(",
"\"",
"v_boolean",
"\"",
",",
"\"",
"true",
"\"",
",",
"\"",
"v_byte",
"\"",
",",
"\"",
"5",
"\"",
",",
"\"",
"v_char",
"\"",
",",
"\"",
"6",
"\"",
",",
"\"",
"v_color",
"\"",
",",
"\"",
"BLUE",
"\"",
",",
"\"",
"v_double",
"\"",
",",
"\"",
"7.0",
"\"",
",",
"\"",
"v_float",
"\"",
",",
"\"",
"8.0",
"\"",
",",
"\"",
"v_int",
"\"",
",",
"\"",
"9",
"\"",
",",
"\"",
"v_long",
"\"",
",",
"\"",
"10",
"\"",
",",
"\"",
"v_string",
"\"",
",",
"\"",
"abc",
"\"",
")",
";",
"AllOptionalTypes",
"obj",
"=",
"b2Json",
".",
"fromUrlParameterMap",
"(",
"parameterMap",
",",
"AllOptionalTypes",
".",
"class",
")",
";",
"assertTrue",
"(",
"obj",
".",
"v_boolean",
")",
";",
"assertEquals",
"(",
"5",
",",
"obj",
".",
"v_byte",
")",
";",
"assertEquals",
"(",
"6",
",",
"obj",
".",
"v_char",
")",
";",
"assertEquals",
"(",
"Color",
".",
"BLUE",
",",
"obj",
".",
"v_color",
")",
";",
"assertEquals",
"(",
"7.0",
",",
"obj",
".",
"v_double",
",",
"0.0001",
")",
";",
"assertEquals",
"(",
"8.0",
",",
"obj",
".",
"v_float",
",",
"0.0001",
")",
";",
"assertEquals",
"(",
"9",
",",
"obj",
".",
"v_int",
")",
";",
"assertEquals",
"(",
"10",
",",
"obj",
".",
"v_long",
")",
";",
"assertEquals",
"(",
"\"",
"abc",
"\"",
",",
"obj",
".",
"v_string",
")",
";",
"}",
"private",
"Map",
"<",
"String",
",",
"String",
">",
"makeParameterMap",
"(",
"String",
"...",
"args",
")",
"{",
"if",
"(",
"args",
".",
"length",
"%",
"2",
"!=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"odd number of arguments",
"\"",
")",
";",
"}",
"Map",
"<",
"String",
",",
"String",
">",
"parameterMap",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"+=",
"2",
")",
"{",
"parameterMap",
".",
"put",
"(",
"args",
"[",
"i",
"]",
",",
"args",
"[",
"i",
"+",
"1",
"]",
")",
";",
"}",
"return",
"parameterMap",
";",
"}",
"@",
"Test",
"public",
"void",
"testOptionalNull",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_string",
"\\\"",
" : null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"v_empty",
"\\\"",
" : null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"AllOptionalTypes",
"obj",
"=",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"AllOptionalTypes",
".",
"class",
")",
";",
"assertNull",
"(",
"obj",
".",
"v_string",
")",
";",
"assertNull",
"(",
"obj",
".",
"v_empty",
")",
";",
"}",
"private",
"static",
"class",
"RequiredObject",
"{",
"@",
"B2Json",
".",
"required",
"Empty",
"a",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a",
"\"",
")",
"public",
"RequiredObject",
"(",
"Empty",
"a",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testSerializeNullTopLevel",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"top level object must not be null",
"\"",
")",
";",
"b2Json",
".",
"toJson",
"(",
"null",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testSerializeNullRequired",
"(",
")",
"throws",
"B2JsonException",
"{",
"RequiredObject",
"obj",
"=",
"new",
"RequiredObject",
"(",
"null",
")",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"required field a cannot be null",
"\"",
")",
";",
"b2Json",
".",
"toJson",
"(",
"obj",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDeserializeNullRequired",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"a",
"\\\"",
" : null }",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"required field a cannot be null",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"RequiredObject",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"ListHolder",
"{",
"@",
"B2Json",
".",
"optional",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"intListList",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"intListList",
"\"",
")",
"ListHolder",
"(",
"List",
"<",
"List",
"<",
"Integer",
">",
">",
"intListList",
")",
"{",
"this",
".",
"intListList",
"=",
"intListList",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testList",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json1",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"intListList",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" [ 1, null, 3 ]",
"\\n",
"\"",
"+",
"\"",
" ]",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json1",
",",
"ListHolder",
".",
"class",
")",
";",
"String",
"json2",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"intListList",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json2",
",",
"ListHolder",
".",
"class",
")",
";",
"}",
"private",
"<",
"T",
">",
"void",
"checkDeserializeSerialize",
"(",
"String",
"json",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"T",
"obj",
"=",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"clazz",
")",
";",
"assertEquals",
"(",
"json",
",",
"b2Json",
".",
"toJson",
"(",
"obj",
")",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"getUtf8Bytes",
"(",
"json",
")",
";",
"T",
"obj2",
"=",
"b2Json",
".",
"fromJson",
"(",
"bytes",
",",
"clazz",
")",
";",
"assertArrayEquals",
"(",
"bytes",
",",
"b2Json",
".",
"toJsonUtf8Bytes",
"(",
"obj2",
")",
")",
";",
"T",
"obj3",
"=",
"b2Json",
".",
"fromJson",
"(",
"bytes",
",",
"clazz",
")",
";",
"byte",
"[",
"]",
"bytesWithNewline",
"=",
"getUtf8Bytes",
"(",
"json",
"+",
"\"",
"\\n",
"\"",
")",
";",
"assertArrayEquals",
"(",
"bytesWithNewline",
",",
"b2Json",
".",
"toJsonUtf8BytesWithNewline",
"(",
"obj3",
")",
")",
";",
"}",
"private",
"<",
"T",
">",
"void",
"checkDeserializeSerialize",
"(",
"String",
"json",
",",
"Class",
"<",
"T",
">",
"clazz",
",",
"String",
"expectedJson",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"T",
"obj",
"=",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"clazz",
")",
";",
"assertEquals",
"(",
"expectedJson",
",",
"b2Json",
".",
"toJson",
"(",
"obj",
")",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"getUtf8Bytes",
"(",
"json",
")",
";",
"T",
"obj2",
"=",
"b2Json",
".",
"fromJson",
"(",
"bytes",
",",
"clazz",
")",
";",
"assertArrayEquals",
"(",
"getUtf8Bytes",
"(",
"expectedJson",
")",
",",
"b2Json",
".",
"toJsonUtf8Bytes",
"(",
"obj2",
")",
")",
";",
"}",
"private",
"static",
"class",
"MapHolder",
"{",
"@",
"B2Json",
".",
"optional",
"public",
"Map",
"<",
"LocalDate",
",",
"Integer",
">",
"map",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"map",
"\"",
")",
"public",
"MapHolder",
"(",
"Map",
"<",
"LocalDate",
",",
"Integer",
">",
"map",
")",
"{",
"this",
".",
"map",
"=",
"map",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testMap",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json1",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"map",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"20150101",
"\\\"",
": 37,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"20150207",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json1",
",",
"MapHolder",
".",
"class",
")",
";",
"String",
"json2",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"map",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json2",
",",
"MapHolder",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"MapWithNullKeyHolder",
"{",
"@",
"B2Json",
".",
"optional",
"Map",
"<",
"String",
",",
"String",
">",
"map",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"map",
"\"",
")",
"public",
"MapWithNullKeyHolder",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"map",
")",
"{",
"this",
".",
"map",
"=",
"map",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testSerializationOfMapWithNullKeyGeneratesException",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"map",
".",
"put",
"(",
"null",
",",
"\"",
"Text",
"\"",
")",
";",
"MapWithNullKeyHolder",
"mapWithNullKeyHolder",
"=",
"new",
"MapWithNullKeyHolder",
"(",
"map",
")",
";",
"try",
"{",
"b2Json",
".",
"toJson",
"(",
"mapWithNullKeyHolder",
")",
";",
"assertTrue",
"(",
"\"",
"Map with null key should not be allowed to be serialized",
"\"",
",",
"false",
")",
";",
"}",
"catch",
"(",
"B2JsonException",
"ex",
")",
"{",
"assertEquals",
"(",
"\"",
"Map key is null",
"\"",
",",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"private",
"static",
"class",
"TreeMapHolder",
"{",
"@",
"B2Json",
".",
"optional",
"TreeMap",
"<",
"LocalDate",
",",
"Integer",
">",
"treeMap",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"treeMap",
"\"",
")",
"public",
"TreeMapHolder",
"(",
"TreeMap",
"<",
"LocalDate",
",",
"Integer",
">",
"treeMap",
")",
"{",
"this",
".",
"treeMap",
"=",
"treeMap",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testTreeMap",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json1",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"treeMap",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"20150101",
"\\\"",
": 37,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"20150207",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json1",
",",
"TreeMapHolder",
".",
"class",
")",
";",
"String",
"json2",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"treeMap",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json2",
",",
"TreeMapHolder",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"SortedMapHolder",
"{",
"@",
"B2Json",
".",
"optional",
"SortedMap",
"<",
"LocalDate",
",",
"Integer",
">",
"sortedMap",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"sortedMap",
"\"",
")",
"public",
"SortedMapHolder",
"(",
"SortedMap",
"<",
"LocalDate",
",",
"Integer",
">",
"sortedMap",
")",
"{",
"this",
".",
"sortedMap",
"=",
"sortedMap",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testSortedMap",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json1",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"sortedMap",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"20150101",
"\\\"",
": 37,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"20150207",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json1",
",",
"SortedMapHolder",
".",
"class",
")",
";",
"String",
"json2",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"sortedMap",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json2",
",",
"SortedMapHolder",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"ConcurrentMapHolder",
"{",
"@",
"B2Json",
".",
"optional",
"public",
"ConcurrentMap",
"<",
"LocalDate",
",",
"Integer",
">",
"map",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"map",
"\"",
")",
"public",
"ConcurrentMapHolder",
"(",
"ConcurrentMap",
"<",
"LocalDate",
",",
"Integer",
">",
"map",
")",
"{",
"this",
".",
"map",
"=",
"map",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testConcurrentMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"ConcurrentMap",
"<",
"LocalDate",
",",
"Integer",
">",
"map",
"=",
"new",
"ConcurrentHashMap",
"<",
">",
"(",
")",
";",
"map",
".",
"put",
"(",
"LocalDate",
".",
"of",
"(",
"2015",
",",
"5",
",",
"2",
")",
",",
"7",
")",
";",
"ConcurrentMapHolder",
"holder",
"=",
"new",
"ConcurrentMapHolder",
"(",
"map",
")",
";",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"map",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"20150502",
"\\\"",
": 7",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"json",
",",
"b2Json",
".",
"toJson",
"(",
"holder",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDirectMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"Map",
"<",
"String",
",",
"Integer",
">",
"map",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"map",
".",
"put",
"(",
"\"",
"a",
"\"",
",",
"5",
")",
";",
"map",
".",
"put",
"(",
"\"",
"b",
"\"",
",",
"6",
")",
";",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 5,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": 6",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"json",
",",
"b2Json",
".",
"mapToJson",
"(",
"map",
",",
"String",
".",
"class",
",",
"Integer",
".",
"class",
")",
")",
";",
"assertEquals",
"(",
"map",
",",
"b2Json",
".",
"mapFromJson",
"(",
"json",
",",
"String",
".",
"class",
",",
"Integer",
".",
"class",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDirectList",
"(",
")",
"throws",
"B2JsonException",
"{",
"List",
"<",
"String",
">",
"list",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"list",
".",
"add",
"(",
"\"",
"alfa",
"\"",
")",
";",
"list",
".",
"add",
"(",
"\"",
"bravo",
"\"",
")",
";",
"String",
"json",
"=",
"\"",
"[",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"alfa",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bravo",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"]",
"\"",
";",
"assertEquals",
"(",
"json",
",",
"b2Json",
".",
"listToJson",
"(",
"list",
",",
"String",
".",
"class",
")",
")",
";",
"assertEquals",
"(",
"list",
",",
"b2Json",
".",
"listFromJson",
"(",
"json",
",",
"String",
".",
"class",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testUtf8",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"appendCodePoint",
"(",
"0xA",
")",
";",
"builder",
".",
"appendCodePoint",
"(",
"0x41",
")",
";",
"builder",
".",
"appendCodePoint",
"(",
"0xDF",
")",
";",
"builder",
".",
"appendCodePoint",
"(",
"0x6771",
")",
";",
"builder",
".",
"appendCodePoint",
"(",
"0x10400",
")",
";",
"String",
"str",
"=",
"builder",
".",
"toString",
"(",
")",
";",
"String",
"json",
"=",
"\"",
"\\\"",
"\\\\",
"u000a",
"\"",
"+",
"str",
".",
"substring",
"(",
"1",
")",
"+",
"\"",
"\\\"",
"\"",
";",
"byte",
"[",
"]",
"utf8Json",
"=",
"new",
"byte",
"[",
"]",
"{",
"(",
"byte",
")",
"0x22",
",",
"(",
"byte",
")",
"0x5C",
",",
"(",
"byte",
")",
"0x75",
",",
"(",
"byte",
")",
"0x30",
",",
"(",
"byte",
")",
"0x30",
",",
"(",
"byte",
")",
"0x30",
",",
"(",
"byte",
")",
"0x61",
",",
"(",
"byte",
")",
"0x41",
",",
"(",
"byte",
")",
"0xC3",
",",
"(",
"byte",
")",
"0x9F",
",",
"(",
"byte",
")",
"0xE6",
",",
"(",
"byte",
")",
"0x9D",
",",
"(",
"byte",
")",
"0xB1",
",",
"(",
"byte",
")",
"0xF0",
",",
"(",
"byte",
")",
"0x90",
",",
"(",
"byte",
")",
"0x90",
",",
"(",
"byte",
")",
"0x80",
",",
"(",
"byte",
")",
"0x22",
"}",
";",
"assertEquals",
"(",
"str",
",",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"String",
".",
"class",
")",
")",
";",
"assertEquals",
"(",
"str",
",",
"b2Json",
".",
"fromJson",
"(",
"new",
"ByteArrayInputStream",
"(",
"utf8Json",
")",
",",
"String",
".",
"class",
")",
")",
";",
"assertEquals",
"(",
"json",
",",
"b2Json",
".",
"toJson",
"(",
"str",
")",
")",
";",
"try",
"(",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
")",
"{",
"b2Json",
".",
"toJson",
"(",
"str",
",",
"out",
")",
";",
"assertArrayEquals",
"(",
"utf8Json",
",",
"out",
".",
"toByteArray",
"(",
")",
")",
";",
"}",
"}",
"private",
"static",
"class",
"Private",
"{",
"@",
"B2Json",
".",
"required",
"private",
"int",
"age",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"age",
"\"",
")",
"private",
"Private",
"(",
"int",
"age",
")",
"{",
"this",
".",
"age",
"=",
"age",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testPrivate",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"Private",
"orig",
"=",
"new",
"Private",
"(",
"6",
")",
";",
"assertEquals",
"(",
"6",
",",
"orig",
".",
"age",
")",
";",
"final",
"String",
"json",
"=",
"b2Json",
".",
"toJson",
"(",
"orig",
")",
";",
"final",
"String",
"expectedJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"age",
"\\\"",
": 6",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expectedJson",
",",
"json",
")",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"Private",
".",
"class",
")",
";",
"}",
"private",
"enum",
"Color",
"{",
"BLUE",
",",
"GREEN",
",",
"RED",
"}",
"private",
"static",
"class",
"ColorHolder",
"{",
"@",
"B2Json",
".",
"required",
"Color",
"color",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"color",
"\"",
")",
"public",
"ColorHolder",
"(",
"Color",
"color",
")",
"{",
"this",
".",
"color",
"=",
"color",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testEnum",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"color",
"\\\"",
": ",
"\\\"",
"RED",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"ColorHolder",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testUnknownEnum_noDefaultForInvalidEnumValue",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"color",
"\\\"",
": ",
"\\\"",
"CHARTREUSE",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"CHARTREUSE is not a valid value. Valid values are: BLUE, GREEN, RED",
"\"",
")",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"ColorHolder",
".",
"class",
")",
";",
"}",
"private",
"enum",
"Spin",
"{",
"@",
"B2Json",
".",
"defaultForInvalidEnumValue",
"(",
")",
"LEFT",
",",
"@",
"B2Json",
".",
"defaultForInvalidEnumValue",
"(",
")",
"RIGHT",
"}",
"private",
"static",
"class",
"SpinHolder",
"{",
"@",
"B2Json",
".",
"optional",
"final",
"Spin",
"spin",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"spin",
"\"",
")",
"private",
"SpinHolder",
"(",
"Spin",
"spin",
")",
"{",
"this",
".",
"spin",
"=",
"spin",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnknownEnum_tooManyDefaultInvalidEnumValue",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"spin",
"\\\"",
": ",
"\\\"",
"CHARTREUSE",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"more than one @B2Json.defaultForInvalidEnumValue annotation in enum class com.backblaze.b2.json.B2JsonTest.Spin",
"\"",
")",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"SpinHolder",
".",
"class",
")",
";",
"}",
"private",
"enum",
"Flavor",
"{",
"UP",
",",
"DOWN",
",",
"@",
"B2Json",
".",
"defaultForInvalidEnumValue",
"STRANGE",
",",
"CHARM",
",",
"TOP",
",",
"BOTTOM",
"}",
"private",
"static",
"class",
"FlavorHolder",
"{",
"@",
"B2Json",
".",
"optional",
"final",
"Flavor",
"flavor",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"flavor",
"\"",
")",
"private",
"FlavorHolder",
"(",
"Flavor",
"flavor",
")",
"{",
"this",
".",
"flavor",
"=",
"flavor",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnknownEnum_usesDefaultInvalidEnumValue",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"flavor",
"\\\"",
": ",
"\\\"",
"CHARTREUSE",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"final",
"FlavorHolder",
"holder",
"=",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"json",
",",
"FlavorHolder",
".",
"class",
")",
";",
"assertEquals",
"(",
"Flavor",
".",
"STRANGE",
",",
"holder",
".",
"flavor",
")",
";",
"}",
"private",
"static",
"class",
"EvenNumber",
"{",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"@",
"B2Json",
".",
"required",
"private",
"final",
"int",
"number",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"number",
"\"",
")",
"public",
"EvenNumber",
"(",
"int",
"number",
")",
"{",
"if",
"(",
"number",
"%",
"2",
"!=",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"not even: ",
"\"",
"+",
"number",
")",
";",
"}",
"this",
".",
"number",
"=",
"number",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testConstructorThrowsIllegalArgument",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"number",
"\\\"",
" : 7 }",
"\"",
";",
"thrown",
".",
"expect",
"(",
"B2JsonBadValueException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"not even: 7",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"EvenNumber",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"PrimitiveArrayContainer",
"{",
"@",
"B2Json",
".",
"required",
"final",
"boolean",
"[",
"]",
"booleans",
";",
"@",
"B2Json",
".",
"required",
"final",
"char",
"[",
"]",
"chars",
";",
"@",
"B2Json",
".",
"required",
"final",
"byte",
"[",
"]",
"bytes",
";",
"@",
"B2Json",
".",
"required",
"final",
"int",
"[",
"]",
"ints",
";",
"@",
"B2Json",
".",
"required",
"final",
"long",
"[",
"]",
"longs",
";",
"@",
"B2Json",
".",
"required",
"final",
"float",
"[",
"]",
"floats",
";",
"@",
"B2Json",
".",
"required",
"final",
"double",
"[",
"]",
"doubles",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"booleans,chars,bytes,ints,longs,floats,doubles",
"\"",
")",
"public",
"PrimitiveArrayContainer",
"(",
"boolean",
"[",
"]",
"booleans",
",",
"char",
"[",
"]",
"chars",
",",
"byte",
"[",
"]",
"bytes",
",",
"int",
"[",
"]",
"ints",
",",
"long",
"[",
"]",
"longs",
",",
"float",
"[",
"]",
"floats",
",",
"double",
"[",
"]",
"doubles",
")",
"{",
"this",
".",
"booleans",
"=",
"booleans",
";",
"this",
".",
"chars",
"=",
"chars",
";",
"this",
".",
"bytes",
"=",
"bytes",
";",
"this",
".",
"ints",
"=",
"ints",
";",
"this",
".",
"longs",
"=",
"longs",
";",
"this",
".",
"floats",
"=",
"floats",
";",
"this",
".",
"doubles",
"=",
"doubles",
";",
"}",
"}",
"private",
"static",
"class",
"OptionalPrimitiveArrayContainer",
"{",
"@",
"B2Json",
".",
"optional",
"final",
"boolean",
"[",
"]",
"booleans",
";",
"@",
"B2Json",
".",
"optional",
"final",
"char",
"[",
"]",
"chars",
";",
"@",
"B2Json",
".",
"optional",
"final",
"byte",
"[",
"]",
"bytes",
";",
"@",
"B2Json",
".",
"optional",
"final",
"int",
"[",
"]",
"ints",
";",
"@",
"B2Json",
".",
"optional",
"final",
"long",
"[",
"]",
"longs",
";",
"@",
"B2Json",
".",
"optional",
"final",
"float",
"[",
"]",
"floats",
";",
"@",
"B2Json",
".",
"optional",
"final",
"double",
"[",
"]",
"doubles",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"booleans,chars,bytes,ints,longs,floats,doubles",
"\"",
")",
"public",
"OptionalPrimitiveArrayContainer",
"(",
"boolean",
"[",
"]",
"booleans",
",",
"char",
"[",
"]",
"chars",
",",
"byte",
"[",
"]",
"bytes",
",",
"int",
"[",
"]",
"ints",
",",
"long",
"[",
"]",
"longs",
",",
"float",
"[",
"]",
"floats",
",",
"double",
"[",
"]",
"doubles",
")",
"{",
"this",
".",
"booleans",
"=",
"booleans",
";",
"this",
".",
"chars",
"=",
"chars",
";",
"this",
".",
"bytes",
"=",
"bytes",
";",
"this",
".",
"ints",
"=",
"ints",
";",
"this",
".",
"longs",
"=",
"longs",
";",
"this",
".",
"floats",
"=",
"floats",
";",
"this",
".",
"doubles",
"=",
"doubles",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testEmptyArrays",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"booleans",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bytes",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"chars",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"doubles",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"floats",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"ints",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longs",
"\\\"",
": []",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"PrimitiveArrayContainer",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testArraysWithValues",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"booleans",
"\\\"",
": [ true, false ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bytes",
"\\\"",
": [ 1, 2, 3 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"chars",
"\\\"",
": [ 65, 0, 128, 255 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"doubles",
"\\\"",
": [ 1.1, -2.2 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"floats",
"\\\"",
": [ 1.0, 2.0, 3.0 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"ints",
"\\\"",
": [ -2147483648, 0, 2147483647 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longs",
"\\\"",
": [ 9223372036854775807, -9223372036854775808 ]",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"PrimitiveArrayContainer",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOptionalArraysWithValues",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"booleans",
"\\\"",
": [ true ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bytes",
"\\\"",
": [ 1 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"chars",
"\\\"",
": [ 65 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"doubles",
"\\\"",
": [ 1.0 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"floats",
"\\\"",
": [ 2.0 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"ints",
"\\\"",
": [ 257 ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longs",
"\\\"",
": [ 12345 ]",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"OptionalPrimitiveArrayContainer",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOptionalArraysWithMissing",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{}",
"\"",
";",
"final",
"String",
"expectedJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"booleans",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bytes",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"chars",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"doubles",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"floats",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"ints",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longs",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"OptionalPrimitiveArrayContainer",
".",
"class",
",",
"expectedJson",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOptionalArraysThatAreNulls",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"booleans",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bytes",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"chars",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"doubles",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"floats",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"ints",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longs",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"OptionalPrimitiveArrayContainer",
".",
"class",
")",
";",
"}",
"private",
"void",
"checkNullInArray",
"(",
"String",
"fieldType",
")",
"throws",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"\"",
"+",
"fieldType",
"+",
"\"",
"s",
"\\\"",
": [ null ]",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"try",
"{",
"checkDeserializeSerialize",
"(",
"json",
",",
"OptionalPrimitiveArrayContainer",
".",
"class",
")",
";",
"fail",
"(",
"\"",
"should've thrown",
"\"",
")",
";",
"}",
"catch",
"(",
"B2JsonException",
"e",
")",
"{",
"assertEquals",
"(",
"\"",
"can't put null in a ",
"\"",
"+",
"fieldType",
"+",
"\"",
"[].",
"\"",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testNullInPrimitiveArray",
"(",
")",
"throws",
"IOException",
"{",
"checkNullInArray",
"(",
"\"",
"boolean",
"\"",
")",
";",
"checkNullInArray",
"(",
"\"",
"byte",
"\"",
")",
";",
"checkNullInArray",
"(",
"\"",
"char",
"\"",
")",
";",
"checkNullInArray",
"(",
"\"",
"double",
"\"",
")",
";",
"checkNullInArray",
"(",
"\"",
"float",
"\"",
")",
";",
"checkNullInArray",
"(",
"\"",
"int",
"\"",
")",
";",
"checkNullInArray",
"(",
"\"",
"boolean",
"\"",
")",
";",
"checkNullInArray",
"(",
"\"",
"long",
"\"",
")",
";",
"}",
"private",
"static",
"class",
"ObjectArrayContainer",
"{",
"@",
"B2Json",
".",
"required",
"final",
"OptionalPrimitiveArrayContainer",
"[",
"]",
"containers",
";",
"@",
"B2Json",
".",
"required",
"final",
"Color",
"[",
"]",
"colors",
";",
"@",
"B2Json",
".",
"required",
"final",
"long",
"[",
"]",
"[",
"]",
"arrays",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"containers, colors, arrays",
"\"",
")",
"public",
"ObjectArrayContainer",
"(",
"OptionalPrimitiveArrayContainer",
"[",
"]",
"containers",
",",
"Color",
"[",
"]",
"colors",
",",
"long",
"[",
"]",
"[",
"]",
"arrays",
")",
"{",
"this",
".",
"containers",
"=",
"containers",
";",
"this",
".",
"colors",
"=",
"colors",
";",
"this",
".",
"arrays",
"=",
"arrays",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testEmptyObjectArrays",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"arrays",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"colors",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"containers",
"\\\"",
": []",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"ObjectArrayContainer",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testObjectArrays",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"arrays",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" [ 1, 2, 3 ],",
"\\n",
"\"",
"+",
"\"",
" null,",
"\\n",
"\"",
"+",
"\"",
" [ 4, 5, 6 ]",
"\\n",
"\"",
"+",
"\"",
" ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"colors",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"RED",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"BLUE",
"\\\"",
"\\n",
"\"",
"+",
"\"",
" ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"containers",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"booleans",
"\\\"",
": [ true ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bytes",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"chars",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"doubles",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"floats",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"ints",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longs",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
" },",
"\\n",
"\"",
"+",
"\"",
" null,",
"\\n",
"\"",
"+",
"\"",
" {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"booleans",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"bytes",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"chars",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"doubles",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"floats",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"ints",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longs",
"\\\"",
": [ 7, 8, 9 ]",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
" ]",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"ObjectArrayContainer",
".",
"class",
")",
";",
"}",
"private",
"byte",
"[",
"]",
"getUtf8Bytes",
"(",
"String",
"str",
")",
"{",
"try",
"{",
"return",
"str",
".",
"getBytes",
"(",
"\"",
"UTF-8",
"\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"No UTF-8 charset",
"\"",
")",
";",
"}",
"}",
"private",
"static",
"class",
"GoodCustomHandler",
"{",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"private",
"static",
"B2JsonTypeHandler",
"<",
"GoodCustomHandler",
">",
"getJsonTypeHandler",
"(",
")",
"{",
"return",
"new",
"JsonHandler",
"(",
")",
";",
"}",
"private",
"static",
"class",
"JsonHandler",
"implements",
"B2JsonTypeHandler",
"<",
"GoodCustomHandler",
">",
"{",
"public",
"Type",
"getHandledType",
"(",
")",
"{",
"return",
"GoodCustomHandler",
".",
"class",
";",
"}",
"public",
"void",
"serialize",
"(",
"GoodCustomHandler",
"obj",
",",
"B2JsonOptions",
"options",
",",
"B2JsonWriter",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"writeString",
"(",
"\"",
"GoodCustomHandler",
"\"",
")",
";",
"}",
"public",
"GoodCustomHandler",
"deserialize",
"(",
"B2JsonReader",
"in",
",",
"B2JsonOptions",
"options",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"return",
"deserialize",
"(",
"in",
".",
"readString",
"(",
")",
")",
";",
"}",
"public",
"GoodCustomHandler",
"deserializeUrlParam",
"(",
"String",
"urlValue",
")",
"throws",
"B2JsonException",
"{",
"return",
"deserialize",
"(",
"urlValue",
")",
";",
"}",
"private",
"GoodCustomHandler",
"deserialize",
"(",
"String",
"value",
")",
"throws",
"B2JsonBadValueException",
"{",
"if",
"(",
"!",
"value",
".",
"equals",
"(",
"\"",
"GoodCustomHandler",
"\"",
")",
")",
"{",
"throw",
"new",
"B2JsonBadValueException",
"(",
"\"",
"string isn't a GoodCustomHandler (",
"\"",
"+",
"value",
"+",
"\"",
")",
"\"",
")",
";",
"}",
"return",
"new",
"GoodCustomHandler",
"(",
")",
";",
"}",
"public",
"GoodCustomHandler",
"defaultValueForOptional",
"(",
")",
"{",
"return",
"null",
";",
"}",
"public",
"boolean",
"isStringInJson",
"(",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"@",
"Test",
"public",
"void",
"customHandlerGood",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"\\\"",
"GoodCustomHandler",
"\\\"",
"\"",
",",
"GoodCustomHandler",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"WrongTypeHandler",
"{",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"private",
"static",
"Double",
"getJsonTypeHandler",
"(",
")",
"{",
"return",
"6.66",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"customHandlerWrongType",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"{}",
"\"",
",",
"WrongTypeHandler",
".",
"class",
")",
";",
"fail",
"(",
"\"",
"should've thrown!",
"\"",
")",
";",
"}",
"catch",
"(",
"B2JsonException",
"e",
")",
"{",
"assertEquals",
"(",
"\"",
"WrongTypeHandler.getJsonTypeHandler() returned an unexpected type of object (java.lang.Double)",
"\"",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"private",
"static",
"class",
"NullHandler",
"{",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"private",
"static",
"B2JsonTypeHandler",
"<",
"NullHandler",
">",
"getJsonTypeHandler",
"(",
")",
"{",
"return",
"null",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"customHandlerNull",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"checkDeserializeSerialize",
"(",
"\"",
"{}",
"\"",
",",
"NullHandler",
".",
"class",
")",
";",
"fail",
"(",
"\"",
"should've thrown!",
"\"",
")",
";",
"}",
"catch",
"(",
"B2JsonException",
"e",
")",
"{",
"assertEquals",
"(",
"\"",
"NullHandler.getJsonTypeHandler() returned an unexpected type of object (null)",
"\"",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"private",
"static",
"class",
"OptionalWithDefaultHolder",
"{",
"@",
"B2Json",
".",
"optional",
"public",
"final",
"int",
"a",
";",
"@",
"B2Json",
".",
"optionalWithDefault",
"(",
"defaultValue",
"=",
"\"",
"5",
"\"",
")",
"public",
"final",
"int",
"b",
";",
"@",
"B2Json",
".",
"optionalWithDefault",
"(",
"defaultValue",
"=",
"\"",
"\\\"",
"hello",
"\\\"",
"\"",
")",
"public",
"final",
"String",
"c",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a, b, c",
"\"",
")",
"private",
"OptionalWithDefaultHolder",
"(",
"int",
"a",
",",
"int",
"b",
",",
"String",
"c",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"this",
".",
"b",
"=",
"b",
";",
"this",
".",
"c",
"=",
"c",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"o",
"==",
"null",
"||",
"getClass",
"(",
")",
"!=",
"o",
".",
"getClass",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"OptionalWithDefaultHolder",
"that",
"=",
"(",
"OptionalWithDefaultHolder",
")",
"o",
";",
"return",
"Objects",
".",
"equals",
"(",
"a",
",",
"that",
".",
"a",
")",
"&&",
"Objects",
".",
"equals",
"(",
"b",
",",
"that",
".",
"b",
")",
"&&",
"Objects",
".",
"equals",
"(",
"c",
",",
"that",
".",
"c",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"\"",
"OptionalWithDefaultHolder{",
"\"",
"+",
"\"",
"a=",
"\"",
"+",
"a",
"+",
"\"",
", b=",
"\"",
"+",
"b",
"+",
"\"",
", c='",
"\"",
"+",
"c",
"+",
"'\\''",
"+",
"'}'",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testOptionalWithDefault",
"(",
")",
"throws",
"B2JsonException",
"{",
"{",
"OptionalWithDefaultHolder",
"expected",
"=",
"new",
"OptionalWithDefaultHolder",
"(",
"0",
",",
"5",
",",
"\"",
"hello",
"\"",
")",
";",
"OptionalWithDefaultHolder",
"actual",
"=",
"b2Json",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"OptionalWithDefaultHolder",
".",
"class",
")",
";",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"{",
"OptionalWithDefaultHolder",
"expected",
"=",
"new",
"OptionalWithDefaultHolder",
"(",
"2",
",",
"3",
",",
"\"",
"4",
"\"",
")",
";",
"OptionalWithDefaultHolder",
"actual",
"=",
"b2Json",
".",
"fromJson",
"(",
"\"",
"{",
"\\\"",
"a",
"\\\"",
": 2, ",
"\\\"",
"b",
"\\\"",
": 3, ",
"\\\"",
"c",
"\\\"",
": ",
"\\\"",
"4",
"\\\"",
"}",
"\"",
",",
"OptionalWithDefaultHolder",
".",
"class",
")",
";",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"}",
"private",
"static",
"class",
"OptionalWithDefaultInvalidValue",
"{",
"@",
"B2Json",
".",
"optionalWithDefault",
"(",
"defaultValue",
"=",
"\"",
"xxx",
"\"",
")",
"private",
"final",
"int",
"count",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"count",
"\"",
")",
"private",
"OptionalWithDefaultInvalidValue",
"(",
"int",
"count",
")",
"{",
"this",
".",
"count",
"=",
"count",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testInvalidValueInOptionalWithDefault",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"error in default value for OptionalWithDefaultInvalidValue.count: Bad number",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"new",
"OptionalWithDefaultInvalidValue",
"(",
"0",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testVersionRangeBackwards",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"last version 1 is before first version 2 in class com.backblaze.b2.json.B2JsonTest$VersionRangeBackwardsClass",
"\"",
")",
";",
"b2Json",
".",
"toJson",
"(",
"new",
"VersionRangeBackwardsClass",
"(",
"5",
")",
")",
";",
"}",
"private",
"static",
"class",
"VersionRangeBackwardsClass",
"{",
"@",
"B2Json",
".",
"required",
"@",
"B2Json",
".",
"versionRange",
"(",
"firstVersion",
"=",
"2",
",",
"lastVersion",
"=",
"1",
")",
"private",
"final",
"int",
"n",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"n",
"\"",
")",
"private",
"VersionRangeBackwardsClass",
"(",
"int",
"n",
")",
"{",
"this",
".",
"n",
"=",
"n",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testConflictingVersions",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"must not specify both 'firstVersion' and 'versionRange' in class com.backblaze.b2.json.B2JsonTest$VersionConflictClass",
"\"",
")",
";",
"b2Json",
".",
"toJson",
"(",
"new",
"VersionConflictClass",
"(",
"5",
")",
")",
";",
"}",
"private",
"static",
"class",
"VersionConflictClass",
"{",
"@",
"B2Json",
".",
"required",
"@",
"B2Json",
".",
"firstVersion",
"(",
"firstVersion",
"=",
"5",
")",
"@",
"B2Json",
".",
"versionRange",
"(",
"firstVersion",
"=",
"2",
",",
"lastVersion",
"=",
"1",
")",
"private",
"final",
"int",
"n",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"n",
"\"",
")",
"private",
"VersionConflictClass",
"(",
"int",
"n",
")",
"{",
"this",
".",
"n",
"=",
"n",
";",
"}",
"}",
"private",
"static",
"final",
"class",
"Node",
"{",
"@",
"B2Json",
".",
"optional",
"public",
"String",
"name",
";",
"@",
"B2Json",
".",
"optional",
"List",
"<",
"Node",
">",
"childNodes",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"name, childNodes",
"\"",
")",
"public",
"Node",
"(",
"String",
"name",
",",
"List",
"<",
"Node",
">",
"childNodes",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"childNodes",
"=",
"childNodes",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testRecursiveTree",
"(",
")",
"throws",
"IOException",
",",
"B2JsonException",
"{",
"String",
"tree1",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"childNodes",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"Degenerative",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"tree1",
",",
"Node",
".",
"class",
")",
";",
"String",
"tree2",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"childNodes",
"\\\"",
": [],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"With Empty Children",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"tree2",
",",
"Node",
".",
"class",
")",
";",
"String",
"tree3",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"childNodes",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"childNodes",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"Level 2 Child 1",
"\\\"",
"\\n",
"\"",
"+",
"\"",
" },",
"\\n",
"\"",
"+",
"\"",
" {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"childNodes",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"childNodes",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"Level 3 Child 1",
"\\\"",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
" ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"Level 2 Child 2",
"\\\"",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
" ],",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"Top",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"tree3",
",",
"Node",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testEnumWithSpecialHandler",
"(",
")",
"throws",
"B2JsonException",
"{",
"String",
"json",
"=",
"\"",
"{",
"\\\"",
"letter",
"\\\"",
": ",
"\\\"",
"b",
"\\\"",
"}",
"\"",
";",
"LetterHolder",
"holder",
"=",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"json",
",",
"LetterHolder",
".",
"class",
")",
";",
"assertEquals",
"(",
"Letter",
".",
"BEE",
",",
"holder",
".",
"letter",
")",
";",
"}",
"private",
"static",
"class",
"LetterHolder",
"{",
"@",
"B2Json",
".",
"required",
"private",
"final",
"Letter",
"letter",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"letter",
"\"",
")",
"private",
"LetterHolder",
"(",
"Letter",
"letter",
")",
"{",
"this",
".",
"letter",
"=",
"letter",
";",
"}",
"}",
"private",
"enum",
"Letter",
"{",
"BEE",
";",
"public",
"static",
"class",
"JsonHandler",
"implements",
"B2JsonTypeHandler",
"<",
"Letter",
">",
"{",
"@",
"Override",
"public",
"Type",
"getHandledType",
"(",
")",
"{",
"return",
"Letter",
".",
"class",
";",
"}",
"@",
"Override",
"public",
"void",
"serialize",
"(",
"Letter",
"obj",
",",
"B2JsonOptions",
"options",
",",
"B2JsonWriter",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"writeString",
"(",
"\"",
"b",
"\"",
")",
";",
"}",
"@",
"Override",
"public",
"Letter",
"deserialize",
"(",
"B2JsonReader",
"in",
",",
"B2JsonOptions",
"options",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"return",
"deserializeUrlParam",
"(",
"in",
".",
"readString",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"Letter",
"deserializeUrlParam",
"(",
"String",
"urlValue",
")",
"{",
"B2Preconditions",
".",
"checkArgument",
"(",
"urlValue",
".",
"equals",
"(",
"\"",
"b",
"\"",
")",
")",
";",
"return",
"BEE",
";",
"}",
"@",
"Override",
"public",
"Letter",
"defaultValueForOptional",
"(",
")",
"{",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"boolean",
"isStringInJson",
"(",
")",
"{",
"return",
"true",
";",
"}",
"}",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"private",
"static",
"B2JsonTypeHandler",
"<",
"Letter",
">",
"getJsonTypeHandler",
"(",
")",
"{",
"return",
"new",
"Letter",
".",
"JsonHandler",
"(",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testSerializeUnion",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"is a union base class, and cannot be serialized",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"new",
"UnionAZ",
"(",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testFieldFromWrongTypeInUnion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"z",
"\\\"",
" : ",
"\\\"",
"hello",
"\\\"",
", ",
"\\\"",
"type",
"\\\"",
" : ",
"\\\"",
"a",
"\\\"",
" }",
"\"",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"unknown field in com.backblaze.b2.json.B2JsonTest$SubclassA: z",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"json",
",",
"UnionAZ",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testMissingTypeInUnion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"a",
"\\\"",
" : 5 }",
"\"",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"missing 'type' in UnionAZ",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"json",
",",
"UnionAZ",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testUnknownTypeInUnion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"type",
"\\\"",
" : ",
"\\\"",
"bad",
"\\\"",
" }",
"\"",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"unknown 'type' in UnionAZ: 'bad'",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"json",
",",
"UnionAZ",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testUnknownFieldInUnion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"badField",
"\\\"",
" : 5, ",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"a",
"\\\"",
" }",
"\"",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"unknown field 'badField' in union type UnionAZ",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"json",
",",
"UnionAZ",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testSerializeUnionSubType",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"origJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"contained",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
": 1,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"a",
"\\\"",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"origJson",
",",
"ContainsUnion",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testSerializeOptionalAndMissingUnion",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"origJson",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"contained",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"origJson",
",",
"ContainsOptionalUnion",
".",
"class",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testSerializeUnregisteredUnionSubType",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"SubclassUnregistered",
"unregistered",
"=",
"new",
"SubclassUnregistered",
"(",
"\"",
"zzz",
"\"",
")",
";",
"final",
"ContainsUnion",
"container",
"=",
"new",
"ContainsUnion",
"(",
"unregistered",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"class com.backblaze.b2.json.B2JsonTest$SubclassUnregistered isn't a registered part of union class com.backblaze.b2.json.B2JsonTest$UnionAZ",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"container",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"@",
"B2Json",
".",
"defaultForUnknownType",
"(",
"value",
"=",
"\"",
"{",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"a",
"\\\"",
", ",
"\\\"",
"n",
"\\\"",
": 5}",
"\"",
")",
"private",
"static",
"class",
"UnionWithDefault",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"a",
"\"",
",",
"UnionWithDefaultClassA",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"UnionWithDefaultClassA",
"extends",
"UnionWithDefault",
"{",
"@",
"B2Json",
".",
"required",
"private",
"final",
"int",
"n",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"n",
"\"",
")",
"private",
"UnionWithDefaultClassA",
"(",
"int",
"n",
")",
"{",
"this",
".",
"n",
"=",
"n",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"o",
"==",
"null",
"||",
"getClass",
"(",
")",
"!=",
"o",
".",
"getClass",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"UnionWithDefaultClassA",
"that",
"=",
"(",
"UnionWithDefaultClassA",
")",
"o",
";",
"return",
"n",
"==",
"that",
".",
"n",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"Objects",
".",
"hash",
"(",
"n",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionWithDefault",
"(",
")",
"throws",
"B2JsonException",
"{",
"assertEquals",
"(",
"new",
"UnionWithDefaultClassA",
"(",
"5",
")",
",",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"unknown",
"\\\"",
"}",
"\"",
",",
"UnionWithDefault",
".",
"class",
")",
")",
";",
"assertEquals",
"(",
"new",
"UnionWithDefaultClassA",
"(",
"5",
")",
",",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"unknown",
"\\\"",
", ",
"\\\"",
"unknownField",
"\\\"",
": 5}",
"\"",
",",
"UnionWithDefault",
".",
"class",
")",
")",
";",
"assertEquals",
"(",
"new",
"UnionWithDefaultClassA",
"(",
"99",
")",
",",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"a",
"\\\"",
", ",
"\\\"",
"n",
"\\\"",
": 99}",
"\"",
",",
"UnionWithDefault",
".",
"class",
")",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"@",
"B2Json",
".",
"defaultForUnknownType",
"(",
"value",
"=",
"\"",
"{",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"a",
"\\\"",
", ",
"\\\"",
"n",
"\\\"",
": 5}",
"\"",
")",
"private",
"static",
"class",
"UnionWithInvalidDefault",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"a",
"\"",
",",
"UnionWithInvalidDefaultClassA",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"UnionWithInvalidDefaultClassA",
"extends",
"UnionWithInvalidDefault",
"{",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"\"",
")",
"UnionWithInvalidDefaultClassA",
"(",
")",
"{",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionWithInvalidDefault",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"error in default value for union UnionWithInvalidDefault: unknown field 'n' in union type UnionWithInvalidDefault",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"new",
"UnionWithInvalidDefaultClassA",
"(",
")",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionAZ",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"a",
"\"",
",",
"SubclassA",
".",
"class",
")",
".",
"put",
"(",
"\"",
"z",
"\"",
",",
"SubclassZ",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassA",
"extends",
"UnionAZ",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"a",
";",
"@",
"B2Json",
".",
"optional",
"public",
"final",
"Set",
"<",
"Integer",
">",
"b",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a, b",
"\"",
")",
"private",
"SubclassA",
"(",
"int",
"a",
",",
"Set",
"<",
"Integer",
">",
"b",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"this",
".",
"b",
"=",
"b",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassZ",
"extends",
"UnionAZ",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"String",
"z",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"z",
"\"",
")",
"private",
"SubclassZ",
"(",
"String",
"z",
")",
"{",
"this",
".",
"z",
"=",
"z",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassUnregistered",
"extends",
"UnionAZ",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"String",
"u",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"u",
"\"",
")",
"private",
"SubclassUnregistered",
"(",
"String",
"u",
")",
"{",
"this",
".",
"u",
"=",
"u",
";",
"}",
"}",
"private",
"static",
"class",
"ContainsUnion",
"{",
"@",
"B2Json",
".",
"required",
"private",
"final",
"UnionAZ",
"contained",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"contained",
"\"",
")",
"private",
"ContainsUnion",
"(",
"UnionAZ",
"contained",
")",
"{",
"this",
".",
"contained",
"=",
"contained",
";",
"}",
"}",
"private",
"static",
"class",
"ContainsOptionalUnion",
"{",
"@",
"B2Json",
".",
"optional",
"private",
"final",
"UnionAZ",
"contained",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"contained",
"\"",
")",
"private",
"ContainsOptionalUnion",
"(",
"UnionAZ",
"contained",
")",
"{",
"this",
".",
"contained",
"=",
"contained",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionWithFieldAnnotation",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"field annotations not allowed in union class",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"BadUnionWithFieldAnnotation",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"foo",
"\"",
")",
"private",
"static",
"class",
"BadUnionWithFieldAnnotation",
"{",
"@",
"B2Json",
".",
"required",
"public",
"int",
"x",
";",
"}",
"@",
"Test",
"public",
"void",
"testUnionWithConstructorAnnotation",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"constructor annotations not allowed in union class",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"BadUnionWithConstructorAnnotation",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"foo",
"\"",
")",
"private",
"static",
"class",
"BadUnionWithConstructorAnnotation",
"{",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"\"",
")",
"public",
"BadUnionWithConstructorAnnotation",
"(",
")",
"{",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionWithoutGetMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"does not have a method getUnionTypeMap",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"UnionWithoutGetMap",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionWithoutGetMap",
"{",
"}",
"@",
"Test",
"public",
"void",
"testUnionTypeMapNotAMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"UnionWithNonMap.getUnionTypeMap() did not return a B2JsonUnionTypeMap",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"UnionWithNonMap",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionWithNonMap",
"{",
"public",
"static",
"String",
"getUnionTypeMap",
"(",
")",
"{",
"return",
"\"",
"foo",
"\"",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionInheritsFromUnion",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"inherits from another class with a B2Json annotation",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"UnionThatInheritsFromUnion",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionThatInheritsFromUnion",
"extends",
"UnionAZ",
"{",
"}",
"@",
"Test",
"public",
"void",
"testUnionMemberIsNotSubclass",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"is not a subclass of",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"UnionWithMemberThatIsNotSubclass",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionWithMemberThatIsNotSubclass",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"doesNotInherit",
"\"",
",",
"SubclassDoesNotInherit",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassDoesNotInherit",
"{",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"\"",
")",
"private",
"SubclassDoesNotInherit",
"(",
"int",
"a",
")",
"{",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionFieldHasDifferentTypes",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"field sameName has two different types",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"UnionXY",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionXY",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"x",
"\"",
",",
"SubclassX",
".",
"class",
")",
".",
"put",
"(",
"\"",
"y",
"\"",
",",
"SubclassY",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassX",
"extends",
"UnionXY",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"sameName",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"sameName",
"\"",
")",
"private",
"SubclassX",
"(",
"int",
"sameName",
")",
"{",
"this",
".",
"sameName",
"=",
"sameName",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassY",
"extends",
"UnionXY",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"String",
"sameName",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"sameName",
"\"",
")",
"private",
"SubclassY",
"(",
"String",
"sameName",
")",
"{",
"this",
".",
"sameName",
"=",
"sameName",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionSubclassNotInTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"is not in the type map",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"new",
"SubclassM",
"(",
")",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionM",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassM",
"extends",
"UnionM",
"{",
"}",
"@",
"Test",
"public",
"void",
"testUnionMapHasDuplicateName",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"duplicate type name in union type map: 'd'",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"new",
"SubclassD1",
"(",
")",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionD",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"d",
"\"",
",",
"SubclassD1",
".",
"class",
")",
".",
"put",
"(",
"\"",
"d",
"\"",
",",
"SubclassD2",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassD1",
"extends",
"UnionD",
"{",
"}",
"private",
"static",
"class",
"SubclassD2",
"extends",
"UnionD",
"{",
"}",
"@",
"Test",
"public",
"void",
"testUnionMapHasDuplicateClass",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"duplicate class in union type map: class com.backblaze.b2.json.B2JsonTest$SubclassF",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"new",
"SubclassF",
"(",
")",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionF",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"f1",
"\"",
",",
"SubclassF",
".",
"class",
")",
".",
"put",
"(",
"\"",
"f2",
"\"",
",",
"SubclassF",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassF",
"extends",
"UnionF",
"{",
"}",
"@",
"Test",
"public",
"void",
"testUnionSubclassHasNullOptionalField",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"g",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"UnionG",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionG",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"g",
"\"",
",",
"SubclassG",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassG",
"extends",
"UnionG",
"{",
"@",
"B2Json",
".",
"optional",
"final",
"String",
"name",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"name",
"\"",
")",
"private",
"SubclassG",
"(",
"String",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testUnionSubclassHasNullRequiredField",
"(",
")",
"throws",
"B2JsonException",
",",
"IOException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"name",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"type",
"\\\"",
": ",
"\\\"",
"h",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"required field name cannot be null",
"\"",
")",
";",
"checkDeserializeSerialize",
"(",
"json",
",",
"UnionH",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"UnionH",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"h",
"\"",
",",
"SubclassH",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"SubclassH",
"extends",
"UnionH",
"{",
"@",
"B2Json",
".",
"required",
"final",
"String",
"name",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"name",
"\"",
")",
"private",
"SubclassH",
"(",
"String",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testRequiredFieldNotInVersion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{}",
"\"",
";",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"1",
")",
".",
"build",
"(",
")",
";",
"final",
"VersionedContainer",
"obj",
"=",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"VersionedContainer",
".",
"class",
",",
"options",
")",
";",
"assertEquals",
"(",
"0",
",",
"obj",
".",
"x",
")",
";",
"assertEquals",
"(",
"1",
",",
"obj",
".",
"version",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testRequiredFieldMissingInVersion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{}",
"\"",
";",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"5",
")",
".",
"build",
"(",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"required field x is missing",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"VersionedContainer",
".",
"class",
",",
"options",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testFieldPresentButNotInVersion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"x",
"\\\"",
": 5 }",
"\"",
";",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"1",
")",
".",
"build",
"(",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"field x is not in version 1",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"VersionedContainer",
".",
"class",
",",
"options",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testFieldPresentAndInVersion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"String",
"json",
"=",
"\"",
"{ ",
"\\\"",
"x",
"\\\"",
": 7 }",
"\"",
";",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"5",
")",
".",
"build",
"(",
")",
";",
"final",
"VersionedContainer",
"obj",
"=",
"b2Json",
".",
"fromJson",
"(",
"json",
",",
"VersionedContainer",
".",
"class",
",",
"options",
")",
";",
"assertEquals",
"(",
"7",
",",
"obj",
".",
"x",
")",
";",
"assertEquals",
"(",
"5",
",",
"obj",
".",
"version",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testSerializeSkipFieldNotInVersion",
"(",
")",
"throws",
"B2JsonException",
"{",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"3",
")",
".",
"build",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"{}",
"\"",
",",
"b2Json",
".",
"toJson",
"(",
"new",
"VersionedContainer",
"(",
"3",
",",
"5",
")",
",",
"options",
")",
")",
";",
"}",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"4",
")",
".",
"build",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
" ",
"\\\"",
"x",
"\\\"",
": 3",
"\\n",
"}",
"\"",
",",
"b2Json",
".",
"toJson",
"(",
"new",
"VersionedContainer",
"(",
"3",
",",
"5",
")",
",",
"options",
")",
")",
";",
"}",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"4",
")",
".",
"build",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
" ",
"\\\"",
"x",
"\\\"",
": 3",
"\\n",
"}",
"\"",
",",
"b2Json",
".",
"toJson",
"(",
"new",
"VersionedContainer",
"(",
"3",
",",
"5",
")",
",",
"options",
")",
")",
";",
"}",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"7",
")",
".",
"build",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"{}",
"\"",
",",
"b2Json",
".",
"toJson",
"(",
"new",
"VersionedContainer",
"(",
"3",
",",
"5",
")",
",",
"options",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testSerializeIncludeFieldInVersion",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"5",
")",
".",
"build",
"(",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"x",
"\\\"",
": 3",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
",",
"b2Json",
".",
"toJson",
"(",
"new",
"VersionedContainer",
"(",
"3",
",",
"5",
")",
",",
"options",
")",
")",
";",
"}",
"private",
"static",
"class",
"VersionedContainer",
"{",
"@",
"B2Json",
".",
"versionRange",
"(",
"firstVersion",
"=",
"4",
",",
"lastVersion",
"=",
"6",
")",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"x",
";",
"@",
"B2Json",
".",
"ignored",
"public",
"final",
"int",
"version",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"x, v",
"\"",
",",
"versionParam",
"=",
"\"",
"v",
"\"",
")",
"public",
"VersionedContainer",
"(",
"int",
"x",
",",
"int",
"v",
")",
"{",
"this",
".",
"x",
"=",
"x",
";",
"this",
".",
"version",
"=",
"v",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testParamListedTwice",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"com.backblaze.b2.json.B2JsonTest$ConstructorParamListedTwice constructor parameter 'a' listed twice",
"\"",
")",
";",
"b2Json",
".",
"fromJson",
"(",
"\"",
"{}",
"\"",
",",
"ConstructorParamListedTwice",
".",
"class",
",",
"options",
")",
";",
"}",
"private",
"static",
"class",
"TestClassOne",
"{",
"@",
"B2Json",
".",
"versionRange",
"(",
"firstVersion",
"=",
"1",
",",
"lastVersion",
"=",
"3",
")",
"@",
"B2Json",
".",
"required",
"final",
"String",
"name",
";",
"@",
"B2Json",
".",
"required",
"final",
"int",
"number",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"name, number",
"\"",
")",
"private",
"TestClassOne",
"(",
"String",
"name",
",",
"int",
"number",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"number",
"=",
"number",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testToJson",
"(",
")",
"{",
"final",
"TestClassOne",
"testClassOne",
"=",
"new",
"TestClassOne",
"(",
"\"",
"testABC",
"\"",
",",
"1",
")",
";",
"final",
"String",
"testClassOneStr",
"=",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"testClassOne",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"testABC",
"\\\"",
",",
"\\n",
" ",
"\\\"",
"number",
"\\\"",
": 1",
"\\n",
"}",
"\"",
",",
"testClassOneStr",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testToJsonWithDefaultOptions",
"(",
")",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
";",
"final",
"TestClassOne",
"testClassOne",
"=",
"new",
"TestClassOne",
"(",
"\"",
"testABC",
"\"",
",",
"1",
")",
";",
"final",
"String",
"testClassOneStr",
"=",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"testClassOne",
",",
"options",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"testABC",
"\\\"",
",",
"\\n",
" ",
"\\\"",
"number",
"\\\"",
": 1",
"\\n",
"}",
"\"",
",",
"testClassOneStr",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testToJsonWithOptions",
"(",
")",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"4",
")",
".",
"build",
"(",
")",
";",
"final",
"TestClassOne",
"testClassOne",
"=",
"new",
"TestClassOne",
"(",
"\"",
"testABC",
"\"",
",",
"1",
")",
";",
"final",
"String",
"testClassOneStr",
"=",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"testClassOne",
",",
"options",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
" ",
"\\\"",
"number",
"\\\"",
": 1",
"\\n",
"}",
"\"",
",",
"testClassOneStr",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testToJsonThrows",
"(",
")",
"{",
"thrown",
".",
"expect",
"(",
"IllegalArgumentException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"failed to convert to json: required field a cannot be null",
"\"",
")",
";",
"RequiredObject",
"obj",
"=",
"new",
"RequiredObject",
"(",
"null",
")",
";",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"obj",
")",
";",
"}",
"private",
"static",
"class",
"SecureContainer",
"{",
"@",
"B2Json",
".",
"required",
"@",
"B2Json",
".",
"sensitive",
"private",
"final",
"String",
"sensitiveString",
";",
"@",
"B2Json",
".",
"required",
"private",
"final",
"String",
"insensitiveString",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"sensitiveString,insensitiveString",
"\"",
")",
"public",
"SecureContainer",
"(",
"String",
"secureString",
",",
"String",
"insecureString",
")",
"{",
"this",
".",
"sensitiveString",
"=",
"secureString",
";",
"this",
".",
"insensitiveString",
"=",
"insecureString",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testSensitiveRedactedWhenOptionSet",
"(",
")",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setRedactSensitive",
"(",
"true",
")",
".",
"build",
"(",
")",
";",
"final",
"SecureContainer",
"secureContainer",
"=",
"new",
"SecureContainer",
"(",
"\"",
"foo",
"\"",
",",
"\"",
"bar",
"\"",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
" ",
"\\\"",
"insensitiveString",
"\\\"",
": ",
"\\\"",
"bar",
"\\\"",
",",
"\\n",
" ",
"\\\"",
"sensitiveString",
"\\\"",
": ",
"\\\"",
"***REDACTED***",
"\\\"",
"\\n",
"}",
"\"",
",",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"secureContainer",
",",
"options",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testSensitiveWrittenWhenOptionNotSet",
"(",
")",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setRedactSensitive",
"(",
"false",
")",
".",
"build",
"(",
")",
";",
"final",
"SecureContainer",
"secureContainer",
"=",
"new",
"SecureContainer",
"(",
"\"",
"foo",
"\"",
",",
"\"",
"bar",
"\"",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
" ",
"\\\"",
"insensitiveString",
"\\\"",
": ",
"\\\"",
"bar",
"\\\"",
",",
"\\n",
" ",
"\\\"",
"sensitiveString",
"\\\"",
": ",
"\\\"",
"foo",
"\\\"",
"\\n",
"}",
"\"",
",",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"secureContainer",
",",
"options",
")",
")",
";",
"}",
"private",
"static",
"class",
"OmitNullBadTestClass",
"{",
"@",
"B2Json",
".",
"optional",
"(",
"omitNull",
"=",
"true",
")",
"private",
"final",
"int",
"omitNullInt",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"omitNullInt",
"\"",
")",
"public",
"OmitNullBadTestClass",
"(",
"int",
"omitNullInt",
")",
"{",
"this",
".",
"omitNullInt",
"=",
"omitNullInt",
";",
"}",
"}",
"private",
"static",
"class",
"OmitNullTestClass",
"{",
"@",
"B2Json",
".",
"optional",
"(",
"omitNull",
"=",
"true",
")",
"private",
"final",
"String",
"omitNullString",
";",
"@",
"B2Json",
".",
"optional",
"private",
"final",
"String",
"regularString",
";",
"@",
"B2Json",
".",
"optional",
"(",
"omitNull",
"=",
"true",
")",
"private",
"final",
"Integer",
"omitNullInteger",
";",
"@",
"B2Json",
".",
"optional",
"private",
"final",
"Integer",
"regularInteger",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"omitNullString, regularString, omitNullInteger, regularInteger",
"\"",
")",
"public",
"OmitNullTestClass",
"(",
"String",
"omitNullString",
",",
"String",
"regularString",
",",
"Integer",
"omitNullInteger",
",",
"Integer",
"regularInteger",
")",
"{",
"this",
".",
"omitNullString",
"=",
"omitNullString",
";",
"this",
".",
"regularString",
"=",
"regularString",
";",
"this",
".",
"omitNullInteger",
"=",
"omitNullInteger",
";",
"this",
".",
"regularInteger",
"=",
"regularInteger",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testOmitNullWithNullInputs",
"(",
")",
"{",
"final",
"OmitNullTestClass",
"object",
"=",
"new",
"OmitNullTestClass",
"(",
"null",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"final",
"String",
"actual",
"=",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"object",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"regularInteger",
"\\\"",
": null,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"regularString",
"\\\"",
": null",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
",",
"actual",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOmitNullWithNonNullInputs",
"(",
")",
"{",
"final",
"OmitNullTestClass",
"object",
"=",
"new",
"OmitNullTestClass",
"(",
"\"",
"foo",
"\"",
",",
"\"",
"bar",
"\"",
",",
"1",
",",
"1",
")",
";",
"final",
"String",
"actual",
"=",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"object",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"omitNullInteger",
"\\\"",
": 1,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"omitNullString",
"\\\"",
": ",
"\\\"",
"foo",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"regularInteger",
"\\\"",
": 1,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"regularString",
"\\\"",
": ",
"\\\"",
"bar",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
",",
"actual",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOmitNullCreateFromEmpty",
"(",
")",
"{",
"final",
"OmitNullTestClass",
"actual",
"=",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"\"",
"{}",
"\"",
",",
"OmitNullTestClass",
".",
"class",
")",
";",
"assertNull",
"(",
"actual",
".",
"omitNullString",
")",
";",
"assertNull",
"(",
"actual",
".",
"regularString",
")",
";",
"assertNull",
"(",
"actual",
".",
"omitNullInteger",
")",
";",
"assertNull",
"(",
"actual",
".",
"regularInteger",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOmitNullOnPrimitive",
"(",
")",
"throws",
"B2JsonException",
"{",
"thrown",
".",
"expectMessage",
"(",
"\"",
"Field OmitNullBadTestClass.omitNullInt declared with 'omitNull = true' but is a primitive type",
"\"",
")",
";",
"final",
"OmitNullBadTestClass",
"bad",
"=",
"new",
"OmitNullBadTestClass",
"(",
"123",
")",
";",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"bad",
")",
";",
"}",
"/**\n * Because of serialization, the object returned from B2Json will never be the same object as an\n * instantiated one.\n *\n * So we just look at and test the members.\n */",
"@",
"Test",
"public",
"void",
"testFromJson",
"(",
")",
"{",
"final",
"String",
"testClassOneStr",
"=",
"\"",
"{",
"\\n",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"testABC",
"\\\"",
",",
"\\n",
" ",
"\\\"",
"number",
"\\\"",
": 1",
"\\n",
"}",
"\"",
";",
"final",
"TestClassOne",
"testClassOne",
"=",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"testClassOneStr",
",",
"TestClassOne",
".",
"class",
")",
";",
"assertEquals",
"(",
"\"",
"testABC",
"\"",
",",
"testClassOne",
".",
"name",
")",
";",
"assertEquals",
"(",
"1",
",",
"testClassOne",
".",
"number",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testFromJsonWithDefaultOptions",
"(",
")",
"{",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
";",
"final",
"String",
"testClassOneStr",
"=",
"\"",
"{",
"\\n",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"testABC",
"\\\"",
",",
"\\n",
" ",
"\\\"",
"number",
"\\\"",
": 1",
"\\n",
"}",
"\"",
";",
"final",
"TestClassOne",
"testClassOne",
"=",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"testClassOneStr",
",",
"TestClassOne",
".",
"class",
",",
"options",
")",
";",
"assertEquals",
"(",
"\"",
"testABC",
"\"",
",",
"testClassOne",
".",
"name",
")",
";",
"assertEquals",
"(",
"1",
",",
"testClassOne",
".",
"number",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testFromJsonWithOptions",
"(",
")",
"{",
"thrown",
".",
"expect",
"(",
"IllegalArgumentException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"failed to convert from json: field name is not in version 6",
"\"",
")",
";",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setVersion",
"(",
"6",
")",
".",
"build",
"(",
")",
";",
"final",
"String",
"testClassOneStr",
"=",
"\"",
"{",
"\\n",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"testABC",
"\\\"",
",",
"\\n",
" ",
"\\\"",
"number",
"\\\"",
": 1",
"\\n",
"}",
"\"",
";",
"final",
"TestClassOne",
"testClassOne",
"=",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"testClassOneStr",
",",
"TestClassOne",
".",
"class",
",",
"options",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testFromJsonThrows",
"(",
")",
"{",
"thrown",
".",
"expect",
"(",
"IllegalArgumentException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"failed to convert from json: required field number is missing",
"\"",
")",
";",
"final",
"String",
"testClassOneStr",
"=",
"\"",
"{",
"\\n",
" ",
"\\\"",
"name",
"\\\"",
": ",
"\\\"",
"testABC",
"\\\"",
"\\n",
"}",
"\"",
";",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"testClassOneStr",
",",
"TestClassOne",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"ConstructorParamListedTwice",
"{",
"@",
"B2Json",
".",
"required",
"public",
"final",
"int",
"a",
";",
"@",
"B2Json",
".",
"optional",
"public",
"final",
"int",
"b",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"a, a",
"\"",
")",
"public",
"ConstructorParamListedTwice",
"(",
"int",
"a",
",",
"int",
"b",
")",
"{",
"this",
".",
"a",
"=",
"a",
";",
"this",
".",
"b",
"=",
"b",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testRecursiveUnion",
"(",
")",
"{",
"final",
"String",
"json",
"=",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"new",
"RecursiveUnionNode",
"(",
"new",
"RecursiveUnionNode",
"(",
"null",
")",
")",
")",
";",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"json",
",",
"RecursiveUnion",
".",
"class",
")",
";",
"}",
"@",
"B2Json",
".",
"union",
"(",
"typeField",
"=",
"\"",
"type",
"\"",
")",
"private",
"static",
"class",
"RecursiveUnion",
"{",
"public",
"static",
"B2JsonUnionTypeMap",
"getUnionTypeMap",
"(",
")",
"throws",
"B2JsonException",
"{",
"return",
"B2JsonUnionTypeMap",
".",
"builder",
"(",
")",
".",
"put",
"(",
"\"",
"node",
"\"",
",",
"RecursiveUnionNode",
".",
"class",
")",
".",
"build",
"(",
")",
";",
"}",
"}",
"private",
"static",
"class",
"RecursiveUnionNode",
"extends",
"RecursiveUnion",
"{",
"@",
"B2Json",
".",
"optional",
"private",
"final",
"RecursiveUnion",
"recursiveUnion",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"recursiveUnion",
"\"",
")",
"private",
"RecursiveUnionNode",
"(",
"RecursiveUnion",
"recursiveUnion",
")",
"{",
"this",
".",
"recursiveUnion",
"=",
"recursiveUnion",
";",
"}",
"}",
"/**\n * A regression test for a case where a class has a field with a default value,\n * and the class of the default value has a class initializer.\n */",
"@",
"Test",
"public",
"void",
"testClassInitializationInDefaultValue",
"(",
")",
"{",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"\"",
"{}",
"\"",
",",
"TestClassInit_ClassWithDefaultValue",
".",
"class",
")",
";",
"}",
"private",
"static",
"class",
"TestClassInit_ClassWithDefaultValue",
"{",
"@",
"B2Json",
".",
"optionalWithDefault",
"(",
"defaultValue",
"=",
"\"",
"{}",
"\"",
")",
"private",
"final",
"TestClassInit_ClassThatDoesInitializition",
"objThatDoesInit",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"objThatDoesInit",
"\"",
")",
"private",
"TestClassInit_ClassWithDefaultValue",
"(",
"TestClassInit_ClassThatDoesInitializition",
"objThatDoesInit",
")",
"{",
"this",
".",
"objThatDoesInit",
"=",
"objThatDoesInit",
";",
"}",
"}",
"private",
"static",
"class",
"TestClassInit_ClassThatDoesInitializition",
"{",
"private",
"static",
"TestClassInit_ClassThatDoesInitializition",
"defaultValue",
"=",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"\"",
"{}",
"\"",
",",
"TestClassInit_ClassThatDoesInitializition",
".",
"class",
")",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"\"",
")",
"TestClassInit_ClassThatDoesInitializition",
"(",
")",
"{",
"}",
"}",
"private",
"static",
"class",
"CharSquenceTestClass",
"{",
"@",
"B2Json",
".",
"required",
"CharSequence",
"sequence",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"sequence",
"\"",
")",
"public",
"CharSquenceTestClass",
"(",
"CharSequence",
"sequence",
")",
"{",
"this",
".",
"sequence",
"=",
"sequence",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"testCharSequenceSerialization",
"(",
")",
"{",
"final",
"CharSequence",
"sequence",
"=",
"\"",
"foobarbaz",
"\"",
".",
"subSequence",
"(",
"3",
",",
"6",
")",
";",
"final",
"CharSquenceTestClass",
"obj",
"=",
"new",
"CharSquenceTestClass",
"(",
"sequence",
")",
";",
"final",
"String",
"actual",
"=",
"B2Json",
".",
"toJsonOrThrowRuntime",
"(",
"obj",
")",
";",
"final",
"String",
"expected",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"sequence",
"\\\"",
": ",
"\\\"",
"bar",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testCharSequenceDeserialization",
"(",
")",
"{",
"final",
"String",
"input",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"sequence",
"\\\"",
": ",
"\\\"",
"bar",
"\\\"",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"final",
"CharSquenceTestClass",
"obj",
"=",
"B2Json",
".",
"fromJsonOrThrowRuntime",
"(",
"input",
",",
"CharSquenceTestClass",
".",
"class",
")",
";",
"assertEquals",
"(",
"\"",
"bar",
"\"",
",",
"obj",
".",
"sequence",
")",
";",
"assertEquals",
"(",
"String",
".",
"class",
",",
"obj",
".",
"sequence",
".",
"getClass",
"(",
")",
")",
";",
"}",
"private",
"static",
"class",
"SerializationTestClass",
"{",
"@",
"B2Json",
".",
"required",
"final",
"String",
"stringVal",
";",
"@",
"B2Json",
".",
"required",
"final",
"int",
"intVal",
";",
"@",
"B2Json",
".",
"required",
"final",
"boolean",
"booleanVal",
";",
"@",
"B2Json",
".",
"required",
"final",
"Map",
"<",
"String",
",",
"Integer",
">",
"mapVal",
";",
"@",
"B2Json",
".",
"required",
"final",
"List",
"<",
"String",
">",
"arrayVal",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"stringVal, intVal, booleanVal, mapVal, arrayVal",
"\"",
")",
"public",
"SerializationTestClass",
"(",
"String",
"stringVal",
",",
"int",
"intVal",
",",
"boolean",
"booleanVal",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"mapVal",
",",
"List",
"<",
"String",
">",
"arrayVal",
")",
"{",
"this",
".",
"stringVal",
"=",
"stringVal",
";",
"this",
".",
"intVal",
"=",
"intVal",
";",
"this",
".",
"booleanVal",
"=",
"booleanVal",
";",
"this",
".",
"mapVal",
"=",
"mapVal",
";",
"this",
".",
"arrayVal",
"=",
"arrayVal",
";",
"}",
"@",
"Override",
"public",
"boolean",
"equals",
"(",
"Object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"return",
"true",
";",
"if",
"(",
"o",
"==",
"null",
"||",
"getClass",
"(",
")",
"!=",
"o",
".",
"getClass",
"(",
")",
")",
"return",
"false",
";",
"SerializationTestClass",
"that",
"=",
"(",
"SerializationTestClass",
")",
"o",
";",
"return",
"intVal",
"==",
"that",
".",
"intVal",
"&&",
"booleanVal",
"==",
"that",
".",
"booleanVal",
"&&",
"Objects",
".",
"equals",
"(",
"stringVal",
",",
"that",
".",
"stringVal",
")",
"&&",
"Objects",
".",
"equals",
"(",
"mapVal",
",",
"that",
".",
"mapVal",
")",
"&&",
"Objects",
".",
"equals",
"(",
"arrayVal",
",",
"that",
".",
"arrayVal",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"hashCode",
"(",
")",
"{",
"return",
"Objects",
".",
"hash",
"(",
"stringVal",
",",
"intVal",
",",
"booleanVal",
",",
"mapVal",
",",
"arrayVal",
")",
";",
"}",
"}",
"/**\n * Compact serialization is not an original feature of B2Json and thus\n * is being explicitly tested here. All the above tests were created\n * before the compact option became available and thus all implicitly\n * test the pretty serialization output (which is still the default).\n */",
"@",
"Test",
"public",
"void",
"testCompactSerialization",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"Map",
"<",
"String",
",",
"Integer",
">",
"map",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"map",
".",
"put",
"(",
"\"",
"one",
"\"",
",",
"1",
")",
";",
"map",
".",
"put",
"(",
"\"",
"two",
"\"",
",",
"2",
")",
";",
"map",
".",
"put",
"(",
"\"",
"three",
"\"",
",",
"3",
")",
";",
"final",
"List",
"<",
"String",
">",
"array",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"array",
".",
"add",
"(",
"\"",
"a",
"\"",
")",
";",
"array",
".",
"add",
"(",
"\"",
"b",
"\"",
")",
";",
"array",
".",
"add",
"(",
"\"",
"c",
"\"",
")",
";",
"final",
"SerializationTestClass",
"original",
"=",
"new",
"SerializationTestClass",
"(",
"\"",
"original string value",
"\"",
",",
"123",
",",
"true",
",",
"map",
",",
"array",
")",
";",
"final",
"B2JsonOptions",
"options",
"=",
"B2JsonOptions",
".",
"builder",
"(",
")",
".",
"setSerializationOption",
"(",
"B2JsonOptions",
".",
"SerializationOption",
".",
"COMPACT",
")",
".",
"build",
"(",
")",
";",
"final",
"String",
"actual",
"=",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"original",
",",
"options",
")",
";",
"final",
"String",
"expected",
"=",
"\"",
"{",
"\\\"",
"arrayVal",
"\\\"",
":[",
"\\\"",
"a",
"\\\"",
",",
"\\\"",
"b",
"\\\"",
",",
"\\\"",
"c",
"\\\"",
"],",
"\\\"",
"booleanVal",
"\\\"",
":true,",
"\\\"",
"intVal",
"\\\"",
":123,",
"\\\"",
"mapVal",
"\\\"",
":{",
"\\\"",
"one",
"\\\"",
":1,",
"\\\"",
"two",
"\\\"",
":2,",
"\\\"",
"three",
"\\\"",
":3},",
"\\\"",
"stringVal",
"\\\"",
":",
"\\\"",
"original string value",
"\\\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expected",
",",
"actual",
")",
";",
"final",
"SerializationTestClass",
"derived",
"=",
"B2Json",
".",
"get",
"(",
")",
".",
"fromJson",
"(",
"actual",
",",
"SerializationTestClass",
".",
"class",
")",
";",
"assertEquals",
"(",
"original",
",",
"derived",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testTopLevelObjectIsParameterizedType",
"(",
")",
"throws",
"NoSuchFieldException",
",",
"IOException",
",",
"B2JsonException",
"{",
"final",
"Item",
"<",
"Integer",
">",
"item",
"=",
"new",
"Item",
"<",
">",
"(",
"123",
")",
";",
"final",
"Type",
"type",
"=",
"ClassThatUsesGenerics",
".",
"class",
".",
"getDeclaredField",
"(",
"\"",
"integerItem",
"\"",
")",
".",
"getGenericType",
"(",
")",
";",
"final",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"item",
",",
"B2JsonOptions",
".",
"DEFAULT",
",",
"out",
",",
"type",
")",
";",
"final",
"String",
"json",
"=",
"out",
".",
"toString",
"(",
"B2StringUtil",
".",
"UTF8",
")",
";",
"assertEquals",
"(",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"value",
"\\\"",
": 123",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
",",
"json",
")",
";",
"thrown",
".",
"expect",
"(",
"B2JsonException",
".",
"class",
")",
";",
"thrown",
".",
"expectMessage",
"(",
"\"",
"actualTypeArguments must be same length as class' type parameters",
"\"",
")",
";",
"B2Json",
".",
"get",
"(",
")",
".",
"toJson",
"(",
"item",
",",
"B2JsonOptions",
".",
"DEFAULT",
",",
"out",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testGenerics",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"ClassThatUsesGenerics",
"classThatUsesGenerics",
"=",
"new",
"ClassThatUsesGenerics",
"(",
"999",
",",
"new",
"Item",
"<",
">",
"(",
"\"",
"the string",
"\"",
")",
",",
"new",
"Item",
"<",
">",
"(",
"123",
")",
",",
"new",
"Item",
"<",
">",
"(",
"new",
"Item",
"<",
">",
"(",
"456L",
")",
")",
")",
";",
"final",
"String",
"expected",
"=",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"id",
"\\\"",
": 999,",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"integerItem",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"value",
"\\\"",
": 123",
"\\n",
"\"",
"+",
"\"",
" },",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"longItemItem",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"value",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"value",
"\\\"",
": 456",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
" },",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"stringItem",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"value",
"\\\"",
": ",
"\\\"",
"the string",
"\\\"",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expected",
",",
"b2Json",
".",
"toJson",
"(",
"classThatUsesGenerics",
")",
")",
";",
"final",
"ClassThatUsesGenerics",
"classThatUsesGenericsFromJson",
"=",
"b2Json",
".",
"fromJson",
"(",
"expected",
",",
"ClassThatUsesGenerics",
".",
"class",
")",
";",
"assertEquals",
"(",
"999",
",",
"classThatUsesGenericsFromJson",
".",
"id",
")",
";",
"assertEquals",
"(",
"\"",
"the string",
"\"",
",",
"classThatUsesGenericsFromJson",
".",
"stringItem",
".",
"value",
")",
";",
"assertEquals",
"(",
"new",
"Long",
"(",
"456",
")",
",",
"classThatUsesGenericsFromJson",
".",
"longItemItem",
".",
"value",
".",
"value",
")",
";",
"assertEquals",
"(",
"new",
"Integer",
"(",
"123",
")",
",",
"classThatUsesGenericsFromJson",
".",
"integerItem",
".",
"value",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testGenericArraySupport",
"(",
")",
"throws",
"B2JsonException",
"{",
"final",
"ClassWithGenericArrays",
"objectWithGenericArrays",
"=",
"new",
"ClassWithGenericArrays",
"(",
"new",
"ItemArray",
"<",
">",
"(",
"new",
"Integer",
"[",
"]",
"{",
"0",
",",
"1",
",",
"2",
",",
"3",
"}",
")",
",",
"new",
"ItemArray",
"<",
">",
"(",
"new",
"String",
"[",
"]",
"{",
"\"",
"a",
"\"",
",",
"\"",
"b",
"\"",
"}",
")",
")",
";",
"final",
"String",
"expected",
"=",
"\"",
"\"",
"+",
"\"",
"{",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"intArray",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"values",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" 0,",
"\\n",
"\"",
"+",
"\"",
" 1,",
"\\n",
"\"",
"+",
"\"",
" 2,",
"\\n",
"\"",
"+",
"\"",
" 3",
"\\n",
"\"",
"+",
"\"",
" ]",
"\\n",
"\"",
"+",
"\"",
" },",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"stringArray",
"\\\"",
": {",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"values",
"\\\"",
": [",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"a",
"\\\"",
",",
"\\n",
"\"",
"+",
"\"",
" ",
"\\\"",
"b",
"\\\"",
"\\n",
"\"",
"+",
"\"",
" ]",
"\\n",
"\"",
"+",
"\"",
" }",
"\\n",
"\"",
"+",
"\"",
"}",
"\"",
";",
"assertEquals",
"(",
"expected",
",",
"b2Json",
".",
"toJson",
"(",
"objectWithGenericArrays",
")",
")",
";",
"}",
"private",
"static",
"class",
"ClassThatUsesGenerics",
"{",
"@",
"B2Json",
".",
"required",
"private",
"int",
"id",
";",
"@",
"B2Json",
".",
"required",
"private",
"final",
"Item",
"<",
"String",
">",
"stringItem",
";",
"@",
"B2Json",
".",
"required",
"private",
"final",
"Item",
"<",
"Integer",
">",
"integerItem",
";",
"@",
"B2Json",
".",
"required",
"private",
"final",
"Item",
"<",
"Item",
"<",
"Long",
">",
">",
"longItemItem",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"id, stringItem, integerItem, longItemItem",
"\"",
")",
"public",
"ClassThatUsesGenerics",
"(",
"int",
"id",
",",
"Item",
"<",
"String",
">",
"stringItem",
",",
"Item",
"<",
"Integer",
">",
"integerItem",
",",
"Item",
"<",
"Item",
"<",
"Long",
">",
">",
"longItemItem",
")",
"{",
"this",
".",
"id",
"=",
"id",
";",
"this",
".",
"stringItem",
"=",
"stringItem",
";",
"this",
".",
"integerItem",
"=",
"integerItem",
";",
"this",
".",
"longItemItem",
"=",
"longItemItem",
";",
"}",
"}",
"private",
"static",
"class",
"Item",
"<",
"T",
">",
"{",
"@",
"B2Json",
".",
"required",
"private",
"final",
"T",
"value",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"value",
"\"",
")",
"public",
"Item",
"(",
"T",
"value",
")",
"{",
"this",
".",
"value",
"=",
"value",
";",
"}",
"public",
"T",
"getValue",
"(",
")",
"{",
"return",
"value",
";",
"}",
"}",
"private",
"static",
"class",
"ClassWithGenericArrays",
"{",
"@",
"B2Json",
".",
"required",
"private",
"final",
"ItemArray",
"<",
"Integer",
">",
"intArray",
";",
"@",
"B2Json",
".",
"required",
"private",
"final",
"ItemArray",
"<",
"String",
">",
"stringArray",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"intArray, stringArray",
"\"",
")",
"public",
"ClassWithGenericArrays",
"(",
"ItemArray",
"<",
"Integer",
">",
"intArray",
",",
"ItemArray",
"<",
"String",
">",
"stringArray",
")",
"{",
"this",
".",
"intArray",
"=",
"intArray",
";",
"this",
".",
"stringArray",
"=",
"stringArray",
";",
"}",
"}",
"private",
"static",
"class",
"ItemArray",
"<",
"T",
">",
"{",
"@",
"B2Json",
".",
"required",
"private",
"final",
"T",
"[",
"]",
"values",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"values",
"\"",
")",
"public",
"ItemArray",
"(",
"T",
"[",
"]",
"values",
")",
"{",
"this",
".",
"values",
"=",
"values",
";",
"}",
"}",
"}"
] | Unit tests for B2Json. | [
"Unit",
"tests",
"for",
"B2Json",
"."
] | [
"// A lot of the test classes have things that aren't used, but we don't care.",
"// A lot of the test classes could have weaker access, but we don't care.",
"// 'cuz ignored from json and set by constructor.",
"// These test cases are from: http://www.oracle.com/us/technologies/java/supplementary-142654.html",
"// Check de-serializing from string",
"// Check de-serializing from bytes",
"// Check serializing to string",
"// Check serializing to bytes",
"// ensure we can serialize a private member.",
"// ensure we can create with a private constructor and set a private member.",
"// an enum with no @B2Json.defaultForInvalidValue",
"// an enum with too many @B2Json.defaultForInvalidValues",
"// an enum with one @B2Json.defaultForInvalidEnumValue",
"// used by reflection",
"// used by reflection",
"// Any use of the class with B2Json should trigger the exception. Even",
"// serializing will need to initialize the handler, which should trigger",
"// an error.",
"// used by reflection",
"// the default value",
"// the default value",
"// NOT the default value; the value provided",
"// The error should be caught when the class is first used, even if the default",
"// isn't used.",
"// i *soooo* wanted to call this class \"North\",",
"// but the more boring name \"ContainsUnion\" is clearer.",
"// Version 3 is too soon",
"// Version 4 is the first version where it's present",
"// Version 6 is the last version where it's present",
"// Version 7 is too late.",
"// name is only in first 3 versions",
"// The omitNullString and omitNullInteger fields should not be present in the output",
"// All the fields should be in the output",
"// the underlying implementation of CharSequence that we deserialize is String",
"// setup my test object",
"// convert test object to JSON string",
"// Convert JSON string back to SerializationTestClass to ensure that",
"// the produced json can round-trip properly.",
"// Get a reference to a type object that describes an Item<Integer>...",
"// Now try without the type information"
] | [
{
"param": "B2BaseTest",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "B2BaseTest",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
feb9c3bcb94d4d9bf815ade7a8ac3ad64b7d5adb | tlucas30/b2-sdk-java | core/src/test/java/com/backblaze/b2/json/B2JsonTest.java | [
"MIT"
] | Java | ContainsUnion | // but the more boring name "ContainsUnion" is clearer. | but the more boring name "ContainsUnion" is clearer. | [
"but",
"the",
"more",
"boring",
"name",
"\"",
"ContainsUnion",
"\"",
"is",
"clearer",
"."
] | private static class ContainsUnion {
@B2Json.required
private final UnionAZ contained;
@B2Json.constructor(params = "contained")
private ContainsUnion(UnionAZ contained) {
this.contained = contained;
}
} | [
"private",
"static",
"class",
"ContainsUnion",
"{",
"@",
"B2Json",
".",
"required",
"private",
"final",
"UnionAZ",
"contained",
";",
"@",
"B2Json",
".",
"constructor",
"(",
"params",
"=",
"\"",
"contained",
"\"",
")",
"private",
"ContainsUnion",
"(",
"UnionAZ",
"contained",
")",
"{",
"this",
".",
"contained",
"=",
"contained",
";",
"}",
"}"
] | but the more boring name "ContainsUnion" is clearer. | [
"but",
"the",
"more",
"boring",
"name",
"\"",
"ContainsUnion",
"\"",
"is",
"clearer",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
febaee2c32d2f188fb1fdd6d3bf2825d17cc020b | wesleypsn/LabProg | Lab7/src/principal/Contribuinte.java | [
"MIT"
] | Java | Contribuinte | /**
* Classe abstrata que define as caracteristicas padrao dos contribuintes.
*/ | Classe abstrata que define as caracteristicas padrao dos contribuintes. | [
"Classe",
"abstrata",
"que",
"define",
"as",
"caracteristicas",
"padrao",
"dos",
"contribuintes",
"."
] | public abstract class Contribuinte {
private static int Num_Contribuintes_Cad = 0;
private String nome;
private int numeroDoContribuinte;
private boolean temCasaPropria = false;
private boolean temCarro = false;
private double valorDosBens;
/**
* Construtor da classe.
* @param nome Nome do contribuinte.
* @param numeroDoContribuinte Numero de cadastro do contribuinte.
* @param temCasaPropria Sera passado true se o contribuinte tiver casa propria, false se nao tiver.
* @param temCarro Sera passado true se o contribuinte tiver carro, false se nao tiver.
* @param valorDosBens Valor somado de todos os bens do contribuinte.
* @throws Exception Sera lancada caso alguma informacao passada ao construtor seja invalida.
*/
public Contribuinte(String nome, int numeroDoContribuinte, boolean temCasaPropria, boolean temCarro, double valorDosBens) throws Exception{
validaDados(nome, numeroDoContribuinte, valorDosBens);
this.temCasaPropria = temCasaPropria;
this.temCarro = temCarro;
Num_Contribuintes_Cad++;
}
/**
* Validacao dos dados passados pelo usuario.
* @param nome Nome do contribuinte.
* @param numeroDoContribuinte Numero de cadastro do contribuinte.
* @param valorDosBens Valor dos bens do contribuinte.
*/
private void validaDados(String nome, int numeroDoContribuinte, double valorDosBens) throws Exception{
if(nome != null && !nome.trim().isEmpty()) {
this.nome = nome;
}else {
throw new Exception("O nome nao pode ser vazio.");
}
if(numeroDoContribuinte >= 0 && numeroDoContribuinte <= Integer.MAX_VALUE) {
this.numeroDoContribuinte = numeroDoContribuinte;
}else {
throw new Exception("Numero de contribuinte invalido.");
}
if(valorDosBens >= 0) {
this.valorDosBens = valorDosBens;
}else {
throw new Exception("O valor dos bens nao pode ser negativo.");
}
}
/**
* Verifica se o sinal exterior de riqueza de um contribuinte e excessivo ou nao, tomando como base a media de todos os outros contribuintes de sua categoria.
* @param mediaDosContribuintes Media do valor dos bens dos contribuintes de uma mesma categoria.
* @return true caso o sinal de exterior de riqueza de um contribuinte seja excessivo, false se nao for excessivo.
*/
public boolean sinaisExterioresDeRiquezaExcessivos(double mediaDosContribuintes) {
double valorTotal = mediaDosContribuintes + (mediaDosContribuintes * 0.5);
return valorDosBens > valorTotal;
}
/**
* Metodo estatico que calcula a media dos bens dos contribuintes de uma categoria e acrecenta 50% ao valor medio.
* @return A media dos bens dos contribuintes acrescido de 50% desse valor.
*/
public static double calculaMediaDosBensDeContribuintes(List<?> lista) {
int somaDosBens=0;
for(int i = 0; i < lista.size(); i++) {
somaDosBens += ((Contribuinte) lista.get(i)).getValorDosBens();
}
double mediaDosBens = somaDosBens/lista.size();
return mediaDosBens *= 1.5;
}
/**
* Retorna o nome do contribuinte.
* @return O nome do contribuinte.
*/
public String getNome() {
return nome;
}
/**
* Retorna o numero de cadastro do contribuinte.
* @return O numero de cadastro do contribuinte.
*/
public int getNumeroDoContribuinte() {
return numeroDoContribuinte;
}
/**
* Retorna um booleano que diz se um contribuinte tem ou nao casa propria.
* @return true se tiver casa propria, false se nao tiver.
*/
public boolean temCasaPropria() {
return temCasaPropria;
}
/**
* Retorna um booleano que diz se um contribuinte tem ou nao carro.
* @return true se tiver carro, false se nao tiver.
*/
public boolean temCarro() {
return temCarro;
}
/**
* Retorna o valor somado de todos os bens do contribuintes.
* @return O valor total dos bens do contribuinte.
*/
public double getValorDosBens() {
return valorDosBens;
}
/**
* Metodo estatico que retorna o numero de contribuintes ja cadastrados no sistema.
* @return O numero de contribuintes ja cadastrados.
*/
public static int numeroContribuintesCadastrados() {
return Num_Contribuintes_Cad;
}
/**
* Faz o calculo devido do imposto a ser pago, sendo esse valor o tributo subtraido do desconto referente a cada contribuinte.
* @return O valor de todos tributos subtraido do desconto devido. Se o valor do desconto for maior que seus tributos, o contribuinte nao paga imposto.
*/
public double calculaImpostoASerPago() {
double imposto = calculaTributos();
double desconto = calculaDesconto();
return imposto < desconto ? 0 : (imposto-desconto);
}
/**
* Metodo abstrato que sugere o calculo dos tributos de cada contribuinte.
* @return O valor devido do imposto a ser pago.
*/
public abstract double calculaTributos();
/**
* Metodo abstrato que sugere o calculo do desconto aplicado ao tributo de um contribuinte.
* @return O valor do desconto a ser aplicado sobre o tributo de um contribuinte.
*/
public abstract double calculaDesconto();
/**
* Representacao em String dos dados do contribuinte.
*/
@Override
public String toString() {
StringBuilder string = new StringBuilder();
string.append("Profissao do contribuinte: "+getClass().getSimpleName());
string.append("\nNome do contribuinte: "+nome);
string.append("\nNumero do contribuinte: "+numeroDoContribuinte);
string.append(String.format("\nTem casa propria: %s", temCasaPropria ? "Sim" : "Nao"));
string.append(String.format("\nTem carro proprio: %s", temCarro ? "Sim" : "Nao"));
string.append(String.format("\nValor total dos bens = R$ %,.2f", valorDosBens));
return string.toString();
}
} | [
"public",
"abstract",
"class",
"Contribuinte",
"{",
"private",
"static",
"int",
"Num_Contribuintes_Cad",
"=",
"0",
";",
"private",
"String",
"nome",
";",
"private",
"int",
"numeroDoContribuinte",
";",
"private",
"boolean",
"temCasaPropria",
"=",
"false",
";",
"private",
"boolean",
"temCarro",
"=",
"false",
";",
"private",
"double",
"valorDosBens",
";",
"/**\n\t * Construtor da classe.\n\t * @param nome Nome do contribuinte.\n\t * @param numeroDoContribuinte Numero de cadastro do contribuinte.\n\t * @param temCasaPropria Sera passado true se o contribuinte tiver casa propria, false se nao tiver.\n\t * @param temCarro Sera passado true se o contribuinte tiver carro, false se nao tiver.\n\t * @param valorDosBens Valor somado de todos os bens do contribuinte.\n\t * @throws Exception Sera lancada caso alguma informacao passada ao construtor seja invalida.\n\t */",
"public",
"Contribuinte",
"(",
"String",
"nome",
",",
"int",
"numeroDoContribuinte",
",",
"boolean",
"temCasaPropria",
",",
"boolean",
"temCarro",
",",
"double",
"valorDosBens",
")",
"throws",
"Exception",
"{",
"validaDados",
"(",
"nome",
",",
"numeroDoContribuinte",
",",
"valorDosBens",
")",
";",
"this",
".",
"temCasaPropria",
"=",
"temCasaPropria",
";",
"this",
".",
"temCarro",
"=",
"temCarro",
";",
"Num_Contribuintes_Cad",
"++",
";",
"}",
"/**\n\t * Validacao dos dados passados pelo usuario.\n\t * @param nome Nome do contribuinte.\n\t * @param numeroDoContribuinte Numero de cadastro do contribuinte.\n\t * @param valorDosBens Valor dos bens do contribuinte.\n\t */",
"private",
"void",
"validaDados",
"(",
"String",
"nome",
",",
"int",
"numeroDoContribuinte",
",",
"double",
"valorDosBens",
")",
"throws",
"Exception",
"{",
"if",
"(",
"nome",
"!=",
"null",
"&&",
"!",
"nome",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"this",
".",
"nome",
"=",
"nome",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"\"",
"O nome nao pode ser vazio.",
"\"",
")",
";",
"}",
"if",
"(",
"numeroDoContribuinte",
">=",
"0",
"&&",
"numeroDoContribuinte",
"<=",
"Integer",
".",
"MAX_VALUE",
")",
"{",
"this",
".",
"numeroDoContribuinte",
"=",
"numeroDoContribuinte",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"\"",
"Numero de contribuinte invalido.",
"\"",
")",
";",
"}",
"if",
"(",
"valorDosBens",
">=",
"0",
")",
"{",
"this",
".",
"valorDosBens",
"=",
"valorDosBens",
";",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"\"",
"O valor dos bens nao pode ser negativo.",
"\"",
")",
";",
"}",
"}",
"/**\n\t * Verifica se o sinal exterior de riqueza de um contribuinte e excessivo ou nao, tomando como base a media de todos os outros contribuintes de sua categoria.\n\t * @param mediaDosContribuintes Media do valor dos bens dos contribuintes de uma mesma categoria.\n\t * @return true caso o sinal de exterior de riqueza de um contribuinte seja excessivo, false se nao for excessivo.\n\t */",
"public",
"boolean",
"sinaisExterioresDeRiquezaExcessivos",
"(",
"double",
"mediaDosContribuintes",
")",
"{",
"double",
"valorTotal",
"=",
"mediaDosContribuintes",
"+",
"(",
"mediaDosContribuintes",
"*",
"0.5",
")",
";",
"return",
"valorDosBens",
">",
"valorTotal",
";",
"}",
"/**\n\t * Metodo estatico que calcula a media dos bens dos contribuintes de uma categoria e acrecenta 50% ao valor medio.\n\t * @return A media dos bens dos contribuintes acrescido de 50% desse valor.\n\t */",
"public",
"static",
"double",
"calculaMediaDosBensDeContribuintes",
"(",
"List",
"<",
"?",
">",
"lista",
")",
"{",
"int",
"somaDosBens",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"lista",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"somaDosBens",
"+=",
"(",
"(",
"Contribuinte",
")",
"lista",
".",
"get",
"(",
"i",
")",
")",
".",
"getValorDosBens",
"(",
")",
";",
"}",
"double",
"mediaDosBens",
"=",
"somaDosBens",
"/",
"lista",
".",
"size",
"(",
")",
";",
"return",
"mediaDosBens",
"*=",
"1.5",
";",
"}",
"/**\n\t * Retorna o nome do contribuinte.\n\t * @return O nome do contribuinte.\n\t */",
"public",
"String",
"getNome",
"(",
")",
"{",
"return",
"nome",
";",
"}",
"/**\n\t * Retorna o numero de cadastro do contribuinte.\n\t * @return O numero de cadastro do contribuinte.\n\t */",
"public",
"int",
"getNumeroDoContribuinte",
"(",
")",
"{",
"return",
"numeroDoContribuinte",
";",
"}",
"/**\n\t * Retorna um booleano que diz se um contribuinte tem ou nao casa propria.\n\t * @return true se tiver casa propria, false se nao tiver.\n\t */",
"public",
"boolean",
"temCasaPropria",
"(",
")",
"{",
"return",
"temCasaPropria",
";",
"}",
"/**\n\t * Retorna um booleano que diz se um contribuinte tem ou nao carro.\n\t * @return true se tiver carro, false se nao tiver.\n\t */",
"public",
"boolean",
"temCarro",
"(",
")",
"{",
"return",
"temCarro",
";",
"}",
"/**\n\t * Retorna o valor somado de todos os bens do contribuintes.\n\t * @return O valor total dos bens do contribuinte.\n\t */",
"public",
"double",
"getValorDosBens",
"(",
")",
"{",
"return",
"valorDosBens",
";",
"}",
"/**\n\t * Metodo estatico que retorna o numero de contribuintes ja cadastrados no sistema.\n\t * @return O numero de contribuintes ja cadastrados.\n\t */",
"public",
"static",
"int",
"numeroContribuintesCadastrados",
"(",
")",
"{",
"return",
"Num_Contribuintes_Cad",
";",
"}",
"/**\n\t * Faz o calculo devido do imposto a ser pago, sendo esse valor o tributo subtraido do desconto referente a cada contribuinte.\n\t * @return O valor de todos tributos subtraido do desconto devido. Se o valor do desconto for maior que seus tributos, o contribuinte nao paga imposto.\n\t */",
"public",
"double",
"calculaImpostoASerPago",
"(",
")",
"{",
"double",
"imposto",
"=",
"calculaTributos",
"(",
")",
";",
"double",
"desconto",
"=",
"calculaDesconto",
"(",
")",
";",
"return",
"imposto",
"<",
"desconto",
"?",
"0",
":",
"(",
"imposto",
"-",
"desconto",
")",
";",
"}",
"/**\n\t * Metodo abstrato que sugere o calculo dos tributos de cada contribuinte.\n\t * @return O valor devido do imposto a ser pago.\n\t */",
"public",
"abstract",
"double",
"calculaTributos",
"(",
")",
";",
"/**\n\t * Metodo abstrato que sugere o calculo do desconto aplicado ao tributo de um contribuinte.\n\t * @return O valor do desconto a ser aplicado sobre o tributo de um contribuinte.\n\t */",
"public",
"abstract",
"double",
"calculaDesconto",
"(",
")",
";",
"/**\n\t * Representacao em String dos dados do contribuinte.\n\t */",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"StringBuilder",
"string",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"string",
".",
"append",
"(",
"\"",
"Profissao do contribuinte: ",
"\"",
"+",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
";",
"string",
".",
"append",
"(",
"\"",
"\\n",
"Nome do contribuinte: ",
"\"",
"+",
"nome",
")",
";",
"string",
".",
"append",
"(",
"\"",
"\\n",
"Numero do contribuinte: ",
"\"",
"+",
"numeroDoContribuinte",
")",
";",
"string",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"",
"\\n",
"Tem casa propria: %s",
"\"",
",",
"temCasaPropria",
"?",
"\"",
"Sim",
"\"",
":",
"\"",
"Nao",
"\"",
")",
")",
";",
"string",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"",
"\\n",
"Tem carro proprio: %s",
"\"",
",",
"temCarro",
"?",
"\"",
"Sim",
"\"",
":",
"\"",
"Nao",
"\"",
")",
")",
";",
"string",
".",
"append",
"(",
"String",
".",
"format",
"(",
"\"",
"\\n",
"Valor total dos bens = R$ %,.2f",
"\"",
",",
"valorDosBens",
")",
")",
";",
"return",
"string",
".",
"toString",
"(",
")",
";",
"}",
"}"
] | Classe abstrata que define as caracteristicas padrao dos contribuintes. | [
"Classe",
"abstrata",
"que",
"define",
"as",
"caracteristicas",
"padrao",
"dos",
"contribuintes",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fec24bc704b6a8aa9f812a178a02118e744a7ef4 | tanvir-ahmed-m4/fop-0.20.5 | src/org/apache/fop/apps/PrintStarter.java | [
"Apache-1.1"
] | Java | PrintStarter | /**
* This class prints a xsl-fo dokument without interaction.
* At the moment java has not the possibility to configure the printer and it's
* options without interaction (30.03.2000).
* This class allows to print a set of pages (from-to), even/odd pages and many copies.
* - Print from page xxx: property name - start, value int
* - Print to page xxx: property name - end, value int
* - Print even/odd pages: property name - even, value boolean
* - Print xxx copies: property name - copies, value int
*
*/ | This class prints a xsl-fo dokument without interaction.
At the moment java has not the possibility to configure the printer and it's
options without interaction (30.03.2000).
This class allows to print a set of pages (from-to), even/odd pages and many copies. | [
"This",
"class",
"prints",
"a",
"xsl",
"-",
"fo",
"dokument",
"without",
"interaction",
".",
"At",
"the",
"moment",
"java",
"has",
"not",
"the",
"possibility",
"to",
"configure",
"the",
"printer",
"and",
"it",
"'",
"s",
"options",
"without",
"interaction",
"(",
"30",
".",
"03",
".",
"2000",
")",
".",
"This",
"class",
"allows",
"to",
"print",
"a",
"set",
"of",
"pages",
"(",
"from",
"-",
"to",
")",
"even",
"/",
"odd",
"pages",
"and",
"many",
"copies",
"."
] | public class PrintStarter extends CommandLineStarter {
public PrintStarter(CommandLineOptions options) throws FOPException {
super(options);
}
public void run() throws FOPException {
Driver driver = new Driver();
if (errorDump) {
driver.setErrorDump(true);
}
// Nov 18, 02 eliminates spurious [ERROR] message to logger
driver.setLogger (new ConsoleLogger(ConsoleLogger.LEVEL_INFO)) ;
log.info (Version.getVersion()) ;
XMLReader parser = inputHandler.getParser();
PrinterJob pj = PrinterJob.getPrinterJob();
if(System.getProperty("dialog") != null)
if(!pj.printDialog())
throw new FOPException("Printing cancelled by operator");
PrintRenderer renderer = new PrintRenderer(pj);
int copies = getIntProperty("copies", 1);
pj.setCopies(copies);
//renderer.setCopies(copies);
try {
driver.setRenderer(renderer);
driver.render(parser, inputHandler.getInputSource());
} catch (Exception e) {
if (e instanceof FOPException) {
throw (FOPException)e;
}
throw new FOPException(e);
}
System.exit(0);
}
int getIntProperty(String name, int def) {
String propValue = System.getProperty(name);
if(propValue != null) {
try {
return Integer.parseInt(propValue);
} catch (Exception e) {
return def;
}
} else {
return def;
}
}
class PrintRenderer extends AWTRenderer {
private static final int EVEN_AND_ALL = 0;
private static final int EVEN = 1;
private static final int ODD = 2;
private int startNumber;
private int endNumber;
private int mode = EVEN_AND_ALL;
private int copies = 1;
private PrinterJob printerJob;
PrintRenderer(PrinterJob printerJob) {
super(null);
this.printerJob = printerJob;
startNumber = getIntProperty("start", 1) - 1;
endNumber = getIntProperty("end", -1);
printerJob.setPageable(this);
mode = EVEN_AND_ALL;
String str = System.getProperty("even");
if (str != null) {
try {
mode = Boolean.valueOf(str).booleanValue() ? EVEN : ODD;
} catch (Exception e) {}
}
}
public void stopRenderer(OutputStream outputStream)
throws IOException {
super.stopRenderer(outputStream);
if(endNumber == -1)
endNumber = getPageCount();
ArrayList numbers = getInvalidPageNumbers();
for (int i = numbers.size() - 1; i > -1; i--)
removePage(Integer.parseInt((String)numbers.get(i)));
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
throw new IOException(
"Unable to print: " + e.getClass().getName() +
": " + e.getMessage());
}
}
public void renderPage(Page page) {
pageWidth = (int)((float)page.getWidth() / 1000f);
pageHeight = (int)((float)page.getHeight() / 1000f);
super.renderPage(page);
}
private ArrayList getInvalidPageNumbers() {
ArrayList vec = new ArrayList();
int max = getPageCount();
boolean isValid;
for (int i = 0; i < max; i++) {
isValid = true;
if (i < startNumber || i > endNumber) {
isValid = false;
} else if (mode != EVEN_AND_ALL) {
if (mode == EVEN && ((i + 1) % 2 != 0))
isValid = false;
else if (mode == ODD && ((i + 1) % 2 != 1))
isValid = false;
}
if (!isValid)
vec.add(i + "");
}
return vec;
}
/* TODO: I'm totally not sure that this is necessary -Mark
void setCopies(int val) {
copies = val;
ArrayList copie = tree.getPages();
for (int i = 1; i < copies; i++) {
tree.getPages().addAll(copie);
}
}
*/
} // class PrintRenderer
} | [
"public",
"class",
"PrintStarter",
"extends",
"CommandLineStarter",
"{",
"public",
"PrintStarter",
"(",
"CommandLineOptions",
"options",
")",
"throws",
"FOPException",
"{",
"super",
"(",
"options",
")",
";",
"}",
"public",
"void",
"run",
"(",
")",
"throws",
"FOPException",
"{",
"Driver",
"driver",
"=",
"new",
"Driver",
"(",
")",
";",
"if",
"(",
"errorDump",
")",
"{",
"driver",
".",
"setErrorDump",
"(",
"true",
")",
";",
"}",
"driver",
".",
"setLogger",
"(",
"new",
"ConsoleLogger",
"(",
"ConsoleLogger",
".",
"LEVEL_INFO",
")",
")",
";",
"log",
".",
"info",
"(",
"Version",
".",
"getVersion",
"(",
")",
")",
";",
"XMLReader",
"parser",
"=",
"inputHandler",
".",
"getParser",
"(",
")",
";",
"PrinterJob",
"pj",
"=",
"PrinterJob",
".",
"getPrinterJob",
"(",
")",
";",
"if",
"(",
"System",
".",
"getProperty",
"(",
"\"",
"dialog",
"\"",
")",
"!=",
"null",
")",
"if",
"(",
"!",
"pj",
".",
"printDialog",
"(",
")",
")",
"throw",
"new",
"FOPException",
"(",
"\"",
"Printing cancelled by operator",
"\"",
")",
";",
"PrintRenderer",
"renderer",
"=",
"new",
"PrintRenderer",
"(",
"pj",
")",
";",
"int",
"copies",
"=",
"getIntProperty",
"(",
"\"",
"copies",
"\"",
",",
"1",
")",
";",
"pj",
".",
"setCopies",
"(",
"copies",
")",
";",
"try",
"{",
"driver",
".",
"setRenderer",
"(",
"renderer",
")",
";",
"driver",
".",
"render",
"(",
"parser",
",",
"inputHandler",
".",
"getInputSource",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"FOPException",
")",
"{",
"throw",
"(",
"FOPException",
")",
"e",
";",
"}",
"throw",
"new",
"FOPException",
"(",
"e",
")",
";",
"}",
"System",
".",
"exit",
"(",
"0",
")",
";",
"}",
"int",
"getIntProperty",
"(",
"String",
"name",
",",
"int",
"def",
")",
"{",
"String",
"propValue",
"=",
"System",
".",
"getProperty",
"(",
"name",
")",
";",
"if",
"(",
"propValue",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"propValue",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"return",
"def",
";",
"}",
"}",
"else",
"{",
"return",
"def",
";",
"}",
"}",
"class",
"PrintRenderer",
"extends",
"AWTRenderer",
"{",
"private",
"static",
"final",
"int",
"EVEN_AND_ALL",
"=",
"0",
";",
"private",
"static",
"final",
"int",
"EVEN",
"=",
"1",
";",
"private",
"static",
"final",
"int",
"ODD",
"=",
"2",
";",
"private",
"int",
"startNumber",
";",
"private",
"int",
"endNumber",
";",
"private",
"int",
"mode",
"=",
"EVEN_AND_ALL",
";",
"private",
"int",
"copies",
"=",
"1",
";",
"private",
"PrinterJob",
"printerJob",
";",
"PrintRenderer",
"(",
"PrinterJob",
"printerJob",
")",
"{",
"super",
"(",
"null",
")",
";",
"this",
".",
"printerJob",
"=",
"printerJob",
";",
"startNumber",
"=",
"getIntProperty",
"(",
"\"",
"start",
"\"",
",",
"1",
")",
"-",
"1",
";",
"endNumber",
"=",
"getIntProperty",
"(",
"\"",
"end",
"\"",
",",
"-",
"1",
")",
";",
"printerJob",
".",
"setPageable",
"(",
"this",
")",
";",
"mode",
"=",
"EVEN_AND_ALL",
";",
"String",
"str",
"=",
"System",
".",
"getProperty",
"(",
"\"",
"even",
"\"",
")",
";",
"if",
"(",
"str",
"!=",
"null",
")",
"{",
"try",
"{",
"mode",
"=",
"Boolean",
".",
"valueOf",
"(",
"str",
")",
".",
"booleanValue",
"(",
")",
"?",
"EVEN",
":",
"ODD",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"}",
"}",
"}",
"public",
"void",
"stopRenderer",
"(",
"OutputStream",
"outputStream",
")",
"throws",
"IOException",
"{",
"super",
".",
"stopRenderer",
"(",
"outputStream",
")",
";",
"if",
"(",
"endNumber",
"==",
"-",
"1",
")",
"endNumber",
"=",
"getPageCount",
"(",
")",
";",
"ArrayList",
"numbers",
"=",
"getInvalidPageNumbers",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"numbers",
".",
"size",
"(",
")",
"-",
"1",
";",
"i",
">",
"-",
"1",
";",
"i",
"--",
")",
"removePage",
"(",
"Integer",
".",
"parseInt",
"(",
"(",
"String",
")",
"numbers",
".",
"get",
"(",
"i",
")",
")",
")",
";",
"try",
"{",
"printerJob",
".",
"print",
"(",
")",
";",
"}",
"catch",
"(",
"PrinterException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"throw",
"new",
"IOException",
"(",
"\"",
"Unable to print: ",
"\"",
"+",
"e",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"",
": ",
"\"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"public",
"void",
"renderPage",
"(",
"Page",
"page",
")",
"{",
"pageWidth",
"=",
"(",
"int",
")",
"(",
"(",
"float",
")",
"page",
".",
"getWidth",
"(",
")",
"/",
"1000f",
")",
";",
"pageHeight",
"=",
"(",
"int",
")",
"(",
"(",
"float",
")",
"page",
".",
"getHeight",
"(",
")",
"/",
"1000f",
")",
";",
"super",
".",
"renderPage",
"(",
"page",
")",
";",
"}",
"private",
"ArrayList",
"getInvalidPageNumbers",
"(",
")",
"{",
"ArrayList",
"vec",
"=",
"new",
"ArrayList",
"(",
")",
";",
"int",
"max",
"=",
"getPageCount",
"(",
")",
";",
"boolean",
"isValid",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"isValid",
"=",
"true",
";",
"if",
"(",
"i",
"<",
"startNumber",
"||",
"i",
">",
"endNumber",
")",
"{",
"isValid",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"mode",
"!=",
"EVEN_AND_ALL",
")",
"{",
"if",
"(",
"mode",
"==",
"EVEN",
"&&",
"(",
"(",
"i",
"+",
"1",
")",
"%",
"2",
"!=",
"0",
")",
")",
"isValid",
"=",
"false",
";",
"else",
"if",
"(",
"mode",
"==",
"ODD",
"&&",
"(",
"(",
"i",
"+",
"1",
")",
"%",
"2",
"!=",
"1",
")",
")",
"isValid",
"=",
"false",
";",
"}",
"if",
"(",
"!",
"isValid",
")",
"vec",
".",
"add",
"(",
"i",
"+",
"\"",
"\"",
")",
";",
"}",
"return",
"vec",
";",
"}",
"/* TODO: I'm totally not sure that this is necessary -Mark\n void setCopies(int val) {\n copies = val;\n ArrayList copie = tree.getPages();\n for (int i = 1; i < copies; i++) {\n tree.getPages().addAll(copie);\n }\n\n }\n */",
"}",
"}"
] | This class prints a xsl-fo dokument without interaction. | [
"This",
"class",
"prints",
"a",
"xsl",
"-",
"fo",
"dokument",
"without",
"interaction",
"."
] | [
"// Nov 18, 02 eliminates spurious [ERROR] message to logger",
"//renderer.setCopies(copies);",
"// class PrintRenderer"
] | [
{
"param": "CommandLineStarter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "CommandLineStarter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fec3ff3863e1efa10df0c4a31be951cdc492e0da | Uniandes-isis2603/s3_Dietas_201910 | s3_dietas-api/src/main/java/co/edu/uniandes/csw/dietas/resources/CalificacionYComentarioDePersonaResourse.java | [
"MIT"
] | Java | CalificacionYComentarioDePersonaResourse | /**
*
* @author Andrea Montoya
*/ | @author Andrea Montoya | [
"@author",
"Andrea",
"Montoya"
] | @Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class CalificacionYComentarioDePersonaResourse {
private static final Logger LOGGER = Logger.getLogger(CalificacionYComentarioDePersonaResourse.class.getName());
@Inject
private CalificacionYComentarioDePersonaLogic calificacionycomentarioDePersonaLogic;
@Inject
private CalificacionYComentarioLogic calificacionycomentarioLogic;
/**
* Asocia una CalificacionYComentario existente con una persona existente
*
* @param personasId El ID de la persona que se va a asociar
* @param calificacionycomentarioId El ID de la CalificacionYComentario al cual se le va a asociar la persona
* @return JSON {@link SuspensionDetailDTO}
* @throws WebApplicationException {@link WebApplicationExceptionMapper} -
* Error de lógica que se genera cuando no se encuentra la suspension.
*/
@POST
@Path("{calificacionycomentarioId: \\d+}")
public CalificacionYComentarioDTO addCalificacionYComentario(@PathParam("personasId") Long personasId, @PathParam("calificacionycomentarioId") Long calificacionycomentarioId) {
if (calificacionycomentarioLogic.getCalificacionYComentario(calificacionycomentarioId) == null) {
throw new WebApplicationException("El recurso /calificacionycomentario/" + calificacionycomentarioId + " no existe.", 404);
}
CalificacionYComentarioDTO dto = new CalificacionYComentarioDTO(calificacionycomentarioDePersonaLogic.addCalificacionYComentario(personasId, calificacionycomentarioId));
return dto;
}
/**
* Busca y devuelve todas las personas que existen en una CalificacionYComentario.
*
* @param personasId El ID de la persona del cual se buscan las CalificacionYComentario
* @return JSONArray {@link CalificacionYComentarioDTO} - Las CalificacionYComentario encontradas en la
* persona. Si no hay ninguna retorna una lista vacía.
*/
@GET
public List<CalificacionYComentarioDTO> getCalificacionesYComentarios(@PathParam("personasId") Long personasId) {
List<CalificacionYComentarioDTO> lista = personaListEntity2DTO(calificacionycomentarioDePersonaLogic.getCalificacionesYComentarios(personasId));
return lista;
}
/**
* Convierte una lista de PersonaEntity a una lista de PersonaDTO.
*
* @param entityList Lista de PersonaEntity a convertir.
* @return Lista de PersonaDTO convertida.
*/
private List<CalificacionYComentarioDTO> personaListEntity2DTO(List<CalificacionYComentarioEntity> entityList) {
List<CalificacionYComentarioDTO> list = new ArrayList<>();
for (CalificacionYComentarioEntity entity : entityList) {
list.add(new CalificacionYComentarioDTO(entity));
}
return list;
}
} | [
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"public",
"class",
"CalificacionYComentarioDePersonaResourse",
"{",
"private",
"static",
"final",
"Logger",
"LOGGER",
"=",
"Logger",
".",
"getLogger",
"(",
"CalificacionYComentarioDePersonaResourse",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"@",
"Inject",
"private",
"CalificacionYComentarioDePersonaLogic",
"calificacionycomentarioDePersonaLogic",
";",
"@",
"Inject",
"private",
"CalificacionYComentarioLogic",
"calificacionycomentarioLogic",
";",
"/**\r\n * Asocia una CalificacionYComentario existente con una persona existente\r\n *\r\n * @param personasId El ID de la persona que se va a asociar\r\n * @param calificacionycomentarioId El ID de la CalificacionYComentario al cual se le va a asociar la persona\r\n * @return JSON {@link SuspensionDetailDTO} \r\n * @throws WebApplicationException {@link WebApplicationExceptionMapper} -\r\n * Error de lógica que se genera cuando no se encuentra la suspension.\r\n */",
"@",
"POST",
"@",
"Path",
"(",
"\"",
"{calificacionycomentarioId: ",
"\\\\",
"d+}",
"\"",
")",
"public",
"CalificacionYComentarioDTO",
"addCalificacionYComentario",
"(",
"@",
"PathParam",
"(",
"\"",
"personasId",
"\"",
")",
"Long",
"personasId",
",",
"@",
"PathParam",
"(",
"\"",
"calificacionycomentarioId",
"\"",
")",
"Long",
"calificacionycomentarioId",
")",
"{",
"if",
"(",
"calificacionycomentarioLogic",
".",
"getCalificacionYComentario",
"(",
"calificacionycomentarioId",
")",
"==",
"null",
")",
"{",
"throw",
"new",
"WebApplicationException",
"(",
"\"",
"El recurso /calificacionycomentario/",
"\"",
"+",
"calificacionycomentarioId",
"+",
"\"",
" no existe.",
"\"",
",",
"404",
")",
";",
"}",
"CalificacionYComentarioDTO",
"dto",
"=",
"new",
"CalificacionYComentarioDTO",
"(",
"calificacionycomentarioDePersonaLogic",
".",
"addCalificacionYComentario",
"(",
"personasId",
",",
"calificacionycomentarioId",
")",
")",
";",
"return",
"dto",
";",
"}",
"/**\r\n * Busca y devuelve todas las personas que existen en una CalificacionYComentario.\r\n *\r\n * @param personasId El ID de la persona del cual se buscan las CalificacionYComentario\r\n * @return JSONArray {@link CalificacionYComentarioDTO} - Las CalificacionYComentario encontradas en la\r\n * persona. Si no hay ninguna retorna una lista vacía.\r\n */",
"@",
"GET",
"public",
"List",
"<",
"CalificacionYComentarioDTO",
">",
"getCalificacionesYComentarios",
"(",
"@",
"PathParam",
"(",
"\"",
"personasId",
"\"",
")",
"Long",
"personasId",
")",
"{",
"List",
"<",
"CalificacionYComentarioDTO",
">",
"lista",
"=",
"personaListEntity2DTO",
"(",
"calificacionycomentarioDePersonaLogic",
".",
"getCalificacionesYComentarios",
"(",
"personasId",
")",
")",
";",
"return",
"lista",
";",
"}",
"/**\r\n * Convierte una lista de PersonaEntity a una lista de PersonaDTO.\r\n *\r\n * @param entityList Lista de PersonaEntity a convertir.\r\n * @return Lista de PersonaDTO convertida.\r\n */",
"private",
"List",
"<",
"CalificacionYComentarioDTO",
">",
"personaListEntity2DTO",
"(",
"List",
"<",
"CalificacionYComentarioEntity",
">",
"entityList",
")",
"{",
"List",
"<",
"CalificacionYComentarioDTO",
">",
"list",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"for",
"(",
"CalificacionYComentarioEntity",
"entity",
":",
"entityList",
")",
"{",
"list",
".",
"add",
"(",
"new",
"CalificacionYComentarioDTO",
"(",
"entity",
")",
")",
";",
"}",
"return",
"list",
";",
"}",
"}"
] | @author Andrea Montoya | [
"@author",
"Andrea",
"Montoya"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fec71236a778e363a405bfc0cf3cf13baa30a44a | danielvilas/ArduinoCurrentMonitor | javaLogger/src/main/java/es/daniel/datalogger/data/LogData.java | [
"MIT"
] | Java | LogData | /**
* Created by daniel on 11/6/17.
*/ | Created by daniel on 11/6/17. | [
"Created",
"by",
"daniel",
"on",
"11",
"/",
"6",
"/",
"17",
"."
] | public class LogData {
private byte[] rawData;
private long micros;
private int A0;
private int A1;
private DataType type;
public Date getDate() {
return date;
}
private Date date=null;
private long deltaMicros=-1;
public LogData(byte[] rawData){
long t0= ByteBuffer.wrap(rawData,0,4).getInt();
int a0 = ByteBuffer.wrap(rawData,4,2).getShort();
int a1 = ByteBuffer.wrap(rawData,6,2).getShort();
this.rawData=rawData;
if(t0 == -1L && a0==-1 && a1==-1){
this.micros=this.A0 =this.A1 = -1;
type=DataType.Sync;
}else{
this.micros=0x00FFFFFFFFL &t0;
this.A0 =0x03FF & a0;
this.A1 = 0x03FF & a1;
type=DataType.Data;
}
}
public LogData(String data){
StringTokenizer st = new StringTokenizer(data,",");
String stMicros = st.nextToken().trim();
String stA0 =st.nextToken().trim();
String stA1=st.nextToken().trim();
String stDate=st.nextToken().trim();
String stDelta=st.nextToken().trim();
if(stMicros.startsWith("-")){
long tmp = Long.parseLong(stMicros,16);
long tmp2 = 0x00FFFFFFFFL & tmp;
this.micros=(tmp==-1)?tmp:tmp2;
}else{
this.micros=Long.parseLong(stMicros,16);
}
this.A0=Integer.parseInt(stA0);
this.A1=Integer.parseInt(stA1);
this.date=new Date();
this.date.setTime(Long.parseLong(stDate));
this.deltaMicros=Long.parseLong(stDelta);
type=DataType.Data;
}
private LogData(DataType type){
this.type=type;
}
public void overFlowMicros(int i){
// this.micros+=i*0x00FFFFFFFFL;
this.micros+=i*0x0100000000L;
}
@Override
public String toString() {
if(this.type==DataType.Data) {
return "(" + Long.toString(micros,16) + ", " + A0 + ", " + A1+ ", " +date+ ", "+deltaMicros + ")";
}else //if(type==DataType.Sync)
{
return "Sync";
}
}
public String toCsvString(){
if(this.type==DataType.Data) {
if(date==null){
return Long.toString(micros,16) + ", " + A0 + ", " + A1+ ", 0, 0";
}
return Long.toString(micros,16) + ", " + A0 + ", " + A1+ ", " +date.getTime()+ ", "+deltaMicros;
}
return "";
}
public byte[] getRawData() {
return rawData;
}
public long getMicros() {
return micros;
}
public int getA0() {
return A0;
}
public int getA1() {
return A1;
}
public DataType getType() {
return type;
}
public static LogData syncData(){
return new LogData(DataType.Sync);
}
public void fillDate(Date currDate) {
if(date==null)
date=currDate;
}
public void fillDeltaMicros(long delta) {
if(deltaMicros==-1)
deltaMicros=delta;
}
} | [
"public",
"class",
"LogData",
"{",
"private",
"byte",
"[",
"]",
"rawData",
";",
"private",
"long",
"micros",
";",
"private",
"int",
"A0",
";",
"private",
"int",
"A1",
";",
"private",
"DataType",
"type",
";",
"public",
"Date",
"getDate",
"(",
")",
"{",
"return",
"date",
";",
"}",
"private",
"Date",
"date",
"=",
"null",
";",
"private",
"long",
"deltaMicros",
"=",
"-",
"1",
";",
"public",
"LogData",
"(",
"byte",
"[",
"]",
"rawData",
")",
"{",
"long",
"t0",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"rawData",
",",
"0",
",",
"4",
")",
".",
"getInt",
"(",
")",
";",
"int",
"a0",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"rawData",
",",
"4",
",",
"2",
")",
".",
"getShort",
"(",
")",
";",
"int",
"a1",
"=",
"ByteBuffer",
".",
"wrap",
"(",
"rawData",
",",
"6",
",",
"2",
")",
".",
"getShort",
"(",
")",
";",
"this",
".",
"rawData",
"=",
"rawData",
";",
"if",
"(",
"t0",
"==",
"-",
"1L",
"&&",
"a0",
"==",
"-",
"1",
"&&",
"a1",
"==",
"-",
"1",
")",
"{",
"this",
".",
"micros",
"=",
"this",
".",
"A0",
"=",
"this",
".",
"A1",
"=",
"-",
"1",
";",
"type",
"=",
"DataType",
".",
"Sync",
";",
"}",
"else",
"{",
"this",
".",
"micros",
"=",
"0x00FFFFFFFFL",
"&",
"t0",
";",
"this",
".",
"A0",
"=",
"0x03FF",
"&",
"a0",
";",
"this",
".",
"A1",
"=",
"0x03FF",
"&",
"a1",
";",
"type",
"=",
"DataType",
".",
"Data",
";",
"}",
"}",
"public",
"LogData",
"(",
"String",
"data",
")",
"{",
"StringTokenizer",
"st",
"=",
"new",
"StringTokenizer",
"(",
"data",
",",
"\"",
",",
"\"",
")",
";",
"String",
"stMicros",
"=",
"st",
".",
"nextToken",
"(",
")",
".",
"trim",
"(",
")",
";",
"String",
"stA0",
"=",
"st",
".",
"nextToken",
"(",
")",
".",
"trim",
"(",
")",
";",
"String",
"stA1",
"=",
"st",
".",
"nextToken",
"(",
")",
".",
"trim",
"(",
")",
";",
"String",
"stDate",
"=",
"st",
".",
"nextToken",
"(",
")",
".",
"trim",
"(",
")",
";",
"String",
"stDelta",
"=",
"st",
".",
"nextToken",
"(",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"stMicros",
".",
"startsWith",
"(",
"\"",
"-",
"\"",
")",
")",
"{",
"long",
"tmp",
"=",
"Long",
".",
"parseLong",
"(",
"stMicros",
",",
"16",
")",
";",
"long",
"tmp2",
"=",
"0x00FFFFFFFFL",
"&",
"tmp",
";",
"this",
".",
"micros",
"=",
"(",
"tmp",
"==",
"-",
"1",
")",
"?",
"tmp",
":",
"tmp2",
";",
"}",
"else",
"{",
"this",
".",
"micros",
"=",
"Long",
".",
"parseLong",
"(",
"stMicros",
",",
"16",
")",
";",
"}",
"this",
".",
"A0",
"=",
"Integer",
".",
"parseInt",
"(",
"stA0",
")",
";",
"this",
".",
"A1",
"=",
"Integer",
".",
"parseInt",
"(",
"stA1",
")",
";",
"this",
".",
"date",
"=",
"new",
"Date",
"(",
")",
";",
"this",
".",
"date",
".",
"setTime",
"(",
"Long",
".",
"parseLong",
"(",
"stDate",
")",
")",
";",
"this",
".",
"deltaMicros",
"=",
"Long",
".",
"parseLong",
"(",
"stDelta",
")",
";",
"type",
"=",
"DataType",
".",
"Data",
";",
"}",
"private",
"LogData",
"(",
"DataType",
"type",
")",
"{",
"this",
".",
"type",
"=",
"type",
";",
"}",
"public",
"void",
"overFlowMicros",
"(",
"int",
"i",
")",
"{",
"this",
".",
"micros",
"+=",
"i",
"*",
"0x0100000000L",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"if",
"(",
"this",
".",
"type",
"==",
"DataType",
".",
"Data",
")",
"{",
"return",
"\"",
"(",
"\"",
"+",
"Long",
".",
"toString",
"(",
"micros",
",",
"16",
")",
"+",
"\"",
", ",
"\"",
"+",
"A0",
"+",
"\"",
", ",
"\"",
"+",
"A1",
"+",
"\"",
", ",
"\"",
"+",
"date",
"+",
"\"",
", ",
"\"",
"+",
"deltaMicros",
"+",
"\"",
")",
"\"",
";",
"}",
"else",
"{",
"return",
"\"",
"Sync",
"\"",
";",
"}",
"}",
"public",
"String",
"toCsvString",
"(",
")",
"{",
"if",
"(",
"this",
".",
"type",
"==",
"DataType",
".",
"Data",
")",
"{",
"if",
"(",
"date",
"==",
"null",
")",
"{",
"return",
"Long",
".",
"toString",
"(",
"micros",
",",
"16",
")",
"+",
"\"",
", ",
"\"",
"+",
"A0",
"+",
"\"",
", ",
"\"",
"+",
"A1",
"+",
"\"",
", 0, 0",
"\"",
";",
"}",
"return",
"Long",
".",
"toString",
"(",
"micros",
",",
"16",
")",
"+",
"\"",
", ",
"\"",
"+",
"A0",
"+",
"\"",
", ",
"\"",
"+",
"A1",
"+",
"\"",
", ",
"\"",
"+",
"date",
".",
"getTime",
"(",
")",
"+",
"\"",
", ",
"\"",
"+",
"deltaMicros",
";",
"}",
"return",
"\"",
"\"",
";",
"}",
"public",
"byte",
"[",
"]",
"getRawData",
"(",
")",
"{",
"return",
"rawData",
";",
"}",
"public",
"long",
"getMicros",
"(",
")",
"{",
"return",
"micros",
";",
"}",
"public",
"int",
"getA0",
"(",
")",
"{",
"return",
"A0",
";",
"}",
"public",
"int",
"getA1",
"(",
")",
"{",
"return",
"A1",
";",
"}",
"public",
"DataType",
"getType",
"(",
")",
"{",
"return",
"type",
";",
"}",
"public",
"static",
"LogData",
"syncData",
"(",
")",
"{",
"return",
"new",
"LogData",
"(",
"DataType",
".",
"Sync",
")",
";",
"}",
"public",
"void",
"fillDate",
"(",
"Date",
"currDate",
")",
"{",
"if",
"(",
"date",
"==",
"null",
")",
"date",
"=",
"currDate",
";",
"}",
"public",
"void",
"fillDeltaMicros",
"(",
"long",
"delta",
")",
"{",
"if",
"(",
"deltaMicros",
"==",
"-",
"1",
")",
"deltaMicros",
"=",
"delta",
";",
"}",
"}"
] | Created by daniel on 11/6/17. | [
"Created",
"by",
"daniel",
"on",
"11",
"/",
"6",
"/",
"17",
"."
] | [
"// this.micros+=i*0x00FFFFFFFFL;",
"//if(type==DataType.Sync)"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fec73bb80543fd0011ffac199d6b9978949a0a67 | aperkaz/mini-java-syntax-tree | test programs/pass/DoWhile.java | [
"MIT"
] | Java | Test | // This do while statement | This do while statement | [
"This",
"do",
"while",
"statement"
] | class Test{
int foo;
int Loop(){
int aux01 ;
do {
aux01 = 10;
}while(true);
return 0 ;
}
} | [
"class",
"Test",
"{",
"int",
"foo",
";",
"int",
"Loop",
"(",
")",
"{",
"int",
"aux01",
";",
"do",
"{",
"aux01",
"=",
"10",
";",
"}",
"while",
"(",
"true",
")",
";",
"return",
"0",
";",
"}",
"}"
] | This do while statement | [
"This",
"do",
"while",
"statement"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fec779c61a7aa58f1ff0c0fa5336680e43542d30 | 1694672/MyGitHub | app/src/main/java/com/github/mobile/ui/search/SearchActivity.java | [
"Apache-2.0"
] | Java | SearchActivity | /**
* Activity to view search results
*/ | Activity to view search results | [
"Activity",
"to",
"view",
"search",
"results"
] | public class SearchActivity extends TabPagerActivity<SearchPagerAdapter> {
private SearchRepositoryListFragment repoFragment;
private SearchUserListFragment userFragment;
private SearchView searchView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
configurePager();
searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setIconifiedByDefault(false);
searchView.setIconified(false);
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchActivity.class)));
// Hide the magnifying glass icon
searchView.findViewById(android.support.v7.appcompat.R.id.search_mag_icon).setLayoutParams(new LinearLayout.LayoutParams(0, 0));
// Add the SearchView to the toolbar
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(searchView, layoutParams);
handleIntent(getIntent());
}
@Override
public boolean onCreateOptionsMenu(Menu options) {
getMenuInflater().inflate(R.menu.search, options);
return super.onCreateOptionsMenu(options);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.m_clear:
RepositorySearchSuggestionsProvider.clear(this);
ToastUtils.show(this, R.string.search_history_cleared);
return true;
case android.R.id.home:
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected SearchPagerAdapter createAdapter() {
return new SearchPagerAdapter(this);
}
@Override
protected String getIcon(int position) {
switch (position) {
case 0:
return TypefaceUtils.ICON_REPO;
case 1:
return TypefaceUtils.ICON_PERSON;
default:
return super.getIcon(position);
}
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(QUERY);
// Update the SearchView's query
searchView.setQuery(query, false);
// Prevents the suggestions dropdown from showing after we submit
searchView.post(new Runnable() {
@Override public void run() {
searchView.clearFocus();
}
});
search(query);
}
}
private void search(final String query) {
RepositorySearchSuggestionsProvider.save(this, query);
findFragments();
if (repoFragment != null && userFragment != null) {
repoFragment.setListShown(false);
userFragment.setListShown(false);
repoFragment.refreshWithProgress();
userFragment.refreshWithProgress();
}
}
private void configurePager() {
configureTabPager();
}
private void findFragments() {
if (repoFragment == null || userFragment == null) {
FragmentManager fm = getSupportFragmentManager();
repoFragment = (SearchRepositoryListFragment) fm.findFragmentByTag(
"android:switcher:" + pager.getId() + ":" + 0);
userFragment = (SearchUserListFragment) fm.findFragmentByTag(
"android:switcher:" + pager.getId() + ":" + 1);
}
}
} | [
"public",
"class",
"SearchActivity",
"extends",
"TabPagerActivity",
"<",
"SearchPagerAdapter",
">",
"{",
"private",
"SearchRepositoryListFragment",
"repoFragment",
";",
"private",
"SearchUserListFragment",
"userFragment",
";",
"private",
"SearchView",
"searchView",
";",
"@",
"Override",
"protected",
"void",
"onCreate",
"(",
"Bundle",
"savedInstanceState",
")",
"{",
"super",
".",
"onCreate",
"(",
"savedInstanceState",
")",
";",
"ActionBar",
"actionBar",
"=",
"getSupportActionBar",
"(",
")",
";",
"actionBar",
".",
"setDisplayHomeAsUpEnabled",
"(",
"true",
")",
";",
"configurePager",
"(",
")",
";",
"searchView",
"=",
"new",
"SearchView",
"(",
"getSupportActionBar",
"(",
")",
".",
"getThemedContext",
"(",
")",
")",
";",
"searchView",
".",
"setIconifiedByDefault",
"(",
"false",
")",
";",
"searchView",
".",
"setIconified",
"(",
"false",
")",
";",
"SearchManager",
"searchManager",
"=",
"(",
"SearchManager",
")",
"getSystemService",
"(",
"SEARCH_SERVICE",
")",
";",
"searchView",
".",
"setSearchableInfo",
"(",
"searchManager",
".",
"getSearchableInfo",
"(",
"new",
"ComponentName",
"(",
"this",
",",
"SearchActivity",
".",
"class",
")",
")",
")",
";",
"searchView",
".",
"findViewById",
"(",
"android",
".",
"support",
".",
"v7",
".",
"appcompat",
".",
"R",
".",
"id",
".",
"search_mag_icon",
")",
".",
"setLayoutParams",
"(",
"new",
"LinearLayout",
".",
"LayoutParams",
"(",
"0",
",",
"0",
")",
")",
";",
"ActionBar",
".",
"LayoutParams",
"layoutParams",
"=",
"new",
"ActionBar",
".",
"LayoutParams",
"(",
"ActionBar",
".",
"LayoutParams",
".",
"MATCH_PARENT",
",",
"ActionBar",
".",
"LayoutParams",
".",
"MATCH_PARENT",
")",
";",
"getSupportActionBar",
"(",
")",
".",
"setDisplayShowCustomEnabled",
"(",
"true",
")",
";",
"getSupportActionBar",
"(",
")",
".",
"setCustomView",
"(",
"searchView",
",",
"layoutParams",
")",
";",
"handleIntent",
"(",
"getIntent",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"onCreateOptionsMenu",
"(",
"Menu",
"options",
")",
"{",
"getMenuInflater",
"(",
")",
".",
"inflate",
"(",
"R",
".",
"menu",
".",
"search",
",",
"options",
")",
";",
"return",
"super",
".",
"onCreateOptionsMenu",
"(",
"options",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"onOptionsItemSelected",
"(",
"MenuItem",
"item",
")",
"{",
"switch",
"(",
"item",
".",
"getItemId",
"(",
")",
")",
"{",
"case",
"R",
".",
"id",
".",
"m_clear",
":",
"RepositorySearchSuggestionsProvider",
".",
"clear",
"(",
"this",
")",
";",
"ToastUtils",
".",
"show",
"(",
"this",
",",
"R",
".",
"string",
".",
"search_history_cleared",
")",
";",
"return",
"true",
";",
"case",
"android",
".",
"R",
".",
"id",
".",
"home",
":",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"this",
",",
"HomeActivity",
".",
"class",
")",
";",
"intent",
".",
"addFlags",
"(",
"FLAG_ACTIVITY_CLEAR_TOP",
"|",
"FLAG_ACTIVITY_SINGLE_TOP",
")",
";",
"startActivity",
"(",
"intent",
")",
";",
"return",
"true",
";",
"default",
":",
"return",
"super",
".",
"onOptionsItemSelected",
"(",
"item",
")",
";",
"}",
"}",
"@",
"Override",
"protected",
"SearchPagerAdapter",
"createAdapter",
"(",
")",
"{",
"return",
"new",
"SearchPagerAdapter",
"(",
"this",
")",
";",
"}",
"@",
"Override",
"protected",
"String",
"getIcon",
"(",
"int",
"position",
")",
"{",
"switch",
"(",
"position",
")",
"{",
"case",
"0",
":",
"return",
"TypefaceUtils",
".",
"ICON_REPO",
";",
"case",
"1",
":",
"return",
"TypefaceUtils",
".",
"ICON_PERSON",
";",
"default",
":",
"return",
"super",
".",
"getIcon",
"(",
"position",
")",
";",
"}",
"}",
"@",
"Override",
"protected",
"void",
"onNewIntent",
"(",
"Intent",
"intent",
")",
"{",
"setIntent",
"(",
"intent",
")",
";",
"handleIntent",
"(",
"intent",
")",
";",
"}",
"private",
"void",
"handleIntent",
"(",
"Intent",
"intent",
")",
"{",
"if",
"(",
"ACTION_SEARCH",
".",
"equals",
"(",
"intent",
".",
"getAction",
"(",
")",
")",
")",
"{",
"String",
"query",
"=",
"intent",
".",
"getStringExtra",
"(",
"QUERY",
")",
";",
"searchView",
".",
"setQuery",
"(",
"query",
",",
"false",
")",
";",
"searchView",
".",
"post",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"searchView",
".",
"clearFocus",
"(",
")",
";",
"}",
"}",
")",
";",
"search",
"(",
"query",
")",
";",
"}",
"}",
"private",
"void",
"search",
"(",
"final",
"String",
"query",
")",
"{",
"RepositorySearchSuggestionsProvider",
".",
"save",
"(",
"this",
",",
"query",
")",
";",
"findFragments",
"(",
")",
";",
"if",
"(",
"repoFragment",
"!=",
"null",
"&&",
"userFragment",
"!=",
"null",
")",
"{",
"repoFragment",
".",
"setListShown",
"(",
"false",
")",
";",
"userFragment",
".",
"setListShown",
"(",
"false",
")",
";",
"repoFragment",
".",
"refreshWithProgress",
"(",
")",
";",
"userFragment",
".",
"refreshWithProgress",
"(",
")",
";",
"}",
"}",
"private",
"void",
"configurePager",
"(",
")",
"{",
"configureTabPager",
"(",
")",
";",
"}",
"private",
"void",
"findFragments",
"(",
")",
"{",
"if",
"(",
"repoFragment",
"==",
"null",
"||",
"userFragment",
"==",
"null",
")",
"{",
"FragmentManager",
"fm",
"=",
"getSupportFragmentManager",
"(",
")",
";",
"repoFragment",
"=",
"(",
"SearchRepositoryListFragment",
")",
"fm",
".",
"findFragmentByTag",
"(",
"\"",
"android:switcher:",
"\"",
"+",
"pager",
".",
"getId",
"(",
")",
"+",
"\"",
":",
"\"",
"+",
"0",
")",
";",
"userFragment",
"=",
"(",
"SearchUserListFragment",
")",
"fm",
".",
"findFragmentByTag",
"(",
"\"",
"android:switcher:",
"\"",
"+",
"pager",
".",
"getId",
"(",
")",
"+",
"\"",
":",
"\"",
"+",
"1",
")",
";",
"}",
"}",
"}"
] | Activity to view search results | [
"Activity",
"to",
"view",
"search",
"results"
] | [
"// Hide the magnifying glass icon",
"// Add the SearchView to the toolbar",
"// Update the SearchView's query",
"// Prevents the suggestions dropdown from showing after we submit"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fecc920cf3111eecb9deb6ffa43b44026d0ac7f6 | onnoA/sample-collection | shop-common/src/main/java/com/onnoa/shop/common/hive/HiveJDBC.java | [
"Apache-2.0"
] | Java | HiveJDBC | /**
* @className: HiveJDBC
* @description:
* @author: onnoA
* @date: 2021/9/17
**/ | @className: HiveJDBC
@description:
@author: onnoA
@date: 2021/9/17 | [
"@className",
":",
"HiveJDBC",
"@description",
":",
"@author",
":",
"onnoA",
"@date",
":",
"2021",
"/",
"9",
"/",
"17"
] | public class HiveJDBC {
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
private static String url = "jdbc:hive2://172.16.198.22:10000/hive";
private static String user = "hive";
private static String password = "hive";
private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;
// 加载驱动、创建连接
@Before
public void init() throws Exception {
Class.forName(driverName);
conn = DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName(driverName);
conn = DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
String sql = "show databases";
System.out.println("Running: " + sql);
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
// 创建数据库
@Test
public void createDatabase() throws Exception {
String sql = "create database hive_jdbc_test";
System.out.println("Running: " + sql);
stmt.execute(sql);
}
// 查询所有数据库
@Test
public void showDatabases() throws Exception {
String sql = "show databases";
System.out.println("Running: " + sql);
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
// 创建表
@Test
public void createTable() throws Exception {
String sql = "create table emp(\n" +
"empno int,\n" +
"ename string,\n" +
"job string,\n" +
"mgr int,\n" +
"hiredate string,\n" +
"sal double,\n" +
"comm double,\n" +
"deptno int\n" +
")\n" +
"row format delimited fields terminated by '\\t'";
System.out.println("Running: " + sql);
stmt.execute(sql);
}
// 查询所有表
@Test
public void showTables() throws Exception {
String sql = "show tables";
System.out.println("Running: " + sql);
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
// 查看表结构
@Test
public void descTable() throws Exception {
String sql = "desc emp";
System.out.println("Running: " + sql);
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2));
}
}
// 加载数据
@Test
public void loadData() throws Exception {
String filePath = "/home/hadoop/data/emp.txt";
String sql = "load data local inpath '" + filePath + "' overwrite into table emp";
System.out.println("Running: " + sql);
stmt.execute(sql);
}
// 查询数据
@Test
public void selectData() throws Exception {
String sql = "select * from emp";
System.out.println("Running: " + sql);
rs = stmt.executeQuery(sql);
System.out.println("员工编号" + "\t" + "员工姓名" + "\t" + "工作岗位");
while (rs.next()) {
System.out.println(rs.getString("empno") + "\t\t" + rs.getString("ename") + "\t\t" + rs.getString("job"));
}
}
// 统计查询(会运行mapreduce作业)
@Test
public void countData() throws Exception {
String sql = "select count(1) from emp";
System.out.println("Running: " + sql);
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getInt(1) );
}
}
// 删除数据库
@Test
public void dropDatabase() throws Exception {
String sql = "drop database if exists hive_jdbc_test";
System.out.println("Running: " + sql);
stmt.execute(sql);
}
// 删除数据库表
@Test
public void deopTable() throws Exception {
String sql = "drop table if exists emp";
System.out.println("Running: " + sql);
stmt.execute(sql);
}
// 释放资源
@After
public void destory() throws Exception {
if ( rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
} | [
"public",
"class",
"HiveJDBC",
"{",
"private",
"static",
"String",
"driverName",
"=",
"\"",
"org.apache.hive.jdbc.HiveDriver",
"\"",
";",
"private",
"static",
"String",
"url",
"=",
"\"",
"jdbc:hive2://172.16.198.22:10000/hive",
"\"",
";",
"private",
"static",
"String",
"user",
"=",
"\"",
"hive",
"\"",
";",
"private",
"static",
"String",
"password",
"=",
"\"",
"hive",
"\"",
";",
"private",
"static",
"Connection",
"conn",
"=",
"null",
";",
"private",
"static",
"Statement",
"stmt",
"=",
"null",
";",
"private",
"static",
"ResultSet",
"rs",
"=",
"null",
";",
"@",
"Before",
"public",
"void",
"init",
"(",
")",
"throws",
"Exception",
"{",
"Class",
".",
"forName",
"(",
"driverName",
")",
";",
"conn",
"=",
"DriverManager",
".",
"getConnection",
"(",
"url",
",",
"user",
",",
"password",
")",
";",
"stmt",
"=",
"conn",
".",
"createStatement",
"(",
")",
";",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"SQLException",
",",
"ClassNotFoundException",
"{",
"Class",
".",
"forName",
"(",
"driverName",
")",
";",
"conn",
"=",
"DriverManager",
".",
"getConnection",
"(",
"url",
",",
"user",
",",
"password",
")",
";",
"stmt",
"=",
"conn",
".",
"createStatement",
"(",
")",
";",
"String",
"sql",
"=",
"\"",
"show databases",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"sql",
")",
";",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"rs",
".",
"getString",
"(",
"1",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"createDatabase",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"create database hive_jdbc_test",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"stmt",
".",
"execute",
"(",
"sql",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"showDatabases",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"show databases",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"sql",
")",
";",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"rs",
".",
"getString",
"(",
"1",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"createTable",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"create table emp(",
"\\n",
"\"",
"+",
"\"",
"empno int,",
"\\n",
"\"",
"+",
"\"",
"ename string,",
"\\n",
"\"",
"+",
"\"",
"job string,",
"\\n",
"\"",
"+",
"\"",
"mgr int,",
"\\n",
"\"",
"+",
"\"",
"hiredate string,",
"\\n",
"\"",
"+",
"\"",
"sal double,",
"\\n",
"\"",
"+",
"\"",
"comm double,",
"\\n",
"\"",
"+",
"\"",
"deptno int",
"\\n",
"\"",
"+",
"\"",
")",
"\\n",
"\"",
"+",
"\"",
"row format delimited fields terminated by '",
"\\\\",
"t'",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"stmt",
".",
"execute",
"(",
"sql",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"showTables",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"show tables",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"sql",
")",
";",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"rs",
".",
"getString",
"(",
"1",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"descTable",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"desc emp",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"sql",
")",
";",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"rs",
".",
"getString",
"(",
"1",
")",
"+",
"\"",
"\\t",
"\"",
"+",
"rs",
".",
"getString",
"(",
"2",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"loadData",
"(",
")",
"throws",
"Exception",
"{",
"String",
"filePath",
"=",
"\"",
"/home/hadoop/data/emp.txt",
"\"",
";",
"String",
"sql",
"=",
"\"",
"load data local inpath '",
"\"",
"+",
"filePath",
"+",
"\"",
"' overwrite into table emp",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"stmt",
".",
"execute",
"(",
"sql",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"selectData",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"select * from emp",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"sql",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"员工编号\" + \"\\t\"",
" ",
" ",
"员",
"工姓",
"名",
" ",
" ",
"\"\\t\" + \"工作岗位",
"\"",
";",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"rs",
".",
"getString",
"(",
"\"",
"empno",
"\"",
")",
"+",
"\"",
"\\t",
"\\t",
"\"",
"+",
"rs",
".",
"getString",
"(",
"\"",
"ename",
"\"",
")",
"+",
"\"",
"\\t",
"\\t",
"\"",
"+",
"rs",
".",
"getString",
"(",
"\"",
"job",
"\"",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"countData",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"select count(1) from emp",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"rs",
"=",
"stmt",
".",
"executeQuery",
"(",
"sql",
")",
";",
"while",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"rs",
".",
"getInt",
"(",
"1",
")",
")",
";",
"}",
"}",
"@",
"Test",
"public",
"void",
"dropDatabase",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"drop database if exists hive_jdbc_test",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"stmt",
".",
"execute",
"(",
"sql",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"deopTable",
"(",
")",
"throws",
"Exception",
"{",
"String",
"sql",
"=",
"\"",
"drop table if exists emp",
"\"",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Running: ",
"\"",
"+",
"sql",
")",
";",
"stmt",
".",
"execute",
"(",
"sql",
")",
";",
"}",
"@",
"After",
"public",
"void",
"destory",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"rs",
"!=",
"null",
")",
"{",
"rs",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"stmt",
"!=",
"null",
")",
"{",
"stmt",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"conn",
"!=",
"null",
")",
"{",
"conn",
".",
"close",
"(",
")",
";",
"}",
"}",
"}"
] | @className: HiveJDBC
@description:
@author: onnoA
@date: 2021/9/17 | [
"@className",
":",
"HiveJDBC",
"@description",
":",
"@author",
":",
"onnoA",
"@date",
":",
"2021",
"/",
"9",
"/",
"17"
] | [
"// 加载驱动、创建连接",
"// 创建数据库",
"// 查询所有数据库",
"// 创建表",
"// 查询所有表",
"// 查看表结构",
"// 加载数据",
"// 查询数据",
"// 统计查询(会运行mapreduce作业)",
"// 删除数据库",
"// 删除数据库表",
"// 释放资源"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fecdf509a47f57f53bf5497b25f407a85e6fc015 | mirko-felice/DroneSecurity | user-application/src/main/java/io/github/dronesecurity/userapplication/events/StableSituation.java | [
"MIT"
] | Java | StableSituation | /**
* The event to be raised when alert is no more occurring and standard situation comes back.
*/ | The event to be raised when alert is no more occurring and standard situation comes back. | [
"The",
"event",
"to",
"be",
"raised",
"when",
"alert",
"is",
"no",
"more",
"occurring",
"and",
"standard",
"situation",
"comes",
"back",
"."
] | public class StableSituation implements Event {
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return SituationConstants.STABLE;
}
} | [
"public",
"class",
"StableSituation",
"implements",
"Event",
"{",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"SituationConstants",
".",
"STABLE",
";",
"}",
"}"
] | The event to be raised when alert is no more occurring and standard situation comes back. | [
"The",
"event",
"to",
"be",
"raised",
"when",
"alert",
"is",
"no",
"more",
"occurring",
"and",
"standard",
"situation",
"comes",
"back",
"."
] | [] | [
{
"param": "Event",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Event",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fed9a848e93bed40fad67e82b24e657d36134ead | ilbinek/java-runtime-decompiler | runtime-decompiler/src/main/java/org/jrd/frontend/utility/TeeOutputStream.java | [
"BSD-3-Clause"
] | Java | TeeOutputStream | /**
* Behaves like the 'tee' command, sends output to both actual std stream and a
* log
*/ | Behaves like the 'tee' command, sends output to both actual std stream and a
log | [
"Behaves",
"like",
"the",
"'",
"tee",
"'",
"command",
"sends",
"output",
"to",
"both",
"actual",
"std",
"stream",
"and",
"a",
"log"
] | public final class TeeOutputStream extends PrintStream {
// Everything written to TeeOutputStream is written to this buffer too
private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
public TeeOutputStream(PrintStream stdStream) {
super(stdStream, false, StandardCharsets.UTF_8);
}
/*
* The big ones: these do the actual writing
*/
@Override
public synchronized void write(byte[] b, int off, int len) {
if (len == 0) {
return;
}
byteArrayOutputStream.write(b, off, len);
super.write(b, off, len);
}
@Override
public synchronized void write(int b) {
byteArrayOutputStream.write(b);
super.write(b);
}
public byte[] getByteArray() {
return byteArrayOutputStream.toByteArray();
}
} | [
"public",
"final",
"class",
"TeeOutputStream",
"extends",
"PrintStream",
"{",
"private",
"final",
"ByteArrayOutputStream",
"byteArrayOutputStream",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"public",
"TeeOutputStream",
"(",
"PrintStream",
"stdStream",
")",
"{",
"super",
"(",
"stdStream",
",",
"false",
",",
"StandardCharsets",
".",
"UTF_8",
")",
";",
"}",
"/*\n * The big ones: these do the actual writing\n */",
"@",
"Override",
"public",
"synchronized",
"void",
"write",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"{",
"if",
"(",
"len",
"==",
"0",
")",
"{",
"return",
";",
"}",
"byteArrayOutputStream",
".",
"write",
"(",
"b",
",",
"off",
",",
"len",
")",
";",
"super",
".",
"write",
"(",
"b",
",",
"off",
",",
"len",
")",
";",
"}",
"@",
"Override",
"public",
"synchronized",
"void",
"write",
"(",
"int",
"b",
")",
"{",
"byteArrayOutputStream",
".",
"write",
"(",
"b",
")",
";",
"super",
".",
"write",
"(",
"b",
")",
";",
"}",
"public",
"byte",
"[",
"]",
"getByteArray",
"(",
")",
"{",
"return",
"byteArrayOutputStream",
".",
"toByteArray",
"(",
")",
";",
"}",
"}"
] | Behaves like the 'tee' command, sends output to both actual std stream and a
log | [
"Behaves",
"like",
"the",
"'",
"tee",
"'",
"command",
"sends",
"output",
"to",
"both",
"actual",
"std",
"stream",
"and",
"a",
"log"
] | [
"// Everything written to TeeOutputStream is written to this buffer too"
] | [
{
"param": "PrintStream",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "PrintStream",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fedd9d151f142f0578ac5efc1649d1a4bffedfc7 | mapr-demos/mapr-db-fast-fail-over | core/src/main/java/com.mapr.db/EnhancedJSONTable.java | [
"Apache-2.0"
] | Java | EnhancedJSONTable | /**
* EnhancedJSONTable represents a wrapper above {@link DocumentStore} providing a fail-over
* strategy that should provide user a high availability of cluster.
* For update operations failover is not supported because of consistency problems especially with increment operations.
*/ | EnhancedJSONTable represents a wrapper above DocumentStore providing a fail-over
strategy that should provide user a high availability of cluster.
For update operations failover is not supported because of consistency problems especially with increment operations. | [
"EnhancedJSONTable",
"represents",
"a",
"wrapper",
"above",
"DocumentStore",
"providing",
"a",
"fail",
"-",
"over",
"strategy",
"that",
"should",
"provide",
"user",
"a",
"high",
"availability",
"of",
"cluster",
".",
"For",
"update",
"operations",
"failover",
"is",
"not",
"supported",
"because",
"of",
"consistency",
"problems",
"especially",
"with",
"increment",
"operations",
"."
] | public class EnhancedJSONTable implements DocumentStore {
private static final Logger LOG = LoggerFactory.getLogger(EnhancedJSONTable.class);
private static final String DB_DRIVER_NAME = "ojai:mapr:";
/**
* Variable that indicates that request is safe for failover
*/
private static final boolean SAFE = true;
private long timeOut; // How long to wait before starting secondary query
private long secondaryTimeOut; // How long to wait before giving up on a good result
private DocumentStore[] stores; // the tables we talk to. Primary is first, then secondary
private AtomicInteger current = // the index for stores
new AtomicInteger(0);
private AtomicBoolean switched =
new AtomicBoolean(false); // Indicates if the table switched in that moment
private String[] tableNames; // the names of the tables
/**
* Executor for working with primary store
*/
private ExecutorService primaryExecutor = Executors.newSingleThreadExecutor();
/**
* Executor for working with failover store
*/
private ExecutorService secondaryExecutor = Executors.newSingleThreadExecutor();
/**
* Variable for determining time that needed for switching table
*/
private AtomicInteger counterForTableSwitching = new AtomicInteger(0);
/**
* Service that schedules failback operations
*/
private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
/**
* Do we need use failover for medium dangerous operations with db.
* If true than we perform failover for this operations.
*/
private boolean mediumDangerous = false;
/**
* Do we need use failover for non idempotent operations with db
* If true than we perform failover for this operations.
*/
private boolean veryDangerous = false;
/**
* Create a new JSON store that with a primary table and secondary table. The application will automatically switch
* to the secondary table if the operation on primary is not successful in less than 500ms.
*
* @param primaryTable the primary table used by the application
* @param secondaryTable the table used in case of fail over
* @param medium the flag that needed for determining what to do with medium dangerous operations, by default false
* @param hard the flag that needed for determining what to do with non idempotent operations, by default false
*/
public EnhancedJSONTable(String primaryTable, String secondaryTable, long timeOut, boolean medium, boolean hard) {
this(primaryTable, secondaryTable, timeOut);
this.mediumDangerous = medium;
this.veryDangerous = hard;
}
/**
* Create a new JSON store that with a primary table and secondary table. The application will automatically switch
* to the secondary table if the operation on primary is not successful in less than 500ms.
*
* @param primaryTable the primary table used by the application
* @param secondaryTable the table used in case of fail over
*/
public EnhancedJSONTable(String primaryTable, String secondaryTable) {
this(primaryTable, secondaryTable, 700);
}
/**
* Create a new JSON store that with a primary table and secondary table. The application will automatically switch
* to the secondary table if the operation on primary is successful in the <code>timeout</code>
*
* @param primaryTable the primary table used by the application
* @param secondaryTable the table used in case of fail over
* @param timeOut the time out on primary table before switching to secondary.
*/
public EnhancedJSONTable(String primaryTable, String secondaryTable, long timeOut) {
this.tableNames = new String[]{primaryTable, secondaryTable};
this.timeOut = timeOut;
this.secondaryTimeOut = 15 * timeOut;
DocumentStore primary = getDocumentStore(primaryTable);
DocumentStore secondary = getDocumentStore(secondaryTable);
this.stores = new DocumentStore[]{primary, secondary};
}
public boolean isMediumDangerous() {
return mediumDangerous;
}
public void setMediumDangerous(boolean mediumDangerous) {
this.mediumDangerous = mediumDangerous;
}
public boolean isVeryDangerous() {
return veryDangerous;
}
public void setVeryDangerous(boolean veryDangerous) {
this.veryDangerous = veryDangerous;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isReadOnly() {
return checkAndDoWithFailover(DocumentStore::isReadOnly, SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void flush() throws StoreException {
doNoReturn(DocumentStore::flush, SAFE); // TODO verify that this method reference does what is expected
}
/**
* {@inheritDoc}
*/
@Override
public void beginTrackingWrites() throws StoreException {
doNoReturn(DocumentStore::beginTrackingWrites, veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void beginTrackingWrites(@NonNullable String previousWritesContext) throws StoreException {
doNoReturn((DocumentStore t) -> t.beginTrackingWrites(previousWritesContext), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public String endTrackingWrites() throws StoreException {
return checkAndDoWithFailover(DocumentStore::endTrackingWrites, veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void clearTrackedWrites() throws StoreException {
doNoReturn(DocumentStore::clearTrackedWrites, veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(String _id) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(_id), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(Value _id) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(_id), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(String _id, String... fieldPaths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(_id, fieldPaths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(String _id, FieldPath... fieldPaths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(_id, fieldPaths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(Value _id, String... fieldPaths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(_id, fieldPaths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(Value value, FieldPath... fieldPaths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(value, fieldPaths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(String s, QueryCondition queryCondition) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(s, queryCondition), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(Value value, QueryCondition queryCondition) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(value, queryCondition), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(String s, QueryCondition queryCondition, String... strings) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(s, queryCondition, strings), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(String s, QueryCondition queryCondition, FieldPath... fieldPaths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(s, queryCondition, fieldPaths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(Value value, QueryCondition queryCondition, String... strings) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(value, queryCondition, strings), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public Document findById(Value value, QueryCondition queryCondition, FieldPath... fieldPaths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.findById(value, queryCondition, fieldPaths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public DocumentStream find() throws StoreException {
return checkAndDoWithFailover(DocumentStore::find, SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public DocumentStream find(@NonNullable String... paths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.find(paths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public DocumentStream find(@NonNullable FieldPath... paths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.find(paths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public DocumentStream find(@NonNullable QueryCondition c) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.find(c), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public DocumentStream find(@NonNullable QueryCondition c, @NonNullable String... paths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.find(c, paths), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public DocumentStream find(@NonNullable QueryCondition c, @NonNullable FieldPath... paths) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.find(c, paths), SAFE);
}
/**
* {@inheritDoc}
*
* @return DocumentStream that wrapped by DocumentStreamFailoverWrapper for catching {@code StoreException}
* and rethrowing {@code EnhancedJSONTable.FailoverException}
*/
@Override
public DocumentStream findQuery(@NonNullable Query query) throws StoreException {
return new DocumentStreamFailoverWrapper(checkAndDoWithFailover((DocumentStore t) -> t.findQuery(query), SAFE));
}
/**
* {@inheritDoc}
*
* @return DocumentStream that wrapped by DocumentStreamFailoverWrapper for catching {@code StoreException}
* and rethrowing {@code EnhancedJSONTable.FailoverException}
*/
@Override
public DocumentStream findQuery(@NonNullable String query) throws StoreException {
return new DocumentStreamFailoverWrapper(checkAndDoWithFailover((DocumentStore t) -> t.findQuery(query), SAFE));
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.insertOrReplace(doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable Value _id, @NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.insertOrReplace(_id, doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable Document doc, @NonNullable FieldPath fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.insertOrReplace(doc, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable Document doc, @NonNullable String fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.insertOrReplace(doc, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable DocumentStream stream) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.insertOrReplace(stream), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable DocumentStream stream, @NonNullable FieldPath fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.insertOrReplace(stream, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable DocumentStream stream, @NonNullable String fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.insertOrReplace(stream, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insertOrReplace(@NonNullable String _id, @NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.insert(_id, doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable String _id, @NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.insert(_id, doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void update(@NonNullable Value _id, @NonNullable DocumentMutation m) throws StoreException {
doNoReturn((DocumentStore t) -> t.update(_id, m), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void update(@NonNullable String _id, @NonNullable DocumentMutation mutation) throws StoreException {
doNoReturn((DocumentStore t) -> t.update(_id, mutation), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable String _id) throws StoreException {
doNoReturn((DocumentStore t) -> t.delete(_id), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable Value _id) throws StoreException {
doNoReturn((DocumentStore t) -> t.delete(_id), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.delete(doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable Document doc, @NonNullable FieldPath fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.delete(doc, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable Document doc, @NonNullable String fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.delete(doc, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable DocumentStream stream) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.delete(stream), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable DocumentStream stream, @NonNullable FieldPath fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.delete(stream, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(@NonNullable DocumentStream stream, @NonNullable String fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.delete(stream, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable Value _id, @NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.insert(_id, doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.insert(doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable Document doc, @NonNullable FieldPath fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.insert(doc), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable Document doc, @NonNullable String fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.insert(doc, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable DocumentStream stream) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.insert(stream), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable DocumentStream stream, @NonNullable FieldPath fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.insert(stream, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void insert(@NonNullable DocumentStream stream, @NonNullable String fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.insert(stream, fieldAsKey), SAFE);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable String _id, @NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.replace(_id, doc), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable Value _id, @NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.replace(_id, doc), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable Document doc) throws StoreException {
doNoReturn((DocumentStore t) -> t.replace(doc), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable Document doc, @NonNullable FieldPath fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.replace(doc, fieldAsKey), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable Document doc, @NonNullable String fieldAsKey) throws StoreException {
doNoReturn((DocumentStore t) -> t.replace(doc, fieldAsKey), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable DocumentStream stream) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.replace(stream), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable DocumentStream stream, @NonNullable FieldPath fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.replace(stream, fieldAsKey), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void replace(@NonNullable DocumentStream stream, @NonNullable String fieldAsKey) throws MultiOpException {
doNoReturn((DocumentStore t) -> t.replace(stream, fieldAsKey), mediumDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable String _id, @NonNullable String field, byte inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable String _id, @NonNullable String field, short inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable String _id, @NonNullable String field, int inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable String _id, @NonNullable String field, long inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable String _id, @NonNullable String field, float inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable String _id, @NonNullable String field, double inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable String _id, @NonNullable String field, @NonNullable BigDecimal inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable Value _id, @NonNullable String field, byte inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable Value _id, @NonNullable String field, short inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable Value _id, @NonNullable String field, int inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable Value _id, @NonNullable String field, long inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable Value _id, @NonNullable String field, float inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable Value _id, @NonNullable String field, double inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(@NonNullable Value _id, @NonNullable String field, @NonNullable BigDecimal inc) throws StoreException {
doNoReturn((DocumentStore t) -> t.increment(_id, field, inc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public boolean checkAndMutate(@NonNullable String _id, @NonNullable QueryCondition condition,
@NonNullable DocumentMutation mutation) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.checkAndMutate(_id, condition, mutation), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public boolean checkAndDelete(@NonNullable String _id, @NonNullable QueryCondition condition) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.checkAndDelete(_id, condition), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public boolean checkAndReplace(@NonNullable String _id, @NonNullable QueryCondition condition,
@NonNullable Document doc) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.checkAndReplace(_id, condition, doc), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public boolean checkAndMutate(@NonNullable Value _id, @NonNullable QueryCondition condition,
@NonNullable DocumentMutation m) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.checkAndMutate(_id, condition, m), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public boolean checkAndDelete(@NonNullable Value _id, @NonNullable QueryCondition condition) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.checkAndDelete(_id, condition), veryDangerous);
}
/**
* {@inheritDoc}
*/
@Override
public boolean checkAndReplace(@NonNullable Value _id, @NonNullable QueryCondition condition, @NonNullable Document doc) throws StoreException {
return checkAndDoWithFailover((DocumentStore t) -> t.checkAndReplace(_id, condition, doc), veryDangerous);
}
public boolean isTableSwitched() {
return switched.get();
}
private void doNoReturn(TableProcedure task, boolean withFailover) {
checkAndDoWithFailover((DocumentStore t) -> {
task.apply(t);
return null;
}, withFailover);
}
private <R> R checkAndDoWithFailover(TableFunction<R> task, boolean withFailover) {
int i = current.get();
DocumentStore primary = stores[i];
DocumentStore secondary = stores[1 - i];
if (withFailover) {
if (switched.get()) {
// change executor if table switched, in this case primary executor work only with primary cluster
// and secondary executor work only with failover table
return doWithFallback(secondaryExecutor, primaryExecutor, timeOut, secondaryTimeOut, task, primary, secondary,
this::swapTableLinks, switched);
} else {
return doWithFallback(primaryExecutor, secondaryExecutor, timeOut, secondaryTimeOut, task, primary, secondary,
this::swapTableLinks, switched);
}
} else {
return doWithoutFailover(task, primary);
}
}
/**
* Process request to db without Failover
*
* @param task A lambda with one argument, a table, that does the desired operation
* @param primary The primary table
* @param <R> The type that task will return
* @return The value returned by task
*/
private <R> R doWithoutFailover(TableFunction<R> task, DocumentStore primary) {
try {
return primaryExecutor.submit(() -> task.apply(primary)).get();
} catch (InterruptedException e) {
// this should never happen except perhaps in debugging or on shutdown
throw new FailoverException("Thread was interrupted during operation", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
// these are likely StoreException, but we don't differentiate
throw (RuntimeException) cause;
} else {
// this should not happen in our situation since none of the methods do this
throw new FailoverException("Checked exception thrown (shouldn't happen)", cause);
}
}
}
/**
* Tries to do task on primary until timeOut milliseconds have passed. From then
* the task is also attempted with secondary. If second succeeds, we use that result.
* If the primary blows the first timeout, then we initiate a failover by invoking
* failoverTask. When both primary and secondary throw exceptions, we rethrow the
* last exception received. When secondary exceed secondaryTimeOut
* milliseconds with no exceptions and no results, then an exception is thrown.
* <p>
* This method is static to make testing easier.
*
* @param prim The executor that does all the work
* @param timeOut How long to wait before invoking the secondary
* @param secondaryTimeOut How long to wait before entirely giving up
* @param task A lambda with one argument, a table, that does the desired operation
* @param primary The primary table
* @param secondary The secondary table
* @param failover The function to call when primary doesn't respond quickly
* @param switched The flag, that indicate that table switched or not
* @param <R> The type that task will return
* @return The value returned by task
* @throws StoreException If both primary and secondary fail
* @throws FailoverException If both primary and secondary fail. This may wrap a real exception
*/
static <R> R doWithFallback(ExecutorService prim, ExecutorService sec,
long timeOut, long secondaryTimeOut,
TableFunction<R> task,
DocumentStore primary, DocumentStore secondary,
Runnable failover, AtomicBoolean switched) {
Future<R> primaryFuture = prim.submit(() -> task.apply(primary));
try {
try {
// try on the primary table ... if we get a result, we win
return primaryFuture.get(timeOut, TimeUnit.MILLISECONDS);
} catch (TimeoutException | ExecutionException e) {
// We have lost confidence in the primary at this point even if we get a result
// We cancel request to the primary table, for fast change to the failover table
primaryFuture.cancel(true);
if (!switched.get()) {
failover.run();
}
// No result in time from primary so we now try on secondary.
// Exceptional returns when timeout expires.
return sec.submit(() -> task.apply(secondary)).get(secondaryTimeOut, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
// this should never happen except perhaps in debugging or on shutdown
throw new FailoverException("Thread was interrupted during operation", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
// these are likely StoreException, but we don't differentiate
throw (RuntimeException) cause;
} else {
// this should not happen in our situation since none of the methods do this
throw new FailoverException("Checked exception thrown (shouldn't happen)", cause);
}
} catch (TimeoutException e) {
throw new FailoverException("Operation timed out on primary and secondary tables", e);
}
}
/**
* Swap primary and secondary tables
* <p>
* When failing over to another table/cluster or when going back to origin/master cluster
* we do not change the whole logic, but simply switch the primary/secondary tables
*/
private void swapTableLinks() {
current.getAndUpdate(old -> 1 - old);
switched.compareAndSet(switched.get(), !switched.get());
LOG.info("Table switched: " + switched.get());
if (switched.get()) {
int stick = counterForTableSwitching.getAndIncrement();
LOG.info("Switch table for - {} ms", getTimeOut(stick));
swapTableBackAfter(getTimeOut(stick));
}
}
/**
* Create task for swapping table back after timeout
*
* @param timeout Time after what we swap table back
*/
private void swapTableBackAfter(long timeout) {
scheduler.schedule(
this::swapTableLinks, timeout, TimeUnit.MILLISECONDS);
}
/**
* Determines the amount of time that we need to stay on another table
* <p>
*
* @param numberOfSwitch Quantity of table switching
* @return time in milliseconds
*/
private long getTimeOut(int numberOfSwitch) {
long minute = 60000;
switch (numberOfSwitch) {
case 0:
return minute / 3;
case 1:
return minute;
default:
return 2 * minute;
}
}
/**
* Shutdown all executors, close connection to the tables.
* If you do not call this method, the application will freeze
*
* @throws StoreException If the underlying tables fail to close cleanly.
*/
@Override
public void close() throws StoreException {
scheduler.shutdownNow();
primaryExecutor.shutdownNow();
secondaryExecutor.shutdownNow();
try {
stores[0].close();
} finally {
stores[1].close();
}
}
/**
* Get DocumentStore from MapR-DB.
* Table must exist.
*
* @param tableName Name that correspond to db table name
* @return com.mapr.db.Table
*/
private DocumentStore getDocumentStore(String tableName) {
Connection connection = DriverManager.getConnection(DB_DRIVER_NAME);
return connection.getStore(tableName);
}
static class FailoverException extends StoreException {
FailoverException(String msg, Throwable cause) {
super(msg, cause);
}
}
public interface TableFunction<R> {
R apply(DocumentStore d) throws InterruptedException;
}
public interface TableProcedure {
void apply(DocumentStore t);
}
} | [
"public",
"class",
"EnhancedJSONTable",
"implements",
"DocumentStore",
"{",
"private",
"static",
"final",
"Logger",
"LOG",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"EnhancedJSONTable",
".",
"class",
")",
";",
"private",
"static",
"final",
"String",
"DB_DRIVER_NAME",
"=",
"\"",
"ojai:mapr:",
"\"",
";",
"/**\n * Variable that indicates that request is safe for failover\n */",
"private",
"static",
"final",
"boolean",
"SAFE",
"=",
"true",
";",
"private",
"long",
"timeOut",
";",
"private",
"long",
"secondaryTimeOut",
";",
"private",
"DocumentStore",
"[",
"]",
"stores",
";",
"private",
"AtomicInteger",
"current",
"=",
"new",
"AtomicInteger",
"(",
"0",
")",
";",
"private",
"AtomicBoolean",
"switched",
"=",
"new",
"AtomicBoolean",
"(",
"false",
")",
";",
"private",
"String",
"[",
"]",
"tableNames",
";",
"/**\n * Executor for working with primary store\n */",
"private",
"ExecutorService",
"primaryExecutor",
"=",
"Executors",
".",
"newSingleThreadExecutor",
"(",
")",
";",
"/**\n * Executor for working with failover store\n */",
"private",
"ExecutorService",
"secondaryExecutor",
"=",
"Executors",
".",
"newSingleThreadExecutor",
"(",
")",
";",
"/**\n * Variable for determining time that needed for switching table\n */",
"private",
"AtomicInteger",
"counterForTableSwitching",
"=",
"new",
"AtomicInteger",
"(",
"0",
")",
";",
"/**\n * Service that schedules failback operations\n */",
"private",
"ScheduledExecutorService",
"scheduler",
"=",
"Executors",
".",
"newScheduledThreadPool",
"(",
"1",
")",
";",
"/**\n * Do we need use failover for medium dangerous operations with db.\n * If true than we perform failover for this operations.\n */",
"private",
"boolean",
"mediumDangerous",
"=",
"false",
";",
"/**\n * Do we need use failover for non idempotent operations with db\n * If true than we perform failover for this operations.\n */",
"private",
"boolean",
"veryDangerous",
"=",
"false",
";",
"/**\n * Create a new JSON store that with a primary table and secondary table. The application will automatically switch\n * to the secondary table if the operation on primary is not successful in less than 500ms.\n *\n * @param primaryTable the primary table used by the application\n * @param secondaryTable the table used in case of fail over\n * @param medium the flag that needed for determining what to do with medium dangerous operations, by default false\n * @param hard the flag that needed for determining what to do with non idempotent operations, by default false\n */",
"public",
"EnhancedJSONTable",
"(",
"String",
"primaryTable",
",",
"String",
"secondaryTable",
",",
"long",
"timeOut",
",",
"boolean",
"medium",
",",
"boolean",
"hard",
")",
"{",
"this",
"(",
"primaryTable",
",",
"secondaryTable",
",",
"timeOut",
")",
";",
"this",
".",
"mediumDangerous",
"=",
"medium",
";",
"this",
".",
"veryDangerous",
"=",
"hard",
";",
"}",
"/**\n * Create a new JSON store that with a primary table and secondary table. The application will automatically switch\n * to the secondary table if the operation on primary is not successful in less than 500ms.\n *\n * @param primaryTable the primary table used by the application\n * @param secondaryTable the table used in case of fail over\n */",
"public",
"EnhancedJSONTable",
"(",
"String",
"primaryTable",
",",
"String",
"secondaryTable",
")",
"{",
"this",
"(",
"primaryTable",
",",
"secondaryTable",
",",
"700",
")",
";",
"}",
"/**\n * Create a new JSON store that with a primary table and secondary table. The application will automatically switch\n * to the secondary table if the operation on primary is successful in the <code>timeout</code>\n *\n * @param primaryTable the primary table used by the application\n * @param secondaryTable the table used in case of fail over\n * @param timeOut the time out on primary table before switching to secondary.\n */",
"public",
"EnhancedJSONTable",
"(",
"String",
"primaryTable",
",",
"String",
"secondaryTable",
",",
"long",
"timeOut",
")",
"{",
"this",
".",
"tableNames",
"=",
"new",
"String",
"[",
"]",
"{",
"primaryTable",
",",
"secondaryTable",
"}",
";",
"this",
".",
"timeOut",
"=",
"timeOut",
";",
"this",
".",
"secondaryTimeOut",
"=",
"15",
"*",
"timeOut",
";",
"DocumentStore",
"primary",
"=",
"getDocumentStore",
"(",
"primaryTable",
")",
";",
"DocumentStore",
"secondary",
"=",
"getDocumentStore",
"(",
"secondaryTable",
")",
";",
"this",
".",
"stores",
"=",
"new",
"DocumentStore",
"[",
"]",
"{",
"primary",
",",
"secondary",
"}",
";",
"}",
"public",
"boolean",
"isMediumDangerous",
"(",
")",
"{",
"return",
"mediumDangerous",
";",
"}",
"public",
"void",
"setMediumDangerous",
"(",
"boolean",
"mediumDangerous",
")",
"{",
"this",
".",
"mediumDangerous",
"=",
"mediumDangerous",
";",
"}",
"public",
"boolean",
"isVeryDangerous",
"(",
")",
"{",
"return",
"veryDangerous",
";",
"}",
"public",
"void",
"setVeryDangerous",
"(",
"boolean",
"veryDangerous",
")",
"{",
"this",
".",
"veryDangerous",
"=",
"veryDangerous",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"isReadOnly",
"(",
")",
"{",
"return",
"checkAndDoWithFailover",
"(",
"DocumentStore",
"::",
"isReadOnly",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"flush",
"(",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"DocumentStore",
"::",
"flush",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"beginTrackingWrites",
"(",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"DocumentStore",
"::",
"beginTrackingWrites",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"beginTrackingWrites",
"(",
"@",
"NonNullable",
"String",
"previousWritesContext",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"beginTrackingWrites",
"(",
"previousWritesContext",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"String",
"endTrackingWrites",
"(",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"DocumentStore",
"::",
"endTrackingWrites",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"clearTrackedWrites",
"(",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"DocumentStore",
"::",
"clearTrackedWrites",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"String",
"_id",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"_id",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"Value",
"_id",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"_id",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"String",
"_id",
",",
"String",
"...",
"fieldPaths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"_id",
",",
"fieldPaths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"String",
"_id",
",",
"FieldPath",
"...",
"fieldPaths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"_id",
",",
"fieldPaths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"Value",
"_id",
",",
"String",
"...",
"fieldPaths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"_id",
",",
"fieldPaths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"Value",
"value",
",",
"FieldPath",
"...",
"fieldPaths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"value",
",",
"fieldPaths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"String",
"s",
",",
"QueryCondition",
"queryCondition",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"s",
",",
"queryCondition",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"Value",
"value",
",",
"QueryCondition",
"queryCondition",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"value",
",",
"queryCondition",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"String",
"s",
",",
"QueryCondition",
"queryCondition",
",",
"String",
"...",
"strings",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"s",
",",
"queryCondition",
",",
"strings",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"String",
"s",
",",
"QueryCondition",
"queryCondition",
",",
"FieldPath",
"...",
"fieldPaths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"s",
",",
"queryCondition",
",",
"fieldPaths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"Value",
"value",
",",
"QueryCondition",
"queryCondition",
",",
"String",
"...",
"strings",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"value",
",",
"queryCondition",
",",
"strings",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"Document",
"findById",
"(",
"Value",
"value",
",",
"QueryCondition",
"queryCondition",
",",
"FieldPath",
"...",
"fieldPaths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findById",
"(",
"value",
",",
"queryCondition",
",",
"fieldPaths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"DocumentStream",
"find",
"(",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"DocumentStore",
"::",
"find",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"DocumentStream",
"find",
"(",
"@",
"NonNullable",
"String",
"...",
"paths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"find",
"(",
"paths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"DocumentStream",
"find",
"(",
"@",
"NonNullable",
"FieldPath",
"...",
"paths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"find",
"(",
"paths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"DocumentStream",
"find",
"(",
"@",
"NonNullable",
"QueryCondition",
"c",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"find",
"(",
"c",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"DocumentStream",
"find",
"(",
"@",
"NonNullable",
"QueryCondition",
"c",
",",
"@",
"NonNullable",
"String",
"...",
"paths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"find",
"(",
"c",
",",
"paths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"DocumentStream",
"find",
"(",
"@",
"NonNullable",
"QueryCondition",
"c",
",",
"@",
"NonNullable",
"FieldPath",
"...",
"paths",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"find",
"(",
"c",
",",
"paths",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n *\n * @return DocumentStream that wrapped by DocumentStreamFailoverWrapper for catching {@code StoreException}\n * and rethrowing {@code EnhancedJSONTable.FailoverException}\n */",
"@",
"Override",
"public",
"DocumentStream",
"findQuery",
"(",
"@",
"NonNullable",
"Query",
"query",
")",
"throws",
"StoreException",
"{",
"return",
"new",
"DocumentStreamFailoverWrapper",
"(",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findQuery",
"(",
"query",
")",
",",
"SAFE",
")",
")",
";",
"}",
"/**\n * {@inheritDoc}\n *\n * @return DocumentStream that wrapped by DocumentStreamFailoverWrapper for catching {@code StoreException}\n * and rethrowing {@code EnhancedJSONTable.FailoverException}\n */",
"@",
"Override",
"public",
"DocumentStream",
"findQuery",
"(",
"@",
"NonNullable",
"String",
"query",
")",
"throws",
"StoreException",
"{",
"return",
"new",
"DocumentStreamFailoverWrapper",
"(",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"findQuery",
"(",
"query",
")",
",",
"SAFE",
")",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insertOrReplace",
"(",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insertOrReplace",
"(",
"_id",
",",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insertOrReplace",
"(",
"doc",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insertOrReplace",
"(",
"doc",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insertOrReplace",
"(",
"stream",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insertOrReplace",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insertOrReplace",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insertOrReplace",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"_id",
",",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"_id",
",",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"update",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"DocumentMutation",
"m",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"update",
"(",
"_id",
",",
"m",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"update",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"DocumentMutation",
"mutation",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"update",
"(",
"_id",
",",
"mutation",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"String",
"_id",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"_id",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"Value",
"_id",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"_id",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"doc",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"doc",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"stream",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"delete",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"delete",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"_id",
",",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"doc",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"doc",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"stream",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"insert",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"insert",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"SAFE",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"_id",
",",
"doc",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"_id",
",",
"doc",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"doc",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"doc",
",",
"fieldAsKey",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"Document",
"doc",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"doc",
",",
"fieldAsKey",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"stream",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"FieldPath",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"replace",
"(",
"@",
"NonNullable",
"DocumentStream",
"stream",
",",
"@",
"NonNullable",
"String",
"fieldAsKey",
")",
"throws",
"MultiOpException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"replace",
"(",
"stream",
",",
"fieldAsKey",
")",
",",
"mediumDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"byte",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"short",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"int",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"long",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"float",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"double",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"@",
"NonNullable",
"BigDecimal",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"byte",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"short",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"int",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"long",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"float",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"double",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"void",
"increment",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"String",
"field",
",",
"@",
"NonNullable",
"BigDecimal",
"inc",
")",
"throws",
"StoreException",
"{",
"doNoReturn",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"increment",
"(",
"_id",
",",
"field",
",",
"inc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"checkAndMutate",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"QueryCondition",
"condition",
",",
"@",
"NonNullable",
"DocumentMutation",
"mutation",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"checkAndMutate",
"(",
"_id",
",",
"condition",
",",
"mutation",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"checkAndDelete",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"QueryCondition",
"condition",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"checkAndDelete",
"(",
"_id",
",",
"condition",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"checkAndReplace",
"(",
"@",
"NonNullable",
"String",
"_id",
",",
"@",
"NonNullable",
"QueryCondition",
"condition",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"checkAndReplace",
"(",
"_id",
",",
"condition",
",",
"doc",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"checkAndMutate",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"QueryCondition",
"condition",
",",
"@",
"NonNullable",
"DocumentMutation",
"m",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"checkAndMutate",
"(",
"_id",
",",
"condition",
",",
"m",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"checkAndDelete",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"QueryCondition",
"condition",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"checkAndDelete",
"(",
"_id",
",",
"condition",
")",
",",
"veryDangerous",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"@",
"Override",
"public",
"boolean",
"checkAndReplace",
"(",
"@",
"NonNullable",
"Value",
"_id",
",",
"@",
"NonNullable",
"QueryCondition",
"condition",
",",
"@",
"NonNullable",
"Document",
"doc",
")",
"throws",
"StoreException",
"{",
"return",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"t",
".",
"checkAndReplace",
"(",
"_id",
",",
"condition",
",",
"doc",
")",
",",
"veryDangerous",
")",
";",
"}",
"public",
"boolean",
"isTableSwitched",
"(",
")",
"{",
"return",
"switched",
".",
"get",
"(",
")",
";",
"}",
"private",
"void",
"doNoReturn",
"(",
"TableProcedure",
"task",
",",
"boolean",
"withFailover",
")",
"{",
"checkAndDoWithFailover",
"(",
"(",
"DocumentStore",
"t",
")",
"->",
"{",
"task",
".",
"apply",
"(",
"t",
")",
";",
"return",
"null",
";",
"}",
",",
"withFailover",
")",
";",
"}",
"private",
"<",
"R",
">",
"R",
"checkAndDoWithFailover",
"(",
"TableFunction",
"<",
"R",
">",
"task",
",",
"boolean",
"withFailover",
")",
"{",
"int",
"i",
"=",
"current",
".",
"get",
"(",
")",
";",
"DocumentStore",
"primary",
"=",
"stores",
"[",
"i",
"]",
";",
"DocumentStore",
"secondary",
"=",
"stores",
"[",
"1",
"-",
"i",
"]",
";",
"if",
"(",
"withFailover",
")",
"{",
"if",
"(",
"switched",
".",
"get",
"(",
")",
")",
"{",
"return",
"doWithFallback",
"(",
"secondaryExecutor",
",",
"primaryExecutor",
",",
"timeOut",
",",
"secondaryTimeOut",
",",
"task",
",",
"primary",
",",
"secondary",
",",
"this",
"::",
"swapTableLinks",
",",
"switched",
")",
";",
"}",
"else",
"{",
"return",
"doWithFallback",
"(",
"primaryExecutor",
",",
"secondaryExecutor",
",",
"timeOut",
",",
"secondaryTimeOut",
",",
"task",
",",
"primary",
",",
"secondary",
",",
"this",
"::",
"swapTableLinks",
",",
"switched",
")",
";",
"}",
"}",
"else",
"{",
"return",
"doWithoutFailover",
"(",
"task",
",",
"primary",
")",
";",
"}",
"}",
"/**\n * Process request to db without Failover\n *\n * @param task A lambda with one argument, a table, that does the desired operation\n * @param primary The primary table\n * @param <R> The type that task will return\n * @return The value returned by task\n */",
"private",
"<",
"R",
">",
"R",
"doWithoutFailover",
"(",
"TableFunction",
"<",
"R",
">",
"task",
",",
"DocumentStore",
"primary",
")",
"{",
"try",
"{",
"return",
"primaryExecutor",
".",
"submit",
"(",
"(",
")",
"->",
"task",
".",
"apply",
"(",
"primary",
")",
")",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"FailoverException",
"(",
"\"",
"Thread was interrupted during operation",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"e",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"instanceof",
"RuntimeException",
")",
"{",
"throw",
"(",
"RuntimeException",
")",
"cause",
";",
"}",
"else",
"{",
"throw",
"new",
"FailoverException",
"(",
"\"",
"Checked exception thrown (shouldn't happen)",
"\"",
",",
"cause",
")",
";",
"}",
"}",
"}",
"/**\n * Tries to do task on primary until timeOut milliseconds have passed. From then\n * the task is also attempted with secondary. If second succeeds, we use that result.\n * If the primary blows the first timeout, then we initiate a failover by invoking\n * failoverTask. When both primary and secondary throw exceptions, we rethrow the\n * last exception received. When secondary exceed secondaryTimeOut\n * milliseconds with no exceptions and no results, then an exception is thrown.\n * <p>\n * This method is static to make testing easier.\n *\n * @param prim The executor that does all the work\n * @param timeOut How long to wait before invoking the secondary\n * @param secondaryTimeOut How long to wait before entirely giving up\n * @param task A lambda with one argument, a table, that does the desired operation\n * @param primary The primary table\n * @param secondary The secondary table\n * @param failover The function to call when primary doesn't respond quickly\n * @param switched The flag, that indicate that table switched or not\n * @param <R> The type that task will return\n * @return The value returned by task\n * @throws StoreException If both primary and secondary fail\n * @throws FailoverException If both primary and secondary fail. This may wrap a real exception\n */",
"static",
"<",
"R",
">",
"R",
"doWithFallback",
"(",
"ExecutorService",
"prim",
",",
"ExecutorService",
"sec",
",",
"long",
"timeOut",
",",
"long",
"secondaryTimeOut",
",",
"TableFunction",
"<",
"R",
">",
"task",
",",
"DocumentStore",
"primary",
",",
"DocumentStore",
"secondary",
",",
"Runnable",
"failover",
",",
"AtomicBoolean",
"switched",
")",
"{",
"Future",
"<",
"R",
">",
"primaryFuture",
"=",
"prim",
".",
"submit",
"(",
"(",
")",
"->",
"task",
".",
"apply",
"(",
"primary",
")",
")",
";",
"try",
"{",
"try",
"{",
"return",
"primaryFuture",
".",
"get",
"(",
"timeOut",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"|",
"ExecutionException",
"e",
")",
"{",
"primaryFuture",
".",
"cancel",
"(",
"true",
")",
";",
"if",
"(",
"!",
"switched",
".",
"get",
"(",
")",
")",
"{",
"failover",
".",
"run",
"(",
")",
";",
"}",
"return",
"sec",
".",
"submit",
"(",
"(",
")",
"->",
"task",
".",
"apply",
"(",
"secondary",
")",
")",
".",
"get",
"(",
"secondaryTimeOut",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"FailoverException",
"(",
"\"",
"Thread was interrupted during operation",
"\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"e",
".",
"getCause",
"(",
")",
";",
"if",
"(",
"cause",
"instanceof",
"RuntimeException",
")",
"{",
"throw",
"(",
"RuntimeException",
")",
"cause",
";",
"}",
"else",
"{",
"throw",
"new",
"FailoverException",
"(",
"\"",
"Checked exception thrown (shouldn't happen)",
"\"",
",",
"cause",
")",
";",
"}",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"throw",
"new",
"FailoverException",
"(",
"\"",
"Operation timed out on primary and secondary tables",
"\"",
",",
"e",
")",
";",
"}",
"}",
"/**\n * Swap primary and secondary tables\n * <p>\n * When failing over to another table/cluster or when going back to origin/master cluster\n * we do not change the whole logic, but simply switch the primary/secondary tables\n */",
"private",
"void",
"swapTableLinks",
"(",
")",
"{",
"current",
".",
"getAndUpdate",
"(",
"old",
"->",
"1",
"-",
"old",
")",
";",
"switched",
".",
"compareAndSet",
"(",
"switched",
".",
"get",
"(",
")",
",",
"!",
"switched",
".",
"get",
"(",
")",
")",
";",
"LOG",
".",
"info",
"(",
"\"",
"Table switched: ",
"\"",
"+",
"switched",
".",
"get",
"(",
")",
")",
";",
"if",
"(",
"switched",
".",
"get",
"(",
")",
")",
"{",
"int",
"stick",
"=",
"counterForTableSwitching",
".",
"getAndIncrement",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"",
"Switch table for - {} ms",
"\"",
",",
"getTimeOut",
"(",
"stick",
")",
")",
";",
"swapTableBackAfter",
"(",
"getTimeOut",
"(",
"stick",
")",
")",
";",
"}",
"}",
"/**\n * Create task for swapping table back after timeout\n *\n * @param timeout Time after what we swap table back\n */",
"private",
"void",
"swapTableBackAfter",
"(",
"long",
"timeout",
")",
"{",
"scheduler",
".",
"schedule",
"(",
"this",
"::",
"swapTableLinks",
",",
"timeout",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}",
"/**\n * Determines the amount of time that we need to stay on another table\n * <p>\n *\n * @param numberOfSwitch Quantity of table switching\n * @return time in milliseconds\n */",
"private",
"long",
"getTimeOut",
"(",
"int",
"numberOfSwitch",
")",
"{",
"long",
"minute",
"=",
"60000",
";",
"switch",
"(",
"numberOfSwitch",
")",
"{",
"case",
"0",
":",
"return",
"minute",
"/",
"3",
";",
"case",
"1",
":",
"return",
"minute",
";",
"default",
":",
"return",
"2",
"*",
"minute",
";",
"}",
"}",
"/**\n * Shutdown all executors, close connection to the tables.\n * If you do not call this method, the application will freeze\n *\n * @throws StoreException If the underlying tables fail to close cleanly.\n */",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"StoreException",
"{",
"scheduler",
".",
"shutdownNow",
"(",
")",
";",
"primaryExecutor",
".",
"shutdownNow",
"(",
")",
";",
"secondaryExecutor",
".",
"shutdownNow",
"(",
")",
";",
"try",
"{",
"stores",
"[",
"0",
"]",
".",
"close",
"(",
")",
";",
"}",
"finally",
"{",
"stores",
"[",
"1",
"]",
".",
"close",
"(",
")",
";",
"}",
"}",
"/**\n * Get DocumentStore from MapR-DB.\n * Table must exist.\n *\n * @param tableName Name that correspond to db table name\n * @return com.mapr.db.Table\n */",
"private",
"DocumentStore",
"getDocumentStore",
"(",
"String",
"tableName",
")",
"{",
"Connection",
"connection",
"=",
"DriverManager",
".",
"getConnection",
"(",
"DB_DRIVER_NAME",
")",
";",
"return",
"connection",
".",
"getStore",
"(",
"tableName",
")",
";",
"}",
"static",
"class",
"FailoverException",
"extends",
"StoreException",
"{",
"FailoverException",
"(",
"String",
"msg",
",",
"Throwable",
"cause",
")",
"{",
"super",
"(",
"msg",
",",
"cause",
")",
";",
"}",
"}",
"public",
"interface",
"TableFunction",
"<",
"R",
">",
"{",
"R",
"apply",
"(",
"DocumentStore",
"d",
")",
"throws",
"InterruptedException",
";",
"}",
"public",
"interface",
"TableProcedure",
"{",
"void",
"apply",
"(",
"DocumentStore",
"t",
")",
";",
"}",
"}"
] | EnhancedJSONTable represents a wrapper above {@link DocumentStore} providing a fail-over
strategy that should provide user a high availability of cluster. | [
"EnhancedJSONTable",
"represents",
"a",
"wrapper",
"above",
"{",
"@link",
"DocumentStore",
"}",
"providing",
"a",
"fail",
"-",
"over",
"strategy",
"that",
"should",
"provide",
"user",
"a",
"high",
"availability",
"of",
"cluster",
"."
] | [
"// How long to wait before starting secondary query",
"// How long to wait before giving up on a good result",
"// the tables we talk to. Primary is first, then secondary",
"// the index for stores",
"// Indicates if the table switched in that moment",
"// the names of the tables",
"// TODO verify that this method reference does what is expected",
"// change executor if table switched, in this case primary executor work only with primary cluster",
"// and secondary executor work only with failover table",
"// this should never happen except perhaps in debugging or on shutdown",
"// these are likely StoreException, but we don't differentiate",
"// this should not happen in our situation since none of the methods do this",
"// try on the primary table ... if we get a result, we win",
"// We have lost confidence in the primary at this point even if we get a result",
"// We cancel request to the primary table, for fast change to the failover table",
"// No result in time from primary so we now try on secondary.",
"// Exceptional returns when timeout expires.",
"// this should never happen except perhaps in debugging or on shutdown",
"// these are likely StoreException, but we don't differentiate",
"// this should not happen in our situation since none of the methods do this"
] | [
{
"param": "DocumentStore",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "DocumentStore",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fee07e43b10e05ede8e30196ce563c7137de9b2d | mirajgodha/cdap | cdap-app-fabric-tests/src/test/java/co/cask/cdap/internal/app/runtime/distributed/DistributedWorkflowProgramRunnerTest.java | [
"Apache-2.0"
] | Java | DistributedWorkflowProgramRunnerTest | /**
* Unit tests for the {@link DistributedWorkflowProgramRunner}.
* This test class uses {@link DistributedWorkflowTestApp} for testing various aspect of the program runner.
*/ | Unit tests for the DistributedWorkflowProgramRunner.
This test class uses DistributedWorkflowTestApp for testing various aspect of the program runner. | [
"Unit",
"tests",
"for",
"the",
"DistributedWorkflowProgramRunner",
".",
"This",
"test",
"class",
"uses",
"DistributedWorkflowTestApp",
"for",
"testing",
"various",
"aspect",
"of",
"the",
"program",
"runner",
"."
] | public class DistributedWorkflowProgramRunnerTest {
@ClassRule
public static final TemporaryFolder TEMP_FOLDER = new TemporaryFolder();
private static CConfiguration cConf;
private static ProgramRunnerFactory programRunnerFactory;
@BeforeClass
public static void init() throws IOException {
cConf = createCConf();
programRunnerFactory = createProgramRunnerFactory(cConf);
}
@Test
public void testDefaultResources() throws IOException {
// By default the workflow driver would have 768m if none of the children is setting it to higher
// (default for programs are 512m)
testDriverResources(DistributedWorkflowTestApp.SequentialWorkflow.class.getSimpleName(),
Collections.emptyMap(), new Resources(768));
}
@Test
public void testExplicitResources() throws IOException {
// Explicitly set the resources for the workflow, it should always get honored.
// The one prefixed with "task.workflow." should override the one without.
testDriverResources(DistributedWorkflowTestApp.ComplexWorkflow.class.getSimpleName(),
ImmutableMap.of(
SystemArguments.MEMORY_KEY, "4096",
"task.workflow." + SystemArguments.MEMORY_KEY, "1024"
),
new Resources(1024));
}
@Test
public void testInferredResources() throws IOException {
// Inferred from the largest memory usage from children
testDriverResources(DistributedWorkflowTestApp.SequentialWorkflow.class.getSimpleName(),
Collections.singletonMap("mapreduce.mr1." + SystemArguments.MEMORY_KEY, "2048"),
new Resources(2048));
}
@Test
public void testForkJoinInferredResources() throws IOException {
// The complex workflow has 4 parallel executions at max, hence the memory setting should be summation of them
// For vcores, it should pick the max
testDriverResources(DistributedWorkflowTestApp.ComplexWorkflow.class.getSimpleName(),
ImmutableMap.of(
"spark.s2." + SystemArguments.MEMORY_KEY, "1024",
"mapreduce.mr3." + SystemArguments.CORES_KEY, "3"
),
new Resources(512 + 512 + 1024 + 512, 3));
}
@Test
public void testConditionInferredResources() throws IOException {
// Set one of the branch to have memory > fork memory
testDriverResources(DistributedWorkflowTestApp.ComplexWorkflow.class.getSimpleName(),
Collections.singletonMap("spark.s4." + SystemArguments.MEMORY_KEY, "4096"),
new Resources(4096));
}
@Test
public void testInferredWithMaxResources() throws IOException {
// Set to use large memory for the first node in the complex workflow to have it larger than the sum of all forks
testDriverResources(DistributedWorkflowTestApp.ComplexWorkflow.class.getSimpleName(),
Collections.singletonMap("mapreduce.mr1." + SystemArguments.MEMORY_KEY, "4096"),
new Resources(4096));
}
@Test
public void testInferredScopedResources() throws IOException {
// Inferred from the largest memory usage from children.
// Make sure the children arguments have scope resolved correctly.
testDriverResources(DistributedWorkflowTestApp.SequentialWorkflow.class.getSimpleName(),
ImmutableMap.of(
"mapreduce.mr1.task.mapper." + SystemArguments.MEMORY_KEY, "2048",
"spark.s1.task.client." + SystemArguments.MEMORY_KEY, "1024",
"spark.s1.task.driver." + SystemArguments.MEMORY_KEY, "4096"
),
// Should pick the spark client memory
new Resources(1024));
}
@Test
public void testOverrideInferredResources() throws IOException {
// Explicitly setting memory always override what's inferred from children
testDriverResources(DistributedWorkflowTestApp.SequentialWorkflow.class.getSimpleName(),
ImmutableMap.of(
"task.workflow." + SystemArguments.MEMORY_KEY, "512",
"mapreduce.mr1." + SystemArguments.MEMORY_KEY, "2048",
"spark.s1." + SystemArguments.MEMORY_KEY, "1024"
), new Resources(512));
}
@Test
public void testReservedMemoryOverride() throws IOException {
// Sets the reserved memory override for the workflow
String workflowName = DistributedWorkflowTestApp.SequentialWorkflow.class.getSimpleName();
ProgramLaunchConfig launchConfig = setupWorkflowRuntime(workflowName,
ImmutableMap.of(
SystemArguments.RESERVED_MEMORY_KEY_OVERRIDE, "400",
SystemArguments.MEMORY_KEY, "800"
));
RunnableDefinition runnableDefinition = launchConfig.getRunnables().get(workflowName);
Assert.assertNotNull(runnableDefinition);
Map<String, String> twillConfigs = runnableDefinition.getTwillRunnableConfigs();
Assert.assertEquals("400", twillConfigs.get(Configs.Keys.JAVA_RESERVED_MEMORY_MB));
Assert.assertEquals("0.50", twillConfigs.get(Configs.Keys.HEAP_RESERVED_MIN_RATIO));
}
/**
* Helper method to help testing workflow driver resources settings based on varying user arguments
*
* @param workflowName name of the workflow as defined in the {@link DistributedWorkflowTestApp}.
* @param runtimeArgs the runtime arguments for the workflow program
* @param expectedDriverResources the expected {@link Resources} setting for the workflow driver
*/
private void testDriverResources(String workflowName, Map<String, String> runtimeArgs,
Resources expectedDriverResources) throws IOException {
ProgramLaunchConfig launchConfig = setupWorkflowRuntime(workflowName, runtimeArgs);
// Validate the resources setting
RunnableDefinition runnableDefinition = launchConfig.getRunnables().get(workflowName);
Assert.assertNotNull(runnableDefinition);
ResourceSpecification resources = runnableDefinition.getResources();
Assert.assertEquals(expectedDriverResources.getMemoryMB(), resources.getMemorySize());
Assert.assertEquals(expectedDriverResources.getVirtualCores(), resources.getVirtualCores());
}
/**
* Setup the {@link ProgramLaunchConfig} for the given workflow.
*/
private ProgramLaunchConfig setupWorkflowRuntime(String workflowName,
Map<String, String> runtimeArgs) throws IOException {
// Create the distributed workflow program runner
ProgramRunner programRunner = programRunnerFactory.create(ProgramType.WORKFLOW);
Assert.assertTrue(programRunner instanceof DistributedWorkflowProgramRunner);
DistributedWorkflowProgramRunner workflowRunner = (DistributedWorkflowProgramRunner) programRunner;
// Create the Workflow Program
Program workflowProgram = createWorkflowProgram(cConf, programRunner, workflowName);
ProgramLaunchConfig launchConfig = new ProgramLaunchConfig();
ProgramOptions programOpts = new SimpleProgramOptions(workflowProgram.getId(),
new BasicArguments(), new BasicArguments(runtimeArgs));
// Setup the launching config
workflowRunner.setupLaunchConfig(launchConfig, workflowProgram, programOpts,
cConf, new Configuration(), TEMP_FOLDER.newFolder());
return launchConfig;
}
/**
* Creates a workflow {@link Program}.
*/
private Program createWorkflowProgram(CConfiguration cConf, ProgramRunner programRunner,
String workflowName) throws IOException {
Location appJarLocation = AppJarHelper.createDeploymentJar(new LocalLocationFactory(TEMP_FOLDER.newFolder()),
DistributedWorkflowTestApp.class);
ArtifactId artifactId = NamespaceId.DEFAULT.artifact("test", "1.0.0");
DistributedWorkflowTestApp app = new DistributedWorkflowTestApp();
DefaultAppConfigurer configurer = new DefaultAppConfigurer(Id.Namespace.DEFAULT,
Id.Artifact.fromEntityId(artifactId), app);
app.configure(configurer, new DefaultApplicationContext<>());
ApplicationSpecification appSpec = configurer.createSpecification(null);
ProgramId programId = NamespaceId.DEFAULT
.app(appSpec.getName())
.program(ProgramType.WORKFLOW, workflowName);
return Programs.create(cConf, programRunner, new ProgramDescriptor(programId, appSpec),
appJarLocation, TEMP_FOLDER.newFolder());
}
private static ProgramRunnerFactory createProgramRunnerFactory(CConfiguration cConf) {
Injector injector = Guice.createInjector(
new ConfigModule(cConf),
new ZKClientModule(),
new ZKDiscoveryModule(),
new LocalLogAppenderModule(),
new LocalLocationModule(),
new IOModule(),
new KafkaClientModule(),
new DataSetServiceModules().getDistributedModules(),
new DataFabricModules("cdap.master").getDistributedModules(),
new DataSetsModules().getDistributedModules(),
new MetricsClientRuntimeModule().getDistributedModules(),
new MetricsStoreModule(),
new MessagingClientModule(),
new ExploreClientModule(),
new AuditModule(),
new AuthorizationModule(),
new AuthorizationEnforcementModule().getMasterModule(),
new TwillModule(),
new AppFabricServiceRuntimeModule().getDistributedModules(),
new ProgramRunnerRuntimeModule().getDistributedModules(),
new SecureStoreServerModule(),
new OperationalStatsModule(),
new AbstractModule() {
@Override
protected void configure() {
// TODO (CDAP-14677): find a better way to inject metadata publisher
bind(MetadataPublisher.class).to(MessagingMetadataPublisher.class);
}
});
return injector.getInstance(ProgramRunnerFactory.class);
}
private static CConfiguration createCConf() throws IOException {
CConfiguration cConf = CConfiguration.create();
cConf.set(Constants.CFG_LOCAL_DATA_DIR, TEMP_FOLDER.newFolder().getAbsolutePath());
return cConf;
}
} | [
"public",
"class",
"DistributedWorkflowProgramRunnerTest",
"{",
"@",
"ClassRule",
"public",
"static",
"final",
"TemporaryFolder",
"TEMP_FOLDER",
"=",
"new",
"TemporaryFolder",
"(",
")",
";",
"private",
"static",
"CConfiguration",
"cConf",
";",
"private",
"static",
"ProgramRunnerFactory",
"programRunnerFactory",
";",
"@",
"BeforeClass",
"public",
"static",
"void",
"init",
"(",
")",
"throws",
"IOException",
"{",
"cConf",
"=",
"createCConf",
"(",
")",
";",
"programRunnerFactory",
"=",
"createProgramRunnerFactory",
"(",
"cConf",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testDefaultResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"SequentialWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"Collections",
".",
"emptyMap",
"(",
")",
",",
"new",
"Resources",
"(",
"768",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testExplicitResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"ComplexWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"ImmutableMap",
".",
"of",
"(",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"4096",
"\"",
",",
"\"",
"task.workflow.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"1024",
"\"",
")",
",",
"new",
"Resources",
"(",
"1024",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testInferredResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"SequentialWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"Collections",
".",
"singletonMap",
"(",
"\"",
"mapreduce.mr1.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"2048",
"\"",
")",
",",
"new",
"Resources",
"(",
"2048",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testForkJoinInferredResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"ComplexWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"ImmutableMap",
".",
"of",
"(",
"\"",
"spark.s2.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"1024",
"\"",
",",
"\"",
"mapreduce.mr3.",
"\"",
"+",
"SystemArguments",
".",
"CORES_KEY",
",",
"\"",
"3",
"\"",
")",
",",
"new",
"Resources",
"(",
"512",
"+",
"512",
"+",
"1024",
"+",
"512",
",",
"3",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testConditionInferredResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"ComplexWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"Collections",
".",
"singletonMap",
"(",
"\"",
"spark.s4.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"4096",
"\"",
")",
",",
"new",
"Resources",
"(",
"4096",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testInferredWithMaxResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"ComplexWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"Collections",
".",
"singletonMap",
"(",
"\"",
"mapreduce.mr1.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"4096",
"\"",
")",
",",
"new",
"Resources",
"(",
"4096",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testInferredScopedResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"SequentialWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"ImmutableMap",
".",
"of",
"(",
"\"",
"mapreduce.mr1.task.mapper.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"2048",
"\"",
",",
"\"",
"spark.s1.task.client.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"1024",
"\"",
",",
"\"",
"spark.s1.task.driver.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"4096",
"\"",
")",
",",
"new",
"Resources",
"(",
"1024",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testOverrideInferredResources",
"(",
")",
"throws",
"IOException",
"{",
"testDriverResources",
"(",
"DistributedWorkflowTestApp",
".",
"SequentialWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
",",
"ImmutableMap",
".",
"of",
"(",
"\"",
"task.workflow.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"512",
"\"",
",",
"\"",
"mapreduce.mr1.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"2048",
"\"",
",",
"\"",
"spark.s1.",
"\"",
"+",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"1024",
"\"",
")",
",",
"new",
"Resources",
"(",
"512",
")",
")",
";",
"}",
"@",
"Test",
"public",
"void",
"testReservedMemoryOverride",
"(",
")",
"throws",
"IOException",
"{",
"String",
"workflowName",
"=",
"DistributedWorkflowTestApp",
".",
"SequentialWorkflow",
".",
"class",
".",
"getSimpleName",
"(",
")",
";",
"ProgramLaunchConfig",
"launchConfig",
"=",
"setupWorkflowRuntime",
"(",
"workflowName",
",",
"ImmutableMap",
".",
"of",
"(",
"SystemArguments",
".",
"RESERVED_MEMORY_KEY_OVERRIDE",
",",
"\"",
"400",
"\"",
",",
"SystemArguments",
".",
"MEMORY_KEY",
",",
"\"",
"800",
"\"",
")",
")",
";",
"RunnableDefinition",
"runnableDefinition",
"=",
"launchConfig",
".",
"getRunnables",
"(",
")",
".",
"get",
"(",
"workflowName",
")",
";",
"Assert",
".",
"assertNotNull",
"(",
"runnableDefinition",
")",
";",
"Map",
"<",
"String",
",",
"String",
">",
"twillConfigs",
"=",
"runnableDefinition",
".",
"getTwillRunnableConfigs",
"(",
")",
";",
"Assert",
".",
"assertEquals",
"(",
"\"",
"400",
"\"",
",",
"twillConfigs",
".",
"get",
"(",
"Configs",
".",
"Keys",
".",
"JAVA_RESERVED_MEMORY_MB",
")",
")",
";",
"Assert",
".",
"assertEquals",
"(",
"\"",
"0.50",
"\"",
",",
"twillConfigs",
".",
"get",
"(",
"Configs",
".",
"Keys",
".",
"HEAP_RESERVED_MIN_RATIO",
")",
")",
";",
"}",
"/**\n * Helper method to help testing workflow driver resources settings based on varying user arguments\n *\n * @param workflowName name of the workflow as defined in the {@link DistributedWorkflowTestApp}.\n * @param runtimeArgs the runtime arguments for the workflow program\n * @param expectedDriverResources the expected {@link Resources} setting for the workflow driver\n */",
"private",
"void",
"testDriverResources",
"(",
"String",
"workflowName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"runtimeArgs",
",",
"Resources",
"expectedDriverResources",
")",
"throws",
"IOException",
"{",
"ProgramLaunchConfig",
"launchConfig",
"=",
"setupWorkflowRuntime",
"(",
"workflowName",
",",
"runtimeArgs",
")",
";",
"RunnableDefinition",
"runnableDefinition",
"=",
"launchConfig",
".",
"getRunnables",
"(",
")",
".",
"get",
"(",
"workflowName",
")",
";",
"Assert",
".",
"assertNotNull",
"(",
"runnableDefinition",
")",
";",
"ResourceSpecification",
"resources",
"=",
"runnableDefinition",
".",
"getResources",
"(",
")",
";",
"Assert",
".",
"assertEquals",
"(",
"expectedDriverResources",
".",
"getMemoryMB",
"(",
")",
",",
"resources",
".",
"getMemorySize",
"(",
")",
")",
";",
"Assert",
".",
"assertEquals",
"(",
"expectedDriverResources",
".",
"getVirtualCores",
"(",
")",
",",
"resources",
".",
"getVirtualCores",
"(",
")",
")",
";",
"}",
"/**\n * Setup the {@link ProgramLaunchConfig} for the given workflow.\n */",
"private",
"ProgramLaunchConfig",
"setupWorkflowRuntime",
"(",
"String",
"workflowName",
",",
"Map",
"<",
"String",
",",
"String",
">",
"runtimeArgs",
")",
"throws",
"IOException",
"{",
"ProgramRunner",
"programRunner",
"=",
"programRunnerFactory",
".",
"create",
"(",
"ProgramType",
".",
"WORKFLOW",
")",
";",
"Assert",
".",
"assertTrue",
"(",
"programRunner",
"instanceof",
"DistributedWorkflowProgramRunner",
")",
";",
"DistributedWorkflowProgramRunner",
"workflowRunner",
"=",
"(",
"DistributedWorkflowProgramRunner",
")",
"programRunner",
";",
"Program",
"workflowProgram",
"=",
"createWorkflowProgram",
"(",
"cConf",
",",
"programRunner",
",",
"workflowName",
")",
";",
"ProgramLaunchConfig",
"launchConfig",
"=",
"new",
"ProgramLaunchConfig",
"(",
")",
";",
"ProgramOptions",
"programOpts",
"=",
"new",
"SimpleProgramOptions",
"(",
"workflowProgram",
".",
"getId",
"(",
")",
",",
"new",
"BasicArguments",
"(",
")",
",",
"new",
"BasicArguments",
"(",
"runtimeArgs",
")",
")",
";",
"workflowRunner",
".",
"setupLaunchConfig",
"(",
"launchConfig",
",",
"workflowProgram",
",",
"programOpts",
",",
"cConf",
",",
"new",
"Configuration",
"(",
")",
",",
"TEMP_FOLDER",
".",
"newFolder",
"(",
")",
")",
";",
"return",
"launchConfig",
";",
"}",
"/**\n * Creates a workflow {@link Program}.\n */",
"private",
"Program",
"createWorkflowProgram",
"(",
"CConfiguration",
"cConf",
",",
"ProgramRunner",
"programRunner",
",",
"String",
"workflowName",
")",
"throws",
"IOException",
"{",
"Location",
"appJarLocation",
"=",
"AppJarHelper",
".",
"createDeploymentJar",
"(",
"new",
"LocalLocationFactory",
"(",
"TEMP_FOLDER",
".",
"newFolder",
"(",
")",
")",
",",
"DistributedWorkflowTestApp",
".",
"class",
")",
";",
"ArtifactId",
"artifactId",
"=",
"NamespaceId",
".",
"DEFAULT",
".",
"artifact",
"(",
"\"",
"test",
"\"",
",",
"\"",
"1.0.0",
"\"",
")",
";",
"DistributedWorkflowTestApp",
"app",
"=",
"new",
"DistributedWorkflowTestApp",
"(",
")",
";",
"DefaultAppConfigurer",
"configurer",
"=",
"new",
"DefaultAppConfigurer",
"(",
"Id",
".",
"Namespace",
".",
"DEFAULT",
",",
"Id",
".",
"Artifact",
".",
"fromEntityId",
"(",
"artifactId",
")",
",",
"app",
")",
";",
"app",
".",
"configure",
"(",
"configurer",
",",
"new",
"DefaultApplicationContext",
"<",
">",
"(",
")",
")",
";",
"ApplicationSpecification",
"appSpec",
"=",
"configurer",
".",
"createSpecification",
"(",
"null",
")",
";",
"ProgramId",
"programId",
"=",
"NamespaceId",
".",
"DEFAULT",
".",
"app",
"(",
"appSpec",
".",
"getName",
"(",
")",
")",
".",
"program",
"(",
"ProgramType",
".",
"WORKFLOW",
",",
"workflowName",
")",
";",
"return",
"Programs",
".",
"create",
"(",
"cConf",
",",
"programRunner",
",",
"new",
"ProgramDescriptor",
"(",
"programId",
",",
"appSpec",
")",
",",
"appJarLocation",
",",
"TEMP_FOLDER",
".",
"newFolder",
"(",
")",
")",
";",
"}",
"private",
"static",
"ProgramRunnerFactory",
"createProgramRunnerFactory",
"(",
"CConfiguration",
"cConf",
")",
"{",
"Injector",
"injector",
"=",
"Guice",
".",
"createInjector",
"(",
"new",
"ConfigModule",
"(",
"cConf",
")",
",",
"new",
"ZKClientModule",
"(",
")",
",",
"new",
"ZKDiscoveryModule",
"(",
")",
",",
"new",
"LocalLogAppenderModule",
"(",
")",
",",
"new",
"LocalLocationModule",
"(",
")",
",",
"new",
"IOModule",
"(",
")",
",",
"new",
"KafkaClientModule",
"(",
")",
",",
"new",
"DataSetServiceModules",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"DataFabricModules",
"(",
"\"",
"cdap.master",
"\"",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"DataSetsModules",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"MetricsClientRuntimeModule",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"MetricsStoreModule",
"(",
")",
",",
"new",
"MessagingClientModule",
"(",
")",
",",
"new",
"ExploreClientModule",
"(",
")",
",",
"new",
"AuditModule",
"(",
")",
",",
"new",
"AuthorizationModule",
"(",
")",
",",
"new",
"AuthorizationEnforcementModule",
"(",
")",
".",
"getMasterModule",
"(",
")",
",",
"new",
"TwillModule",
"(",
")",
",",
"new",
"AppFabricServiceRuntimeModule",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"ProgramRunnerRuntimeModule",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"SecureStoreServerModule",
"(",
")",
",",
"new",
"OperationalStatsModule",
"(",
")",
",",
"new",
"AbstractModule",
"(",
")",
"{",
"@",
"Override",
"protected",
"void",
"configure",
"(",
")",
"{",
"bind",
"(",
"MetadataPublisher",
".",
"class",
")",
".",
"to",
"(",
"MessagingMetadataPublisher",
".",
"class",
")",
";",
"}",
"}",
")",
";",
"return",
"injector",
".",
"getInstance",
"(",
"ProgramRunnerFactory",
".",
"class",
")",
";",
"}",
"private",
"static",
"CConfiguration",
"createCConf",
"(",
")",
"throws",
"IOException",
"{",
"CConfiguration",
"cConf",
"=",
"CConfiguration",
".",
"create",
"(",
")",
";",
"cConf",
".",
"set",
"(",
"Constants",
".",
"CFG_LOCAL_DATA_DIR",
",",
"TEMP_FOLDER",
".",
"newFolder",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"return",
"cConf",
";",
"}",
"}"
] | Unit tests for the {@link DistributedWorkflowProgramRunner}. | [
"Unit",
"tests",
"for",
"the",
"{",
"@link",
"DistributedWorkflowProgramRunner",
"}",
"."
] | [
"// By default the workflow driver would have 768m if none of the children is setting it to higher",
"// (default for programs are 512m)",
"// Explicitly set the resources for the workflow, it should always get honored.",
"// The one prefixed with \"task.workflow.\" should override the one without.",
"// Inferred from the largest memory usage from children",
"// The complex workflow has 4 parallel executions at max, hence the memory setting should be summation of them",
"// For vcores, it should pick the max",
"// Set one of the branch to have memory > fork memory",
"// Set to use large memory for the first node in the complex workflow to have it larger than the sum of all forks",
"// Inferred from the largest memory usage from children.",
"// Make sure the children arguments have scope resolved correctly.",
"// Should pick the spark client memory",
"// Explicitly setting memory always override what's inferred from children",
"// Sets the reserved memory override for the workflow",
"// Validate the resources setting",
"// Create the distributed workflow program runner",
"// Create the Workflow Program",
"// Setup the launching config",
"// TODO (CDAP-14677): find a better way to inject metadata publisher"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
fee1ccb403dd25bc9b9df788c443a2df4cf3659f | fatu/shifu | src/main/java/ml/shifu/shifu/core/pmml/builder/impl/NNSpecifCreator.java | [
"Apache-2.0"
] | Java | NNSpecifCreator | /**
* Created by zhanhu on 3/29/16.
*/ | Created by zhanhu on 3/29/16. | [
"Created",
"by",
"zhanhu",
"on",
"3",
"/",
"29",
"/",
"16",
"."
] | public class NNSpecifCreator extends AbstractSpecifCreator {
@Override
public boolean build(BasicML basicML, Model model) {
NeuralNetwork nnPmmlModel = (NeuralNetwork) model;
new PMMLEncogNeuralNetworkModel().adaptMLModelToPMML((BasicNetwork) basicML, nnPmmlModel);
nnPmmlModel.withOutput(createNormalizedOutput());
return true;
}
@Override
public boolean build(BasicML basicML, Model model, int id) {
NeuralNetwork nnPmmlModel = (NeuralNetwork) model;
new PMMLEncogNeuralNetworkModel().adaptMLModelToPMML((BasicNetwork) basicML, nnPmmlModel);
nnPmmlModel.withOutput(createNormalizedOutput(id));
return true;
}
} | [
"public",
"class",
"NNSpecifCreator",
"extends",
"AbstractSpecifCreator",
"{",
"@",
"Override",
"public",
"boolean",
"build",
"(",
"BasicML",
"basicML",
",",
"Model",
"model",
")",
"{",
"NeuralNetwork",
"nnPmmlModel",
"=",
"(",
"NeuralNetwork",
")",
"model",
";",
"new",
"PMMLEncogNeuralNetworkModel",
"(",
")",
".",
"adaptMLModelToPMML",
"(",
"(",
"BasicNetwork",
")",
"basicML",
",",
"nnPmmlModel",
")",
";",
"nnPmmlModel",
".",
"withOutput",
"(",
"createNormalizedOutput",
"(",
")",
")",
";",
"return",
"true",
";",
"}",
"@",
"Override",
"public",
"boolean",
"build",
"(",
"BasicML",
"basicML",
",",
"Model",
"model",
",",
"int",
"id",
")",
"{",
"NeuralNetwork",
"nnPmmlModel",
"=",
"(",
"NeuralNetwork",
")",
"model",
";",
"new",
"PMMLEncogNeuralNetworkModel",
"(",
")",
".",
"adaptMLModelToPMML",
"(",
"(",
"BasicNetwork",
")",
"basicML",
",",
"nnPmmlModel",
")",
";",
"nnPmmlModel",
".",
"withOutput",
"(",
"createNormalizedOutput",
"(",
"id",
")",
")",
";",
"return",
"true",
";",
"}",
"}"
] | Created by zhanhu on 3/29/16. | [
"Created",
"by",
"zhanhu",
"on",
"3",
"/",
"29",
"/",
"16",
"."
] | [] | [
{
"param": "AbstractSpecifCreator",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractSpecifCreator",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fee332bd82efd65338acf3305f89c5b348225f5d | mmg-3/OpenOLAT | src/main/java/org/olat/login/oauth/manager/OAuthLoginManagerImpl.java | [
"Apache-2.0"
] | Java | OAuthLoginManagerImpl | /**
*
* Initial date: 9 avr. 2021<br>
* @author srosse, [email protected], http://www.frentix.com
*
*/ | Initial date: 9 avr. | [
"Initial",
"date",
":",
"9",
"avr",
"."
] | @Service
public class OAuthLoginManagerImpl implements OAuthLoginManager {
@Autowired
private UserManager userManager;
@Autowired
private BaseSecurity securityManager;
@Autowired
private OLATAuthManager olatAuthManager;
@Override
public boolean isValid(OAuthUser oauthUser) {
String username = null;
if(StringHelper.containsNonWhitespace(oauthUser.getNickName())) {
username = oauthUser.getNickName();
} else if(StringHelper.containsNonWhitespace(oauthUser.getId())) {
username = oauthUser.getId();
}
TransientIdentity newIdentity = new TransientIdentity();
newIdentity.setName(username);
SyntaxValidator usernameSyntaxValidator = olatAuthManager.createUsernameSytaxValidator();
ValidationResult validationResult = usernameSyntaxValidator.validate(username, newIdentity);
if (!validationResult.isValid()) {
return false;
}
List<UserPropertyHandler> userPropertyHandlers = userManager.getUserPropertyHandlersFor(OAuthRegistrationController.USERPROPERTIES_FORM_IDENTIFIER, false);
for (UserPropertyHandler userPropertyHandler : userPropertyHandlers) {
if (userPropertyHandler == null) continue;
ValidationError error = new ValidationError();
String value = oauthUser.getProperty(userPropertyHandler.getName());
if (!userPropertyHandler.isValidValue(newIdentity.getUser(), value, error, Locale.ENGLISH)) {
return false;
}
}
return true;
}
public Identity createIdentity(OAuthUser oauthUser, String provider) {
String username = null;
if(StringHelper.containsNonWhitespace(oauthUser.getNickName())) {
username = oauthUser.getNickName();
} else if(StringHelper.containsNonWhitespace(oauthUser.getId())) {
username = oauthUser.getId();
}
ValidationError error = new ValidationError();
User newUser = userManager.createUser(null, null, null);
List<UserPropertyHandler> userPropertyHandlers = userManager.getUserPropertyHandlersFor(OAuthRegistrationController.USERPROPERTIES_FORM_IDENTIFIER, false);
for (UserPropertyHandler userPropertyHandler : userPropertyHandlers) {
if (userPropertyHandler == null) continue;
String value = oauthUser.getProperty(userPropertyHandler.getName());
if (userPropertyHandler.isValidValue(newUser, value, error, Locale.ENGLISH)) {
newUser.setProperty(userPropertyHandler.getName(), value);
}
}
// Init preferences
String lang = oauthUser.getLang();
newUser.getPreferences().setLanguage(lang);
newUser.getPreferences().setInformSessionTimeout(true);
String id;
if(StringHelper.containsNonWhitespace(oauthUser.getId())) {
id = oauthUser.getId();
} else if(StringHelper.containsNonWhitespace(oauthUser.getEmail())) {
id = oauthUser.getEmail();
} else {
id = username;
}
return securityManager.createAndPersistIdentityAndUserWithOrganisation(null, username, null, newUser,
provider, BaseSecurity.DEFAULT_ISSUER, id, null, null, null);
}
} | [
"@",
"Service",
"public",
"class",
"OAuthLoginManagerImpl",
"implements",
"OAuthLoginManager",
"{",
"@",
"Autowired",
"private",
"UserManager",
"userManager",
";",
"@",
"Autowired",
"private",
"BaseSecurity",
"securityManager",
";",
"@",
"Autowired",
"private",
"OLATAuthManager",
"olatAuthManager",
";",
"@",
"Override",
"public",
"boolean",
"isValid",
"(",
"OAuthUser",
"oauthUser",
")",
"{",
"String",
"username",
"=",
"null",
";",
"if",
"(",
"StringHelper",
".",
"containsNonWhitespace",
"(",
"oauthUser",
".",
"getNickName",
"(",
")",
")",
")",
"{",
"username",
"=",
"oauthUser",
".",
"getNickName",
"(",
")",
";",
"}",
"else",
"if",
"(",
"StringHelper",
".",
"containsNonWhitespace",
"(",
"oauthUser",
".",
"getId",
"(",
")",
")",
")",
"{",
"username",
"=",
"oauthUser",
".",
"getId",
"(",
")",
";",
"}",
"TransientIdentity",
"newIdentity",
"=",
"new",
"TransientIdentity",
"(",
")",
";",
"newIdentity",
".",
"setName",
"(",
"username",
")",
";",
"SyntaxValidator",
"usernameSyntaxValidator",
"=",
"olatAuthManager",
".",
"createUsernameSytaxValidator",
"(",
")",
";",
"ValidationResult",
"validationResult",
"=",
"usernameSyntaxValidator",
".",
"validate",
"(",
"username",
",",
"newIdentity",
")",
";",
"if",
"(",
"!",
"validationResult",
".",
"isValid",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"List",
"<",
"UserPropertyHandler",
">",
"userPropertyHandlers",
"=",
"userManager",
".",
"getUserPropertyHandlersFor",
"(",
"OAuthRegistrationController",
".",
"USERPROPERTIES_FORM_IDENTIFIER",
",",
"false",
")",
";",
"for",
"(",
"UserPropertyHandler",
"userPropertyHandler",
":",
"userPropertyHandlers",
")",
"{",
"if",
"(",
"userPropertyHandler",
"==",
"null",
")",
"continue",
";",
"ValidationError",
"error",
"=",
"new",
"ValidationError",
"(",
")",
";",
"String",
"value",
"=",
"oauthUser",
".",
"getProperty",
"(",
"userPropertyHandler",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"!",
"userPropertyHandler",
".",
"isValidValue",
"(",
"newIdentity",
".",
"getUser",
"(",
")",
",",
"value",
",",
"error",
",",
"Locale",
".",
"ENGLISH",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"public",
"Identity",
"createIdentity",
"(",
"OAuthUser",
"oauthUser",
",",
"String",
"provider",
")",
"{",
"String",
"username",
"=",
"null",
";",
"if",
"(",
"StringHelper",
".",
"containsNonWhitespace",
"(",
"oauthUser",
".",
"getNickName",
"(",
")",
")",
")",
"{",
"username",
"=",
"oauthUser",
".",
"getNickName",
"(",
")",
";",
"}",
"else",
"if",
"(",
"StringHelper",
".",
"containsNonWhitespace",
"(",
"oauthUser",
".",
"getId",
"(",
")",
")",
")",
"{",
"username",
"=",
"oauthUser",
".",
"getId",
"(",
")",
";",
"}",
"ValidationError",
"error",
"=",
"new",
"ValidationError",
"(",
")",
";",
"User",
"newUser",
"=",
"userManager",
".",
"createUser",
"(",
"null",
",",
"null",
",",
"null",
")",
";",
"List",
"<",
"UserPropertyHandler",
">",
"userPropertyHandlers",
"=",
"userManager",
".",
"getUserPropertyHandlersFor",
"(",
"OAuthRegistrationController",
".",
"USERPROPERTIES_FORM_IDENTIFIER",
",",
"false",
")",
";",
"for",
"(",
"UserPropertyHandler",
"userPropertyHandler",
":",
"userPropertyHandlers",
")",
"{",
"if",
"(",
"userPropertyHandler",
"==",
"null",
")",
"continue",
";",
"String",
"value",
"=",
"oauthUser",
".",
"getProperty",
"(",
"userPropertyHandler",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"userPropertyHandler",
".",
"isValidValue",
"(",
"newUser",
",",
"value",
",",
"error",
",",
"Locale",
".",
"ENGLISH",
")",
")",
"{",
"newUser",
".",
"setProperty",
"(",
"userPropertyHandler",
".",
"getName",
"(",
")",
",",
"value",
")",
";",
"}",
"}",
"String",
"lang",
"=",
"oauthUser",
".",
"getLang",
"(",
")",
";",
"newUser",
".",
"getPreferences",
"(",
")",
".",
"setLanguage",
"(",
"lang",
")",
";",
"newUser",
".",
"getPreferences",
"(",
")",
".",
"setInformSessionTimeout",
"(",
"true",
")",
";",
"String",
"id",
";",
"if",
"(",
"StringHelper",
".",
"containsNonWhitespace",
"(",
"oauthUser",
".",
"getId",
"(",
")",
")",
")",
"{",
"id",
"=",
"oauthUser",
".",
"getId",
"(",
")",
";",
"}",
"else",
"if",
"(",
"StringHelper",
".",
"containsNonWhitespace",
"(",
"oauthUser",
".",
"getEmail",
"(",
")",
")",
")",
"{",
"id",
"=",
"oauthUser",
".",
"getEmail",
"(",
")",
";",
"}",
"else",
"{",
"id",
"=",
"username",
";",
"}",
"return",
"securityManager",
".",
"createAndPersistIdentityAndUserWithOrganisation",
"(",
"null",
",",
"username",
",",
"null",
",",
"newUser",
",",
"provider",
",",
"BaseSecurity",
".",
"DEFAULT_ISSUER",
",",
"id",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}",
"}"
] | Initial date: 9 avr. | [
"Initial",
"date",
":",
"9",
"avr",
"."
] | [
"// Init preferences"
] | [
{
"param": "OAuthLoginManager",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "OAuthLoginManager",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
fee7e8133883ed80381f30dc033365e877c5a23f | enasequence/sequence-validator | src/main/java/uk/ac/ebi/ena/xml/SimpleXmlWriter.java | [
"Apache-2.0"
] | Java | SimpleXmlWriter | /** A simple XML writer.
*/ | A simple XML writer. | [
"A",
"simple",
"XML",
"writer",
"."
] | public class SimpleXmlWriter {
private Writer writer;
private boolean indent;
private boolean noTextElement;
public SimpleXmlWriter(Writer writer) {
this.writer = writer;
indent = true;
noTextElement = false;
}
private static final DateFormat DATE_FORMAT =
new SimpleDateFormat("yyyy-MM-dd");
public boolean isNoTextElement() {
return noTextElement;
}
public void setNoTextElement(boolean noTextElement) {
this.noTextElement = noTextElement;
}
public boolean isIndent() {
return indent;
}
public void setIndent(boolean indent) {
this.indent = indent;
}
private void indent() throws IOException {
for (int i = 0 ; i < elementNames.size() - 1; ++i) {
writer.write("\t");
}
}
private Vector<String> elementNames = new Vector<String>();
private void addElementName(String elementName) {
elementNames.add(elementName);
}
private void removeElementName(String elementName) throws IOException {
assert(elementNames.size() > 0);
assert(elementNames.get(elementNames.size() - 1).equals(elementName));
elementNames.remove(elementNames.size() - 1);
}
private boolean escapeXml = true;
public boolean isEscapeXml() {
return escapeXml;
}
public void setEscapeXml(boolean escapeXml) {
this.escapeXml = escapeXml;
}
private String escapeXml(String xml) throws IOException {
if (xml == null) {
return null;
}
if (!escapeXml) {
return xml;
}
String escapedXml = xml;
escapedXml = escapedXml.replace("&","&");
escapedXml = escapedXml.replace("<","<");
escapedXml = escapedXml.replace(">",">");
escapedXml = escapedXml.replace("\"",""");
escapedXml = escapedXml.replace("'","'");
return escapedXml;
}
public void writeDeclaration() throws IOException {
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
}
public void writeNamespaceAttribute() throws IOException {
writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
}
public void writeNamespaceAttributeForDarwin() throws IOException {
writeAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
writeAttribute("xmlns:dcterms", "http://purl.org/dc/terms/");
writeAttribute("xmlns:dwr", "http://rs.tdwg.org/dwc/xsd/tdwg_dwc_simple.xsd");
writeAttribute("xmlns:dwc", "http://rs.tdwg.org/dwc/terms/");
writeAttribute("version", "1.1");
writeAttribute("targetNamespace", "http://rs.tdwg.org/dwc/xsd/tdwg_dwc_simple.xsd");
}
public void writeAttribute(String attribute, String value) throws IOException {
if (attribute == null || attribute.length() == 0) {
return;
}
if (value == null || value.length() == 0) {
return;
}
writer.write(" ");
writer.write(attribute);
writer.write("=\"");
writer.write(escapeXml(value));
writer.write("\"");
}
public void writeAttribute(String attribute, Boolean value) throws IOException {
if (attribute == null || attribute.length() == 0) {
return;
}
if (value == null || !value) { // Do not show the attribute when value is false.
return;
}
writer.write(" ");
writer.write(attribute);
writer.write("=\"");
if (value) {
writer.write("true");
}
else {
writer.write("false");
}
writer.write("\"");
}
public void writeAttribute(String attribute, Integer value) throws IOException {
if (attribute == null || attribute.length() == 0) {
return;
}
if (value == null) {
return;
}
writer.write(" ");
writer.write(attribute);
writer.write("=\"");
writer.write(value.toString());
writer.write("\"");
}
public void writeAttribute(String attribute, Date value) throws IOException {
if (attribute == null || attribute.length() == 0) {
return;
}
if (value == null) {
return;
}
writer.write(" ");
writer.write(attribute);
writer.write("=\"");
writer.write(DATE_FORMAT.format(value));
writer.write("\"");
}
public void writeAttribute(String attribute, Long value) throws IOException {
if (attribute == null || attribute.length() == 0) {
return;
}
if (value == null) {
return;
}
writer.write(" ");
writer.write(attribute);
writer.write("=\"");
writer.write(value.toString());
writer.write("\"");
}
/**
* Writes '<elementName'.
*/
public void beginElement(String elementName) throws IOException {
addElementName(elementName);
indent();
writer.write("<");
writer.write(elementName);
}
/**
* Writes '>\n'.
*/
public void openElement(String elementName) throws IOException {
assert(elementNames.size() > 0);
assert(elementNames.get(elementNames.size() - 1).equals(elementName));
writer.write(">");
if(indent || noTextElement) {
writer.write("\n");
}
}
/**
* Writes '/>\n'.
*/
public void openCloseElement(String elementName) throws IOException {
assert(elementNames.size() > 0);
assert(elementNames.get(elementNames.size() - 1).equals(elementName));
writer.write("/>\n");
removeElementName(elementName);
}
/**
* Writes </elementName>\n'.
*/
public void closeElement(String elementName) throws IOException {
assert(elementNames.size() > 0);
assert(elementNames.get(elementNames.size() - 1).equals(elementName));
if(indent || noTextElement)
indent();
writer.write("</");
writer.write(elementName);
writer.write(">\n");
removeElementName(elementName);
}
public void writeElementText(String text) throws IOException {
writer.write(escapeXml(text));
}
public void writeElementTextForDarwin(String text) throws IOException {
writer.write(text);
}
/**
* Writes '<elementName><text></elementName>\n'.
*/
public void writeSingleLineTextElement(String elementName, String text) throws IOException {
if (elementName == null || elementName.length() == 0) {
return;
}
if (text == null || text.length() == 0) {
return;
}
addElementName(elementName);
indent();
writer.write("<");
writer.write(elementName);
writer.write(">");
writer.write(escapeXml(text));
writer.write("</");
writer.write(elementName);
writer.write(">\n");
removeElementName(elementName);
}
/**
* Writes '<elementName><text></elementName>\n'.
*/
public void writeSingleLineDateElement(String elementName, Date value) throws IOException {
if (elementName == null || elementName.length() == 0) {
return;
}
if (value == null) {
return;
}
addElementName(elementName);
indent();
writer.write("<");
writer.write(elementName);
writer.write(">");
writer.write(DATE_FORMAT.format(value));
writer.write("</");
writer.write(elementName);
writer.write(">\n");
removeElementName(elementName);
}
/**
* Writes '<elementName>\n<text>\n</elementName>\n'.
*/
public void writeMultiLineTextElement(String elementName, String text) throws IOException {
if (elementName == null || elementName.length() == 0) {
return;
}
if (text == null || text.length() == 0) {
return;
}
addElementName(elementName);
indent();
writer.write("<");
writer.write(elementName);
writer.write(">\n");
writer.write(escapeXml(text));
writer.write("\n");
indent();
writer.write("</");
writer.write(elementName);
writer.write(">\n");
removeElementName(elementName);
}
} | [
"public",
"class",
"SimpleXmlWriter",
"{",
"private",
"Writer",
"writer",
";",
"private",
"boolean",
"indent",
";",
"private",
"boolean",
"noTextElement",
";",
"public",
"SimpleXmlWriter",
"(",
"Writer",
"writer",
")",
"{",
"this",
".",
"writer",
"=",
"writer",
";",
"indent",
"=",
"true",
";",
"noTextElement",
"=",
"false",
";",
"}",
"private",
"static",
"final",
"DateFormat",
"DATE_FORMAT",
"=",
"new",
"SimpleDateFormat",
"(",
"\"",
"yyyy-MM-dd",
"\"",
")",
";",
"public",
"boolean",
"isNoTextElement",
"(",
")",
"{",
"return",
"noTextElement",
";",
"}",
"public",
"void",
"setNoTextElement",
"(",
"boolean",
"noTextElement",
")",
"{",
"this",
".",
"noTextElement",
"=",
"noTextElement",
";",
"}",
"public",
"boolean",
"isIndent",
"(",
")",
"{",
"return",
"indent",
";",
"}",
"public",
"void",
"setIndent",
"(",
"boolean",
"indent",
")",
"{",
"this",
".",
"indent",
"=",
"indent",
";",
"}",
"private",
"void",
"indent",
"(",
")",
"throws",
"IOException",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"elementNames",
".",
"size",
"(",
")",
"-",
"1",
";",
"++",
"i",
")",
"{",
"writer",
".",
"write",
"(",
"\"",
"\\t",
"\"",
")",
";",
"}",
"}",
"private",
"Vector",
"<",
"String",
">",
"elementNames",
"=",
"new",
"Vector",
"<",
"String",
">",
"(",
")",
";",
"private",
"void",
"addElementName",
"(",
"String",
"elementName",
")",
"{",
"elementNames",
".",
"add",
"(",
"elementName",
")",
";",
"}",
"private",
"void",
"removeElementName",
"(",
"String",
"elementName",
")",
"throws",
"IOException",
"{",
"assert",
"(",
"elementNames",
".",
"size",
"(",
")",
">",
"0",
")",
";",
"assert",
"(",
"elementNames",
".",
"get",
"(",
"elementNames",
".",
"size",
"(",
")",
"-",
"1",
")",
".",
"equals",
"(",
"elementName",
")",
")",
";",
"elementNames",
".",
"remove",
"(",
"elementNames",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}",
"private",
"boolean",
"escapeXml",
"=",
"true",
";",
"public",
"boolean",
"isEscapeXml",
"(",
")",
"{",
"return",
"escapeXml",
";",
"}",
"public",
"void",
"setEscapeXml",
"(",
"boolean",
"escapeXml",
")",
"{",
"this",
".",
"escapeXml",
"=",
"escapeXml",
";",
"}",
"private",
"String",
"escapeXml",
"(",
"String",
"xml",
")",
"throws",
"IOException",
"{",
"if",
"(",
"xml",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"escapeXml",
")",
"{",
"return",
"xml",
";",
"}",
"String",
"escapedXml",
"=",
"xml",
";",
"escapedXml",
"=",
"escapedXml",
".",
"replace",
"(",
"\"",
"&",
"\"",
",",
"\"",
"&",
"\"",
")",
";",
"escapedXml",
"=",
"escapedXml",
".",
"replace",
"(",
"\"",
"<",
"\"",
",",
"\"",
"<",
"\"",
")",
";",
"escapedXml",
"=",
"escapedXml",
".",
"replace",
"(",
"\"",
">",
"\"",
",",
"\"",
">",
"\"",
")",
";",
"escapedXml",
"=",
"escapedXml",
".",
"replace",
"(",
"\"",
"\\\"",
"\"",
",",
"\"",
""",
"\"",
")",
";",
"escapedXml",
"=",
"escapedXml",
".",
"replace",
"(",
"\"",
"'",
"\"",
",",
"\"",
"'",
"\"",
")",
";",
"return",
"escapedXml",
";",
"}",
"public",
"void",
"writeDeclaration",
"(",
")",
"throws",
"IOException",
"{",
"writer",
".",
"write",
"(",
"\"",
"<?xml version=",
"\\\"",
"1.0",
"\\\"",
" encoding=",
"\\\"",
"UTF-8",
"\\\"",
"?>",
"\\n",
"\"",
")",
";",
"}",
"public",
"void",
"writeNamespaceAttribute",
"(",
")",
"throws",
"IOException",
"{",
"writeAttribute",
"(",
"\"",
"xmlns:xsi",
"\"",
",",
"\"",
"http://www.w3.org/2001/XMLSchema-instance",
"\"",
")",
";",
"}",
"public",
"void",
"writeNamespaceAttributeForDarwin",
"(",
")",
"throws",
"IOException",
"{",
"writeAttribute",
"(",
"\"",
"xmlns:xs",
"\"",
",",
"\"",
"http://www.w3.org/2001/XMLSchema",
"\"",
")",
";",
"writeAttribute",
"(",
"\"",
"xmlns:dcterms",
"\"",
",",
"\"",
"http://purl.org/dc/terms/",
"\"",
")",
";",
"writeAttribute",
"(",
"\"",
"xmlns:dwr",
"\"",
",",
"\"",
"http://rs.tdwg.org/dwc/xsd/tdwg_dwc_simple.xsd",
"\"",
")",
";",
"writeAttribute",
"(",
"\"",
"xmlns:dwc",
"\"",
",",
"\"",
"http://rs.tdwg.org/dwc/terms/",
"\"",
")",
";",
"writeAttribute",
"(",
"\"",
"version",
"\"",
",",
"\"",
"1.1",
"\"",
")",
";",
"writeAttribute",
"(",
"\"",
"targetNamespace",
"\"",
",",
"\"",
"http://rs.tdwg.org/dwc/xsd/tdwg_dwc_simple.xsd",
"\"",
")",
";",
"}",
"public",
"void",
"writeAttribute",
"(",
"String",
"attribute",
",",
"String",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"attribute",
"==",
"null",
"||",
"attribute",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"value",
"==",
"null",
"||",
"value",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"writer",
".",
"write",
"(",
"\"",
" ",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"attribute",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"=",
"\\\"",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"escapeXml",
"(",
"value",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"\\\"",
"\"",
")",
";",
"}",
"public",
"void",
"writeAttribute",
"(",
"String",
"attribute",
",",
"Boolean",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"attribute",
"==",
"null",
"||",
"attribute",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"value",
"==",
"null",
"||",
"!",
"value",
")",
"{",
"return",
";",
"}",
"writer",
".",
"write",
"(",
"\"",
" ",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"attribute",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"=",
"\\\"",
"\"",
")",
";",
"if",
"(",
"value",
")",
"{",
"writer",
".",
"write",
"(",
"\"",
"true",
"\"",
")",
";",
"}",
"else",
"{",
"writer",
".",
"write",
"(",
"\"",
"false",
"\"",
")",
";",
"}",
"writer",
".",
"write",
"(",
"\"",
"\\\"",
"\"",
")",
";",
"}",
"public",
"void",
"writeAttribute",
"(",
"String",
"attribute",
",",
"Integer",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"attribute",
"==",
"null",
"||",
"attribute",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
";",
"}",
"writer",
".",
"write",
"(",
"\"",
" ",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"attribute",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"=",
"\\\"",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"value",
".",
"toString",
"(",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"\\\"",
"\"",
")",
";",
"}",
"public",
"void",
"writeAttribute",
"(",
"String",
"attribute",
",",
"Date",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"attribute",
"==",
"null",
"||",
"attribute",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
";",
"}",
"writer",
".",
"write",
"(",
"\"",
" ",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"attribute",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"=",
"\\\"",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"DATE_FORMAT",
".",
"format",
"(",
"value",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"\\\"",
"\"",
")",
";",
"}",
"public",
"void",
"writeAttribute",
"(",
"String",
"attribute",
",",
"Long",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"attribute",
"==",
"null",
"||",
"attribute",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
";",
"}",
"writer",
".",
"write",
"(",
"\"",
" ",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"attribute",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"=",
"\\\"",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"value",
".",
"toString",
"(",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"\\\"",
"\"",
")",
";",
"}",
"/**\n\t * Writes '<elementName'.\n\t */",
"public",
"void",
"beginElement",
"(",
"String",
"elementName",
")",
"throws",
"IOException",
"{",
"addElementName",
"(",
"elementName",
")",
";",
"indent",
"(",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"<",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"}",
"/**\n\t * Writes '>\\n'.\n\t */",
"public",
"void",
"openElement",
"(",
"String",
"elementName",
")",
"throws",
"IOException",
"{",
"assert",
"(",
"elementNames",
".",
"size",
"(",
")",
">",
"0",
")",
";",
"assert",
"(",
"elementNames",
".",
"get",
"(",
"elementNames",
".",
"size",
"(",
")",
"-",
"1",
")",
".",
"equals",
"(",
"elementName",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\"",
")",
";",
"if",
"(",
"indent",
"||",
"noTextElement",
")",
"{",
"writer",
".",
"write",
"(",
"\"",
"\\n",
"\"",
")",
";",
"}",
"}",
"/**\n\t * Writes '/>\\n'.\n\t */",
"public",
"void",
"openCloseElement",
"(",
"String",
"elementName",
")",
"throws",
"IOException",
"{",
"assert",
"(",
"elementNames",
".",
"size",
"(",
")",
">",
"0",
")",
";",
"assert",
"(",
"elementNames",
".",
"get",
"(",
"elementNames",
".",
"size",
"(",
")",
"-",
"1",
")",
".",
"equals",
"(",
"elementName",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"/>",
"\\n",
"\"",
")",
";",
"removeElementName",
"(",
"elementName",
")",
";",
"}",
"/**\n\t * Writes </elementName>\\n'.\n\t */",
"public",
"void",
"closeElement",
"(",
"String",
"elementName",
")",
"throws",
"IOException",
"{",
"assert",
"(",
"elementNames",
".",
"size",
"(",
")",
">",
"0",
")",
";",
"assert",
"(",
"elementNames",
".",
"get",
"(",
"elementNames",
".",
"size",
"(",
")",
"-",
"1",
")",
".",
"equals",
"(",
"elementName",
")",
")",
";",
"if",
"(",
"indent",
"||",
"noTextElement",
")",
"indent",
"(",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"</",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\\n",
"\"",
")",
";",
"removeElementName",
"(",
"elementName",
")",
";",
"}",
"public",
"void",
"writeElementText",
"(",
"String",
"text",
")",
"throws",
"IOException",
"{",
"writer",
".",
"write",
"(",
"escapeXml",
"(",
"text",
")",
")",
";",
"}",
"public",
"void",
"writeElementTextForDarwin",
"(",
"String",
"text",
")",
"throws",
"IOException",
"{",
"writer",
".",
"write",
"(",
"text",
")",
";",
"}",
"/**\n\t * Writes '<elementName><text></elementName>\\n'.\n\t */",
"public",
"void",
"writeSingleLineTextElement",
"(",
"String",
"elementName",
",",
"String",
"text",
")",
"throws",
"IOException",
"{",
"if",
"(",
"elementName",
"==",
"null",
"||",
"elementName",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"addElementName",
"(",
"elementName",
")",
";",
"indent",
"(",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"<",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"escapeXml",
"(",
"text",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"</",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\\n",
"\"",
")",
";",
"removeElementName",
"(",
"elementName",
")",
";",
"}",
"/**\n\t * Writes '<elementName><text></elementName>\\n'.\n\t */",
"public",
"void",
"writeSingleLineDateElement",
"(",
"String",
"elementName",
",",
"Date",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"elementName",
"==",
"null",
"||",
"elementName",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
";",
"}",
"addElementName",
"(",
"elementName",
")",
";",
"indent",
"(",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"<",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"DATE_FORMAT",
".",
"format",
"(",
"value",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"</",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\\n",
"\"",
")",
";",
"removeElementName",
"(",
"elementName",
")",
";",
"}",
"/**\n\t * Writes '<elementName>\\n<text>\\n</elementName>\\n'.\n\t */",
"public",
"void",
"writeMultiLineTextElement",
"(",
"String",
"elementName",
",",
"String",
"text",
")",
"throws",
"IOException",
"{",
"if",
"(",
"elementName",
"==",
"null",
"||",
"elementName",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
";",
"}",
"addElementName",
"(",
"elementName",
")",
";",
"indent",
"(",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"<",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\\n",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"escapeXml",
"(",
"text",
")",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"\\n",
"\"",
")",
";",
"indent",
"(",
")",
";",
"writer",
".",
"write",
"(",
"\"",
"</",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"elementName",
")",
";",
"writer",
".",
"write",
"(",
"\"",
">",
"\\n",
"\"",
")",
";",
"removeElementName",
"(",
"elementName",
")",
";",
"}",
"}"
] | A simple XML writer. | [
"A",
"simple",
"XML",
"writer",
"."
] | [
"// Do not show the attribute when value is false."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b973608bd72269e4813c33c5626ce7707df617fc | alexandra-bucur/egeria-connector-ibm-information-server | igc-clientlibrary/src/main/java/org/odpi/egeria/connectors/ibm/igc/clientlibrary/model/base/ParameterSet.java | [
"Apache-2.0"
] | Java | ParameterSet | /**
* POJO for the {@code parameter_set} asset type in IGC, displayed as '{@literal Parameter Set}' in the IGC UI.
* <br><br>
* (this code has been created based on out-of-the-box IGC metadata types.
* If modifications are needed, eg. to handle custom attributes,
* extending from this class in your own custom class is the best approach.)
*/ | POJO for the parameter_set asset type in IGC, displayed as ' Parameter Set' in the IGC UI.
(this code has been created based on out-of-the-box IGC metadata types.
If modifications are needed, eg. to handle custom attributes,
extending from this class in your own custom class is the best approach.) | [
"POJO",
"for",
"the",
"parameter_set",
"asset",
"type",
"in",
"IGC",
"displayed",
"as",
"'",
"Parameter",
"Set",
"'",
"in",
"the",
"IGC",
"UI",
".",
"(",
"this",
"code",
"has",
"been",
"created",
"based",
"on",
"out",
"-",
"of",
"-",
"the",
"-",
"box",
"IGC",
"metadata",
"types",
".",
"If",
"modifications",
"are",
"needed",
"eg",
".",
"to",
"handle",
"custom",
"attributes",
"extending",
"from",
"this",
"class",
"in",
"your",
"own",
"custom",
"class",
"is",
"the",
"best",
"approach",
".",
")"
] | @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.EXISTING_PROPERTY, property="_type", visible=true, defaultImpl=ParameterSet.class)
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonTypeName("parameter_set")
public class ParameterSet extends InformationAsset {
@JsonProperty("jobs")
protected ItemList<Jobdef> jobs;
@JsonProperty("parameters")
protected ItemList<DsparameterSet> parameters;
@JsonProperty("transformation_project")
protected TransformationProject transformationProject;
/**
* Retrieve the {@code jobs} property (displayed as '{@literal Jobs}') of the object.
* @return {@code ItemList<Jobdef>}
*/
@JsonProperty("jobs")
public ItemList<Jobdef> getJobs() { return this.jobs; }
/**
* Set the {@code jobs} property (displayed as {@code Jobs}) of the object.
* @param jobs the value to set
*/
@JsonProperty("jobs")
public void setJobs(ItemList<Jobdef> jobs) { this.jobs = jobs; }
/**
* Retrieve the {@code parameters} property (displayed as '{@literal Parameters}') of the object.
* @return {@code ItemList<DsparameterSet>}
*/
@JsonProperty("parameters")
public ItemList<DsparameterSet> getParameters() { return this.parameters; }
/**
* Set the {@code parameters} property (displayed as {@code Parameters}) of the object.
* @param parameters the value to set
*/
@JsonProperty("parameters")
public void setParameters(ItemList<DsparameterSet> parameters) { this.parameters = parameters; }
/**
* Retrieve the {@code transformation_project} property (displayed as '{@literal Transformation Project}') of the object.
* @return {@code TransformationProject}
*/
@JsonProperty("transformation_project")
public TransformationProject getTransformationProject() { return this.transformationProject; }
/**
* Set the {@code transformation_project} property (displayed as {@code Transformation Project}) of the object.
* @param transformationProject the value to set
*/
@JsonProperty("transformation_project")
public void setTransformationProject(TransformationProject transformationProject) { this.transformationProject = transformationProject; }
} | [
"@",
"JsonTypeInfo",
"(",
"use",
"=",
"JsonTypeInfo",
".",
"Id",
".",
"NAME",
",",
"include",
"=",
"JsonTypeInfo",
".",
"As",
".",
"EXISTING_PROPERTY",
",",
"property",
"=",
"\"",
"_type",
"\"",
",",
"visible",
"=",
"true",
",",
"defaultImpl",
"=",
"ParameterSet",
".",
"class",
")",
"@",
"JsonAutoDetect",
"(",
"getterVisibility",
"=",
"PUBLIC_ONLY",
",",
"setterVisibility",
"=",
"PUBLIC_ONLY",
",",
"fieldVisibility",
"=",
"NONE",
")",
"@",
"JsonInclude",
"(",
"JsonInclude",
".",
"Include",
".",
"NON_NULL",
")",
"@",
"JsonIgnoreProperties",
"(",
"ignoreUnknown",
"=",
"true",
")",
"@",
"JsonTypeName",
"(",
"\"",
"parameter_set",
"\"",
")",
"public",
"class",
"ParameterSet",
"extends",
"InformationAsset",
"{",
"@",
"JsonProperty",
"(",
"\"",
"jobs",
"\"",
")",
"protected",
"ItemList",
"<",
"Jobdef",
">",
"jobs",
";",
"@",
"JsonProperty",
"(",
"\"",
"parameters",
"\"",
")",
"protected",
"ItemList",
"<",
"DsparameterSet",
">",
"parameters",
";",
"@",
"JsonProperty",
"(",
"\"",
"transformation_project",
"\"",
")",
"protected",
"TransformationProject",
"transformationProject",
";",
"/**\n * Retrieve the {@code jobs} property (displayed as '{@literal Jobs}') of the object.\n * @return {@code ItemList<Jobdef>}\n */",
"@",
"JsonProperty",
"(",
"\"",
"jobs",
"\"",
")",
"public",
"ItemList",
"<",
"Jobdef",
">",
"getJobs",
"(",
")",
"{",
"return",
"this",
".",
"jobs",
";",
"}",
"/**\n * Set the {@code jobs} property (displayed as {@code Jobs}) of the object.\n * @param jobs the value to set\n */",
"@",
"JsonProperty",
"(",
"\"",
"jobs",
"\"",
")",
"public",
"void",
"setJobs",
"(",
"ItemList",
"<",
"Jobdef",
">",
"jobs",
")",
"{",
"this",
".",
"jobs",
"=",
"jobs",
";",
"}",
"/**\n * Retrieve the {@code parameters} property (displayed as '{@literal Parameters}') of the object.\n * @return {@code ItemList<DsparameterSet>}\n */",
"@",
"JsonProperty",
"(",
"\"",
"parameters",
"\"",
")",
"public",
"ItemList",
"<",
"DsparameterSet",
">",
"getParameters",
"(",
")",
"{",
"return",
"this",
".",
"parameters",
";",
"}",
"/**\n * Set the {@code parameters} property (displayed as {@code Parameters}) of the object.\n * @param parameters the value to set\n */",
"@",
"JsonProperty",
"(",
"\"",
"parameters",
"\"",
")",
"public",
"void",
"setParameters",
"(",
"ItemList",
"<",
"DsparameterSet",
">",
"parameters",
")",
"{",
"this",
".",
"parameters",
"=",
"parameters",
";",
"}",
"/**\n * Retrieve the {@code transformation_project} property (displayed as '{@literal Transformation Project}') of the object.\n * @return {@code TransformationProject}\n */",
"@",
"JsonProperty",
"(",
"\"",
"transformation_project",
"\"",
")",
"public",
"TransformationProject",
"getTransformationProject",
"(",
")",
"{",
"return",
"this",
".",
"transformationProject",
";",
"}",
"/**\n * Set the {@code transformation_project} property (displayed as {@code Transformation Project}) of the object.\n * @param transformationProject the value to set\n */",
"@",
"JsonProperty",
"(",
"\"",
"transformation_project",
"\"",
")",
"public",
"void",
"setTransformationProject",
"(",
"TransformationProject",
"transformationProject",
")",
"{",
"this",
".",
"transformationProject",
"=",
"transformationProject",
";",
"}",
"}"
] | POJO for the {@code parameter_set} asset type in IGC, displayed as '{@literal Parameter Set}' in the IGC UI. | [
"POJO",
"for",
"the",
"{",
"@code",
"parameter_set",
"}",
"asset",
"type",
"in",
"IGC",
"displayed",
"as",
"'",
"{",
"@literal",
"Parameter",
"Set",
"}",
"'",
"in",
"the",
"IGC",
"UI",
"."
] | [] | [
{
"param": "InformationAsset",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "InformationAsset",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b97369f6acc5ff0612fd84d598a274c4101f5ecf | valb3r/datasafe | datasafe-directory/datasafe-directory-impl/src/main/java/de/adorsys/datasafe/directory/impl/profile/dfs/BucketAccessServiceImpl.java | [
"Apache-2.0"
] | Java | BucketAccessServiceImpl | /**
* Specifies how to access desired user resource (example: private bucket). By default is no-op - simply wraps
* resource into {@link AbsoluteLocation}
*/ | Specifies how to access desired user resource (example: private bucket). By default is no-op - simply wraps
resource into AbsoluteLocation | [
"Specifies",
"how",
"to",
"access",
"desired",
"user",
"resource",
"(",
"example",
":",
"private",
"bucket",
")",
".",
"By",
"default",
"is",
"no",
"-",
"op",
"-",
"simply",
"wraps",
"resource",
"into",
"AbsoluteLocation"
] | @Slf4j
public class BucketAccessServiceImpl implements BucketAccessService {
@Inject
public BucketAccessServiceImpl() {
}
/**
* Do nothing, just wrap, real use case would be to plug user credentials to access bucket.
*/
@Override
public AbsoluteLocation<PrivateResource> privateAccessFor(UserIDAuth user, PrivateResource resource) {
log.debug("get private access for user {} and bucket {}", user, resource);
return new AbsoluteLocation<>(resource);
}
/**
* Do nothing, just wrap, real use case would be to plug user credentials to access bucket.
*/
@Override
public AbsoluteLocation<PublicResource> publicAccessFor(UserID user, PublicResource resource) {
log.debug("get public access for user {} and bucket {}", user, resource.location());
return new AbsoluteLocation<>(resource);
}
} | [
"@",
"Slf4j",
"public",
"class",
"BucketAccessServiceImpl",
"implements",
"BucketAccessService",
"{",
"@",
"Inject",
"public",
"BucketAccessServiceImpl",
"(",
")",
"{",
"}",
"/**\n * Do nothing, just wrap, real use case would be to plug user credentials to access bucket.\n */",
"@",
"Override",
"public",
"AbsoluteLocation",
"<",
"PrivateResource",
">",
"privateAccessFor",
"(",
"UserIDAuth",
"user",
",",
"PrivateResource",
"resource",
")",
"{",
"log",
".",
"debug",
"(",
"\"",
"get private access for user {} and bucket {}",
"\"",
",",
"user",
",",
"resource",
")",
";",
"return",
"new",
"AbsoluteLocation",
"<",
">",
"(",
"resource",
")",
";",
"}",
"/**\n * Do nothing, just wrap, real use case would be to plug user credentials to access bucket.\n */",
"@",
"Override",
"public",
"AbsoluteLocation",
"<",
"PublicResource",
">",
"publicAccessFor",
"(",
"UserID",
"user",
",",
"PublicResource",
"resource",
")",
"{",
"log",
".",
"debug",
"(",
"\"",
"get public access for user {} and bucket {}",
"\"",
",",
"user",
",",
"resource",
".",
"location",
"(",
")",
")",
";",
"return",
"new",
"AbsoluteLocation",
"<",
">",
"(",
"resource",
")",
";",
"}",
"}"
] | Specifies how to access desired user resource (example: private bucket). | [
"Specifies",
"how",
"to",
"access",
"desired",
"user",
"resource",
"(",
"example",
":",
"private",
"bucket",
")",
"."
] | [] | [
{
"param": "BucketAccessService",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "BucketAccessService",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b973803f31829b4dc29092d687eca713b432206e | astrowq/DSpace | dspace-api/src/main/java/org/dspace/app/mediafilter/MediaFilterServiceImpl.java | [
"BSD-3-Clause"
] | Java | MediaFilterServiceImpl | /**
* MediaFilterManager is the class that invokes the media/format filters over the
* repository's content. A few command line flags affect the operation of the
* MFM: -v verbose outputs all extracted text to STDOUT; -f force forces all
* bitstreams to be processed, even if they have been before; -n noindex does not
* recreate index after processing bitstreams; -i [identifier] limits processing
* scope to a community, collection or item; and -m [max] limits processing to a
* maximum number of items.
*/ | MediaFilterManager is the class that invokes the media/format filters over the
repository's content. | [
"MediaFilterManager",
"is",
"the",
"class",
"that",
"invokes",
"the",
"media",
"/",
"format",
"filters",
"over",
"the",
"repository",
"'",
"s",
"content",
"."
] | public class MediaFilterServiceImpl implements MediaFilterService, InitializingBean {
@Autowired(required = true)
protected AuthorizeService authorizeService;
@Autowired(required = true)
protected BitstreamFormatService bitstreamFormatService;
@Autowired(required = true)
protected BitstreamService bitstreamService;
@Autowired(required = true)
protected BundleService bundleService;
@Autowired(required = true)
protected CollectionService collectionService;
@Autowired(required = true)
protected CommunityService communityService;
@Autowired(required = true)
protected GroupService groupService;
@Autowired(required = true)
protected ItemService itemService;
@Autowired(required = true)
protected ConfigurationService configurationService;
protected int max2Process = Integer.MAX_VALUE; // maximum number items to process
protected int processed = 0; // number items processed
protected Item currentItem = null; // current item being processed
protected List<FormatFilter> filterClasses = null;
protected Map<String, List<String>> filterFormats = new HashMap<>();
protected List<String> skipList = null; //list of identifiers to skip during processing
protected final List<String> publicFiltersClasses = new ArrayList<>();
protected boolean isVerbose = false;
protected boolean isQuiet = false;
protected boolean isForce = false; // default to not forced
protected MediaFilterServiceImpl() {
}
@Override
public void afterPropertiesSet() throws Exception {
String[] publicPermissionFilters = configurationService
.getArrayProperty("filter.org.dspace.app.mediafilter.publicPermission");
if (publicPermissionFilters != null) {
for (String filter : publicPermissionFilters) {
publicFiltersClasses.add(filter.trim());
}
}
}
@Override
public void applyFiltersAllItems(Context context) throws Exception {
if (skipList != null) {
//if a skip-list exists, we need to filter community-by-community
//so we can respect what is in the skip-list
List<Community> topLevelCommunities = communityService.findAllTop(context);
for (Community topLevelCommunity : topLevelCommunities) {
applyFiltersCommunity(context, topLevelCommunity);
}
} else {
//otherwise, just find every item and process
Iterator<Item> itemIterator = itemService.findAll(context);
while (itemIterator.hasNext() && processed < max2Process) {
applyFiltersItem(context, itemIterator.next());
}
}
}
@Override
public void applyFiltersCommunity(Context context, Community community)
throws Exception { //only apply filters if community not in skip-list
if (!inSkipList(community.getHandle())) {
List<Community> subcommunities = community.getSubcommunities();
for (Community subcommunity : subcommunities) {
applyFiltersCommunity(context, subcommunity);
}
List<Collection> collections = community.getCollections();
for (Collection collection : collections) {
applyFiltersCollection(context, collection);
}
}
}
@Override
public void applyFiltersCollection(Context context, Collection collection)
throws Exception {
//only apply filters if collection not in skip-list
if (!inSkipList(collection.getHandle())) {
Iterator<Item> itemIterator = itemService.findAllByCollection(context, collection);
while (itemIterator.hasNext() && processed < max2Process) {
applyFiltersItem(context, itemIterator.next());
}
}
}
@Override
public void applyFiltersItem(Context c, Item item) throws Exception {
//only apply filters if item not in skip-list
if (!inSkipList(item.getHandle())) {
//cache this item in MediaFilterManager
//so it can be accessed by MediaFilters as necessary
currentItem = item;
if (filterItem(c, item)) {
// increment processed count
++processed;
}
// clear item objects from context cache and internal cache
c.uncacheEntity(currentItem);
currentItem = null;
}
}
@Override
public boolean filterItem(Context context, Item myItem) throws Exception {
// get 'original' bundles
List<Bundle> myBundles = itemService.getBundles(myItem, "ORIGINAL");
boolean done = false;
for (Bundle myBundle : myBundles) {
// now look at all of the bitstreams
List<Bitstream> myBitstreams = myBundle.getBitstreams();
for (Bitstream myBitstream : myBitstreams) {
done |= filterBitstream(context, myItem, myBitstream);
}
}
return done;
}
@Override
public boolean filterBitstream(Context context, Item myItem,
Bitstream myBitstream) throws Exception {
boolean filtered = false;
// iterate through filter classes. A single format may be actioned
// by more than one filter
for (FormatFilter filterClass : filterClasses) {
//List fmts = (List)filterFormats.get(filterClasses[i].getClass().getName());
String pluginName = null;
//if this filter class is a SelfNamedPlugin,
//its list of supported formats is different for
//differently named "plugin"
if (SelfNamedPlugin.class.isAssignableFrom(filterClass.getClass())) {
//get plugin instance name for this media filter
pluginName = ((SelfNamedPlugin) filterClass).getPluginInstanceName();
}
//Get list of supported formats for the filter (and possibly named plugin)
//For SelfNamedPlugins, map key is:
// <class-name><separator><plugin-name>
//For other MediaFilters, map key is just:
// <class-name>
List<String> fmts = filterFormats.get(filterClass.getClass().getName() +
(pluginName != null ? FILTER_PLUGIN_SEPARATOR + pluginName : ""));
if (fmts.contains(myBitstream.getFormat(context).getShortDescription())) {
try {
// only update item if bitstream not skipped
if (processBitstream(context, myItem, myBitstream, filterClass)) {
itemService.update(context, myItem); // Make sure new bitstream has a sequence
// number
filtered = true;
}
} catch (Exception e) {
String handle = myItem.getHandle();
List<Bundle> bundles = myBitstream.getBundles();
long size = myBitstream.getSizeBytes();
String checksum = myBitstream.getChecksum() + " (" + myBitstream.getChecksumAlgorithm() + ")";
int assetstore = myBitstream.getStoreNumber();
// Printout helpful information to find the errored bitstream.
System.out.println("ERROR filtering, skipping bitstream:\n");
System.out.println("\tItem Handle: " + handle);
for (Bundle bundle : bundles) {
System.out.println("\tBundle Name: " + bundle.getName());
}
System.out.println("\tFile Size: " + size);
System.out.println("\tChecksum: " + checksum);
System.out.println("\tAsset Store: " + assetstore);
System.out.println(e);
e.printStackTrace();
}
} else if (filterClass instanceof SelfRegisterInputFormats) {
// Filter implements self registration, so check to see if it should be applied
// given the formats it claims to support
SelfRegisterInputFormats srif = (SelfRegisterInputFormats) filterClass;
boolean applyFilter = false;
// Check MIME type
String[] mimeTypes = srif.getInputMIMETypes();
if (mimeTypes != null) {
for (String mimeType : mimeTypes) {
if (mimeType.equalsIgnoreCase(myBitstream.getFormat(context).getMIMEType())) {
applyFilter = true;
}
}
}
// Check description
if (!applyFilter) {
String[] descriptions = srif.getInputDescriptions();
if (descriptions != null) {
for (String desc : descriptions) {
if (desc.equalsIgnoreCase(myBitstream.getFormat(context).getShortDescription())) {
applyFilter = true;
}
}
}
}
// Check extensions
if (!applyFilter) {
String[] extensions = srif.getInputExtensions();
if (extensions != null) {
for (String ext : extensions) {
List<String> formatExtensions = myBitstream.getFormat(context).getExtensions();
if (formatExtensions != null && formatExtensions.contains(ext)) {
applyFilter = true;
}
}
}
}
// Filter claims to handle this type of file, so attempt to apply it
if (applyFilter) {
try {
// only update item if bitstream not skipped
if (processBitstream(context, myItem, myBitstream, filterClass)) {
itemService.update(context, myItem); // Make sure new bitstream has a sequence
// number
filtered = true;
}
} catch (Exception e) {
System.out.println("ERROR filtering, skipping bitstream #"
+ myBitstream.getID() + " " + e);
e.printStackTrace();
}
}
}
}
return filtered;
}
@Override
public boolean processBitstream(Context context, Item item, Bitstream source, FormatFilter formatFilter)
throws Exception {
//do pre-processing of this bitstream, and if it fails, skip this bitstream!
if (!formatFilter.preProcessBitstream(context, item, source, isVerbose)) {
return false;
}
boolean overWrite = isForce;
// get bitstream filename, calculate destination filename
String newName = formatFilter.getFilteredName(source.getName());
// check if destination bitstream exists
Bundle existingBundle = null;
Bitstream existingBitstream = null;
List<Bundle> bundles = itemService.getBundles(item, formatFilter.getBundleName());
if (bundles.size() > 0) {
// only finds the last match (FIXME?)
for (Bundle bundle : bundles) {
List<Bitstream> bitstreams = bundle.getBitstreams();
for (Bitstream bitstream : bitstreams) {
if (bitstream.getName().trim().equals(newName.trim())) {
existingBundle = bundle;
existingBitstream = bitstream;
}
}
}
}
// if exists and overwrite = false, exit
if (!overWrite && (existingBitstream != null)) {
if (!isQuiet) {
System.out.println("SKIPPED: bitstream " + source.getID()
+ " (item: " + item.getHandle() + ") because '" + newName + "' already exists");
}
return false;
}
if (isVerbose) {
System.out.println("PROCESSING: bitstream " + source.getID()
+ " (item: " + item.getHandle() + ")");
}
System.out.println("File: " + newName);
// start filtering of the bitstream, using try with resource to close all InputStreams properly
try (
// get the source stream
InputStream srcStream = bitstreamService.retrieve(context, source);
// filter the source stream to produce the destination stream
// this is the hard work, check for OutOfMemoryErrors at the end of the try clause.
InputStream destStream = formatFilter.getDestinationStream(item, srcStream, isVerbose);
) {
if (destStream == null) {
if (!isQuiet) {
System.out.println("SKIPPED: bitstream " + source.getID()
+ " (item: " + item.getHandle() + ") because filtering was unsuccessful");
}
return false;
}
Bundle targetBundle; // bundle we're modifying
if (bundles.size() < 1) {
// create new bundle if needed
targetBundle = bundleService.create(context, item, formatFilter.getBundleName());
} else {
// take the first match as we already looked out for the correct bundle name
targetBundle = bundles.get(0);
}
// create bitstream to store the filter result
Bitstream b = bitstreamService.create(context, targetBundle, destStream);
// set the name, source and description of the bitstream
b.setName(context, newName);
b.setSource(context, "Written by FormatFilter " + formatFilter.getClass().getName() +
" on " + DCDate.getCurrent() + " (GMT).");
b.setDescription(context, formatFilter.getDescription());
// Set the format of the bitstream
BitstreamFormat bf = bitstreamFormatService.findByShortDescription(context,
formatFilter.getFormatString());
bitstreamService.setFormat(context, b, bf);
bitstreamService.update(context, b);
//Set permissions on the derivative bitstream
//- First remove any existing policies
authorizeService.removeAllPolicies(context, b);
//- Determine if this is a public-derivative format
if (publicFiltersClasses.contains(formatFilter.getClass().getSimpleName())) {
//- Set derivative bitstream to be publicly accessible
Group anonymous = groupService.findByName(context, Group.ANONYMOUS);
authorizeService.addPolicy(context, b, Constants.READ, anonymous);
} else {
//- Inherit policies from the source bitstream
authorizeService.inheritPolicies(context, source, b);
}
//do post-processing of the generated bitstream
formatFilter.postProcessBitstream(context, item, b);
} catch (OutOfMemoryError oome) {
System.out.println("!!! OutOfMemoryError !!!");
}
// fixme - set date?
// we are overwriting, so remove old bitstream
if (existingBitstream != null) {
bundleService.removeBitstream(context, existingBundle, existingBitstream);
}
if (!isQuiet) {
System.out.println("FILTERED: bitstream " + source.getID()
+ " (item: " + item.getHandle() + ") and created '" + newName + "'");
}
return true;
}
@Override
public Item getCurrentItem() {
return currentItem;
}
@Override
public boolean inSkipList(String identifier) {
if (skipList != null && skipList.contains(identifier)) {
if (!isQuiet) {
System.out.println("SKIP-LIST: skipped bitstreams within identifier " + identifier);
}
return true;
} else {
return false;
}
}
@Override
public void setVerbose(boolean isVerbose) {
this.isVerbose = isVerbose;
}
@Override
public void setQuiet(boolean isQuiet) {
this.isQuiet = isQuiet;
}
@Override
public void setForce(boolean isForce) {
this.isForce = isForce;
}
@Override
public void setMax2Process(int max2Process) {
this.max2Process = max2Process;
}
@Override
public void setFilterClasses(List<FormatFilter> filterClasses) {
this.filterClasses = filterClasses;
}
@Override
public void setSkipList(List<String> skipList) {
this.skipList = skipList;
}
@Override
public void setFilterFormats(Map<String, List<String>> filterFormats) {
this.filterFormats = filterFormats;
}
} | [
"public",
"class",
"MediaFilterServiceImpl",
"implements",
"MediaFilterService",
",",
"InitializingBean",
"{",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"AuthorizeService",
"authorizeService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"BitstreamFormatService",
"bitstreamFormatService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"BitstreamService",
"bitstreamService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"BundleService",
"bundleService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"CollectionService",
"collectionService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"CommunityService",
"communityService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"GroupService",
"groupService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"ItemService",
"itemService",
";",
"@",
"Autowired",
"(",
"required",
"=",
"true",
")",
"protected",
"ConfigurationService",
"configurationService",
";",
"protected",
"int",
"max2Process",
"=",
"Integer",
".",
"MAX_VALUE",
";",
"protected",
"int",
"processed",
"=",
"0",
";",
"protected",
"Item",
"currentItem",
"=",
"null",
";",
"protected",
"List",
"<",
"FormatFilter",
">",
"filterClasses",
"=",
"null",
";",
"protected",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"filterFormats",
"=",
"new",
"HashMap",
"<",
">",
"(",
")",
";",
"protected",
"List",
"<",
"String",
">",
"skipList",
"=",
"null",
";",
"protected",
"final",
"List",
"<",
"String",
">",
"publicFiltersClasses",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"protected",
"boolean",
"isVerbose",
"=",
"false",
";",
"protected",
"boolean",
"isQuiet",
"=",
"false",
";",
"protected",
"boolean",
"isForce",
"=",
"false",
";",
"protected",
"MediaFilterServiceImpl",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"afterPropertiesSet",
"(",
")",
"throws",
"Exception",
"{",
"String",
"[",
"]",
"publicPermissionFilters",
"=",
"configurationService",
".",
"getArrayProperty",
"(",
"\"",
"filter.org.dspace.app.mediafilter.publicPermission",
"\"",
")",
";",
"if",
"(",
"publicPermissionFilters",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"filter",
":",
"publicPermissionFilters",
")",
"{",
"publicFiltersClasses",
".",
"add",
"(",
"filter",
".",
"trim",
"(",
")",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"void",
"applyFiltersAllItems",
"(",
"Context",
"context",
")",
"throws",
"Exception",
"{",
"if",
"(",
"skipList",
"!=",
"null",
")",
"{",
"List",
"<",
"Community",
">",
"topLevelCommunities",
"=",
"communityService",
".",
"findAllTop",
"(",
"context",
")",
";",
"for",
"(",
"Community",
"topLevelCommunity",
":",
"topLevelCommunities",
")",
"{",
"applyFiltersCommunity",
"(",
"context",
",",
"topLevelCommunity",
")",
";",
"}",
"}",
"else",
"{",
"Iterator",
"<",
"Item",
">",
"itemIterator",
"=",
"itemService",
".",
"findAll",
"(",
"context",
")",
";",
"while",
"(",
"itemIterator",
".",
"hasNext",
"(",
")",
"&&",
"processed",
"<",
"max2Process",
")",
"{",
"applyFiltersItem",
"(",
"context",
",",
"itemIterator",
".",
"next",
"(",
")",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"void",
"applyFiltersCommunity",
"(",
"Context",
"context",
",",
"Community",
"community",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"inSkipList",
"(",
"community",
".",
"getHandle",
"(",
")",
")",
")",
"{",
"List",
"<",
"Community",
">",
"subcommunities",
"=",
"community",
".",
"getSubcommunities",
"(",
")",
";",
"for",
"(",
"Community",
"subcommunity",
":",
"subcommunities",
")",
"{",
"applyFiltersCommunity",
"(",
"context",
",",
"subcommunity",
")",
";",
"}",
"List",
"<",
"Collection",
">",
"collections",
"=",
"community",
".",
"getCollections",
"(",
")",
";",
"for",
"(",
"Collection",
"collection",
":",
"collections",
")",
"{",
"applyFiltersCollection",
"(",
"context",
",",
"collection",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"void",
"applyFiltersCollection",
"(",
"Context",
"context",
",",
"Collection",
"collection",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"inSkipList",
"(",
"collection",
".",
"getHandle",
"(",
")",
")",
")",
"{",
"Iterator",
"<",
"Item",
">",
"itemIterator",
"=",
"itemService",
".",
"findAllByCollection",
"(",
"context",
",",
"collection",
")",
";",
"while",
"(",
"itemIterator",
".",
"hasNext",
"(",
")",
"&&",
"processed",
"<",
"max2Process",
")",
"{",
"applyFiltersItem",
"(",
"context",
",",
"itemIterator",
".",
"next",
"(",
")",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"void",
"applyFiltersItem",
"(",
"Context",
"c",
",",
"Item",
"item",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"inSkipList",
"(",
"item",
".",
"getHandle",
"(",
")",
")",
")",
"{",
"currentItem",
"=",
"item",
";",
"if",
"(",
"filterItem",
"(",
"c",
",",
"item",
")",
")",
"{",
"++",
"processed",
";",
"}",
"c",
".",
"uncacheEntity",
"(",
"currentItem",
")",
";",
"currentItem",
"=",
"null",
";",
"}",
"}",
"@",
"Override",
"public",
"boolean",
"filterItem",
"(",
"Context",
"context",
",",
"Item",
"myItem",
")",
"throws",
"Exception",
"{",
"List",
"<",
"Bundle",
">",
"myBundles",
"=",
"itemService",
".",
"getBundles",
"(",
"myItem",
",",
"\"",
"ORIGINAL",
"\"",
")",
";",
"boolean",
"done",
"=",
"false",
";",
"for",
"(",
"Bundle",
"myBundle",
":",
"myBundles",
")",
"{",
"List",
"<",
"Bitstream",
">",
"myBitstreams",
"=",
"myBundle",
".",
"getBitstreams",
"(",
")",
";",
"for",
"(",
"Bitstream",
"myBitstream",
":",
"myBitstreams",
")",
"{",
"done",
"|=",
"filterBitstream",
"(",
"context",
",",
"myItem",
",",
"myBitstream",
")",
";",
"}",
"}",
"return",
"done",
";",
"}",
"@",
"Override",
"public",
"boolean",
"filterBitstream",
"(",
"Context",
"context",
",",
"Item",
"myItem",
",",
"Bitstream",
"myBitstream",
")",
"throws",
"Exception",
"{",
"boolean",
"filtered",
"=",
"false",
";",
"for",
"(",
"FormatFilter",
"filterClass",
":",
"filterClasses",
")",
"{",
"String",
"pluginName",
"=",
"null",
";",
"if",
"(",
"SelfNamedPlugin",
".",
"class",
".",
"isAssignableFrom",
"(",
"filterClass",
".",
"getClass",
"(",
")",
")",
")",
"{",
"pluginName",
"=",
"(",
"(",
"SelfNamedPlugin",
")",
"filterClass",
")",
".",
"getPluginInstanceName",
"(",
")",
";",
"}",
"List",
"<",
"String",
">",
"fmts",
"=",
"filterFormats",
".",
"get",
"(",
"filterClass",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"(",
"pluginName",
"!=",
"null",
"?",
"FILTER_PLUGIN_SEPARATOR",
"+",
"pluginName",
":",
"\"",
"\"",
")",
")",
";",
"if",
"(",
"fmts",
".",
"contains",
"(",
"myBitstream",
".",
"getFormat",
"(",
"context",
")",
".",
"getShortDescription",
"(",
")",
")",
")",
"{",
"try",
"{",
"if",
"(",
"processBitstream",
"(",
"context",
",",
"myItem",
",",
"myBitstream",
",",
"filterClass",
")",
")",
"{",
"itemService",
".",
"update",
"(",
"context",
",",
"myItem",
")",
";",
"filtered",
"=",
"true",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"String",
"handle",
"=",
"myItem",
".",
"getHandle",
"(",
")",
";",
"List",
"<",
"Bundle",
">",
"bundles",
"=",
"myBitstream",
".",
"getBundles",
"(",
")",
";",
"long",
"size",
"=",
"myBitstream",
".",
"getSizeBytes",
"(",
")",
";",
"String",
"checksum",
"=",
"myBitstream",
".",
"getChecksum",
"(",
")",
"+",
"\"",
" (",
"\"",
"+",
"myBitstream",
".",
"getChecksumAlgorithm",
"(",
")",
"+",
"\"",
")",
"\"",
";",
"int",
"assetstore",
"=",
"myBitstream",
".",
"getStoreNumber",
"(",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"ERROR filtering, skipping bitstream:",
"\\n",
"\"",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\\t",
"Item Handle: ",
"\"",
"+",
"handle",
")",
";",
"for",
"(",
"Bundle",
"bundle",
":",
"bundles",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\\t",
"Bundle Name: ",
"\"",
"+",
"bundle",
".",
"getName",
"(",
")",
")",
";",
"}",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\\t",
"File Size: ",
"\"",
"+",
"size",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\\t",
"Checksum: ",
"\"",
"+",
"checksum",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\\t",
"Asset Store: ",
"\"",
"+",
"assetstore",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"e",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"else",
"if",
"(",
"filterClass",
"instanceof",
"SelfRegisterInputFormats",
")",
"{",
"SelfRegisterInputFormats",
"srif",
"=",
"(",
"SelfRegisterInputFormats",
")",
"filterClass",
";",
"boolean",
"applyFilter",
"=",
"false",
";",
"String",
"[",
"]",
"mimeTypes",
"=",
"srif",
".",
"getInputMIMETypes",
"(",
")",
";",
"if",
"(",
"mimeTypes",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"mimeType",
":",
"mimeTypes",
")",
"{",
"if",
"(",
"mimeType",
".",
"equalsIgnoreCase",
"(",
"myBitstream",
".",
"getFormat",
"(",
"context",
")",
".",
"getMIMEType",
"(",
")",
")",
")",
"{",
"applyFilter",
"=",
"true",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"applyFilter",
")",
"{",
"String",
"[",
"]",
"descriptions",
"=",
"srif",
".",
"getInputDescriptions",
"(",
")",
";",
"if",
"(",
"descriptions",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"desc",
":",
"descriptions",
")",
"{",
"if",
"(",
"desc",
".",
"equalsIgnoreCase",
"(",
"myBitstream",
".",
"getFormat",
"(",
"context",
")",
".",
"getShortDescription",
"(",
")",
")",
")",
"{",
"applyFilter",
"=",
"true",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"applyFilter",
")",
"{",
"String",
"[",
"]",
"extensions",
"=",
"srif",
".",
"getInputExtensions",
"(",
")",
";",
"if",
"(",
"extensions",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"ext",
":",
"extensions",
")",
"{",
"List",
"<",
"String",
">",
"formatExtensions",
"=",
"myBitstream",
".",
"getFormat",
"(",
"context",
")",
".",
"getExtensions",
"(",
")",
";",
"if",
"(",
"formatExtensions",
"!=",
"null",
"&&",
"formatExtensions",
".",
"contains",
"(",
"ext",
")",
")",
"{",
"applyFilter",
"=",
"true",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"applyFilter",
")",
"{",
"try",
"{",
"if",
"(",
"processBitstream",
"(",
"context",
",",
"myItem",
",",
"myBitstream",
",",
"filterClass",
")",
")",
"{",
"itemService",
".",
"update",
"(",
"context",
",",
"myItem",
")",
";",
"filtered",
"=",
"true",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"ERROR filtering, skipping bitstream #",
"\"",
"+",
"myBitstream",
".",
"getID",
"(",
")",
"+",
"\"",
" ",
"\"",
"+",
"e",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}",
"}",
"return",
"filtered",
";",
"}",
"@",
"Override",
"public",
"boolean",
"processBitstream",
"(",
"Context",
"context",
",",
"Item",
"item",
",",
"Bitstream",
"source",
",",
"FormatFilter",
"formatFilter",
")",
"throws",
"Exception",
"{",
"if",
"(",
"!",
"formatFilter",
".",
"preProcessBitstream",
"(",
"context",
",",
"item",
",",
"source",
",",
"isVerbose",
")",
")",
"{",
"return",
"false",
";",
"}",
"boolean",
"overWrite",
"=",
"isForce",
";",
"String",
"newName",
"=",
"formatFilter",
".",
"getFilteredName",
"(",
"source",
".",
"getName",
"(",
")",
")",
";",
"Bundle",
"existingBundle",
"=",
"null",
";",
"Bitstream",
"existingBitstream",
"=",
"null",
";",
"List",
"<",
"Bundle",
">",
"bundles",
"=",
"itemService",
".",
"getBundles",
"(",
"item",
",",
"formatFilter",
".",
"getBundleName",
"(",
")",
")",
";",
"if",
"(",
"bundles",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"for",
"(",
"Bundle",
"bundle",
":",
"bundles",
")",
"{",
"List",
"<",
"Bitstream",
">",
"bitstreams",
"=",
"bundle",
".",
"getBitstreams",
"(",
")",
";",
"for",
"(",
"Bitstream",
"bitstream",
":",
"bitstreams",
")",
"{",
"if",
"(",
"bitstream",
".",
"getName",
"(",
")",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"newName",
".",
"trim",
"(",
")",
")",
")",
"{",
"existingBundle",
"=",
"bundle",
";",
"existingBitstream",
"=",
"bitstream",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"overWrite",
"&&",
"(",
"existingBitstream",
"!=",
"null",
")",
")",
"{",
"if",
"(",
"!",
"isQuiet",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"SKIPPED: bitstream ",
"\"",
"+",
"source",
".",
"getID",
"(",
")",
"+",
"\"",
" (item: ",
"\"",
"+",
"item",
".",
"getHandle",
"(",
")",
"+",
"\"",
") because '",
"\"",
"+",
"newName",
"+",
"\"",
"' already exists",
"\"",
")",
";",
"}",
"return",
"false",
";",
"}",
"if",
"(",
"isVerbose",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"PROCESSING: bitstream ",
"\"",
"+",
"source",
".",
"getID",
"(",
")",
"+",
"\"",
" (item: ",
"\"",
"+",
"item",
".",
"getHandle",
"(",
")",
"+",
"\"",
")",
"\"",
")",
";",
"}",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"File: ",
"\"",
"+",
"newName",
")",
";",
"try",
"(",
"InputStream",
"srcStream",
"=",
"bitstreamService",
".",
"retrieve",
"(",
"context",
",",
"source",
")",
";",
"InputStream",
"destStream",
"=",
"formatFilter",
".",
"getDestinationStream",
"(",
"item",
",",
"srcStream",
",",
"isVerbose",
")",
";",
")",
"{",
"if",
"(",
"destStream",
"==",
"null",
")",
"{",
"if",
"(",
"!",
"isQuiet",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"SKIPPED: bitstream ",
"\"",
"+",
"source",
".",
"getID",
"(",
")",
"+",
"\"",
" (item: ",
"\"",
"+",
"item",
".",
"getHandle",
"(",
")",
"+",
"\"",
") because filtering was unsuccessful",
"\"",
")",
";",
"}",
"return",
"false",
";",
"}",
"Bundle",
"targetBundle",
";",
"if",
"(",
"bundles",
".",
"size",
"(",
")",
"<",
"1",
")",
"{",
"targetBundle",
"=",
"bundleService",
".",
"create",
"(",
"context",
",",
"item",
",",
"formatFilter",
".",
"getBundleName",
"(",
")",
")",
";",
"}",
"else",
"{",
"targetBundle",
"=",
"bundles",
".",
"get",
"(",
"0",
")",
";",
"}",
"Bitstream",
"b",
"=",
"bitstreamService",
".",
"create",
"(",
"context",
",",
"targetBundle",
",",
"destStream",
")",
";",
"b",
".",
"setName",
"(",
"context",
",",
"newName",
")",
";",
"b",
".",
"setSource",
"(",
"context",
",",
"\"",
"Written by FormatFilter ",
"\"",
"+",
"formatFilter",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"",
" on ",
"\"",
"+",
"DCDate",
".",
"getCurrent",
"(",
")",
"+",
"\"",
" (GMT).",
"\"",
")",
";",
"b",
".",
"setDescription",
"(",
"context",
",",
"formatFilter",
".",
"getDescription",
"(",
")",
")",
";",
"BitstreamFormat",
"bf",
"=",
"bitstreamFormatService",
".",
"findByShortDescription",
"(",
"context",
",",
"formatFilter",
".",
"getFormatString",
"(",
")",
")",
";",
"bitstreamService",
".",
"setFormat",
"(",
"context",
",",
"b",
",",
"bf",
")",
";",
"bitstreamService",
".",
"update",
"(",
"context",
",",
"b",
")",
";",
"authorizeService",
".",
"removeAllPolicies",
"(",
"context",
",",
"b",
")",
";",
"if",
"(",
"publicFiltersClasses",
".",
"contains",
"(",
"formatFilter",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
")",
"{",
"Group",
"anonymous",
"=",
"groupService",
".",
"findByName",
"(",
"context",
",",
"Group",
".",
"ANONYMOUS",
")",
";",
"authorizeService",
".",
"addPolicy",
"(",
"context",
",",
"b",
",",
"Constants",
".",
"READ",
",",
"anonymous",
")",
";",
"}",
"else",
"{",
"authorizeService",
".",
"inheritPolicies",
"(",
"context",
",",
"source",
",",
"b",
")",
";",
"}",
"formatFilter",
".",
"postProcessBitstream",
"(",
"context",
",",
"item",
",",
"b",
")",
";",
"}",
"catch",
"(",
"OutOfMemoryError",
"oome",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"!!! OutOfMemoryError !!!",
"\"",
")",
";",
"}",
"if",
"(",
"existingBitstream",
"!=",
"null",
")",
"{",
"bundleService",
".",
"removeBitstream",
"(",
"context",
",",
"existingBundle",
",",
"existingBitstream",
")",
";",
"}",
"if",
"(",
"!",
"isQuiet",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"FILTERED: bitstream ",
"\"",
"+",
"source",
".",
"getID",
"(",
")",
"+",
"\"",
" (item: ",
"\"",
"+",
"item",
".",
"getHandle",
"(",
")",
"+",
"\"",
") and created '",
"\"",
"+",
"newName",
"+",
"\"",
"'",
"\"",
")",
";",
"}",
"return",
"true",
";",
"}",
"@",
"Override",
"public",
"Item",
"getCurrentItem",
"(",
")",
"{",
"return",
"currentItem",
";",
"}",
"@",
"Override",
"public",
"boolean",
"inSkipList",
"(",
"String",
"identifier",
")",
"{",
"if",
"(",
"skipList",
"!=",
"null",
"&&",
"skipList",
".",
"contains",
"(",
"identifier",
")",
")",
"{",
"if",
"(",
"!",
"isQuiet",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"SKIP-LIST: skipped bitstreams within identifier ",
"\"",
"+",
"identifier",
")",
";",
"}",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"setVerbose",
"(",
"boolean",
"isVerbose",
")",
"{",
"this",
".",
"isVerbose",
"=",
"isVerbose",
";",
"}",
"@",
"Override",
"public",
"void",
"setQuiet",
"(",
"boolean",
"isQuiet",
")",
"{",
"this",
".",
"isQuiet",
"=",
"isQuiet",
";",
"}",
"@",
"Override",
"public",
"void",
"setForce",
"(",
"boolean",
"isForce",
")",
"{",
"this",
".",
"isForce",
"=",
"isForce",
";",
"}",
"@",
"Override",
"public",
"void",
"setMax2Process",
"(",
"int",
"max2Process",
")",
"{",
"this",
".",
"max2Process",
"=",
"max2Process",
";",
"}",
"@",
"Override",
"public",
"void",
"setFilterClasses",
"(",
"List",
"<",
"FormatFilter",
">",
"filterClasses",
")",
"{",
"this",
".",
"filterClasses",
"=",
"filterClasses",
";",
"}",
"@",
"Override",
"public",
"void",
"setSkipList",
"(",
"List",
"<",
"String",
">",
"skipList",
")",
"{",
"this",
".",
"skipList",
"=",
"skipList",
";",
"}",
"@",
"Override",
"public",
"void",
"setFilterFormats",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"filterFormats",
")",
"{",
"this",
".",
"filterFormats",
"=",
"filterFormats",
";",
"}",
"}"
] | MediaFilterManager is the class that invokes the media/format filters over the
repository's content. | [
"MediaFilterManager",
"is",
"the",
"class",
"that",
"invokes",
"the",
"media",
"/",
"format",
"filters",
"over",
"the",
"repository",
"'",
"s",
"content",
"."
] | [
"// maximum number items to process",
"// number items processed",
"// current item being processed",
"//list of identifiers to skip during processing",
"// default to not forced",
"//if a skip-list exists, we need to filter community-by-community",
"//so we can respect what is in the skip-list",
"//otherwise, just find every item and process",
"//only apply filters if community not in skip-list",
"//only apply filters if collection not in skip-list",
"//only apply filters if item not in skip-list",
"//cache this item in MediaFilterManager",
"//so it can be accessed by MediaFilters as necessary",
"// increment processed count",
"// clear item objects from context cache and internal cache",
"// get 'original' bundles",
"// now look at all of the bitstreams",
"// iterate through filter classes. A single format may be actioned",
"// by more than one filter",
"//List fmts = (List)filterFormats.get(filterClasses[i].getClass().getName());",
"//if this filter class is a SelfNamedPlugin,",
"//its list of supported formats is different for",
"//differently named \"plugin\"",
"//get plugin instance name for this media filter",
"//Get list of supported formats for the filter (and possibly named plugin)",
"//For SelfNamedPlugins, map key is:",
"// <class-name><separator><plugin-name>",
"//For other MediaFilters, map key is just:",
"// <class-name>",
"// only update item if bitstream not skipped",
"// Make sure new bitstream has a sequence",
"// number",
"// Printout helpful information to find the errored bitstream.",
"// Filter implements self registration, so check to see if it should be applied",
"// given the formats it claims to support",
"// Check MIME type",
"// Check description",
"// Check extensions",
"// Filter claims to handle this type of file, so attempt to apply it",
"// only update item if bitstream not skipped",
"// Make sure new bitstream has a sequence",
"// number",
"//do pre-processing of this bitstream, and if it fails, skip this bitstream!",
"// get bitstream filename, calculate destination filename",
"// check if destination bitstream exists",
"// only finds the last match (FIXME?)",
"// if exists and overwrite = false, exit",
"// start filtering of the bitstream, using try with resource to close all InputStreams properly",
"// get the source stream",
"// filter the source stream to produce the destination stream",
"// this is the hard work, check for OutOfMemoryErrors at the end of the try clause.",
"// bundle we're modifying",
"// create new bundle if needed",
"// take the first match as we already looked out for the correct bundle name",
"// create bitstream to store the filter result",
"// set the name, source and description of the bitstream",
"// Set the format of the bitstream",
"//Set permissions on the derivative bitstream",
"//- First remove any existing policies",
"//- Determine if this is a public-derivative format",
"//- Set derivative bitstream to be publicly accessible",
"//- Inherit policies from the source bitstream",
"//do post-processing of the generated bitstream",
"// fixme - set date?",
"// we are overwriting, so remove old bitstream"
] | [
{
"param": "MediaFilterService, InitializingBean",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "MediaFilterService, InitializingBean",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9743ec2afb0a4c9aea4ca9bb2a9803c31d88ad4 | jatanpatel92/NIMS | code/Android Application/src/sen/nims/memberListStatus.java | [
"Apache-2.0"
] | Java | ArrayAdapterMemberListStatus | /***************Array Adapter Member List Status Class**********/ | Array Adapter Member List Status Class | [
"Array",
"Adapter",
"Member",
"List",
"Status",
"Class"
] | public class ArrayAdapterMemberListStatus extends ArrayAdapter<RowMemberListingStatus> {
private final List<RowMemberListingStatus> list;
private NIMSSQLiteOpenHelper helper;
private final Activity context;
private int card_type_index=0;
private String card_type=null;
//Constructor
public ArrayAdapterMemberListStatus(Activity context, List<RowMemberListingStatus> list,String card_type) {
super(context, R.layout.member_list_row_status, list);
if(card_type.equals("Voter"))
card_type_index=8;
else if(card_type.equals("Job"))
card_type_index=7;
else
card_type_index=9;
this.card_type=card_type;
this.context = context;
helper = new NIMSSQLiteOpenHelper(this.context);
this.list = list;
}
//ViewHolder Class
class ViewHolder {
protected TextView text;
protected RadioButton apply;
protected RadioButton issued;
}
//Set the view
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.member_list_row_status, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.apply = (RadioButton) view.findViewById(R.id.apply);
viewHolder.issued = (RadioButton) view.findViewById(R.id.issued);
RadioGroup scheme_status=(RadioGroup)view.findViewById(R.id.types);
scheme_status.setOnCheckedChangeListener (new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Cursor cursorDB_member=helper.getMemInfoCursor();
cursorDB_member=helper.getCursorToName(cursorDB_member,viewHolder.text.getText().toString());
if (checkedId==R.id.apply)
helper.updateMemDatabase("null","null","null","null",0,cursorDB_member.getInt(0),card_type,"APPLIED_NOT_ISSUED");
else
helper.updateMemDatabase("null","null","null","null",0,cursorDB_member.getInt(0),card_type,"ISSUED");
}
});
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.apply.setChecked(list.get(position).isApplySelected());
holder.issued.setChecked(list.get(position).isIssuedSelected());
Cursor cursorDB_member=helper.getMemInfoCursor();
cursorDB_member=helper.getCursorToName(cursorDB_member,list.get(position).getName());
if(cursorDB_member!=null)
{
if(!(cursorDB_member.getString(card_type_index).equals("NOT_APPLIED")))
{
if(cursorDB_member.getString(card_type_index).equals("APPLIED_NOT_ISSUED"))
holder.apply.setChecked(true);
else
holder.issued.setChecked(true);
}
cursorDB_member.close();
}
else
Log.e("Member Cursor","NULL");
return view;
}
} | [
"public",
"class",
"ArrayAdapterMemberListStatus",
"extends",
"ArrayAdapter",
"<",
"RowMemberListingStatus",
">",
"{",
"private",
"final",
"List",
"<",
"RowMemberListingStatus",
">",
"list",
";",
"private",
"NIMSSQLiteOpenHelper",
"helper",
";",
"private",
"final",
"Activity",
"context",
";",
"private",
"int",
"card_type_index",
"=",
"0",
";",
"private",
"String",
"card_type",
"=",
"null",
";",
"public",
"ArrayAdapterMemberListStatus",
"(",
"Activity",
"context",
",",
"List",
"<",
"RowMemberListingStatus",
">",
"list",
",",
"String",
"card_type",
")",
"{",
"super",
"(",
"context",
",",
"R",
".",
"layout",
".",
"member_list_row_status",
",",
"list",
")",
";",
"if",
"(",
"card_type",
".",
"equals",
"(",
"\"",
"Voter",
"\"",
")",
")",
"card_type_index",
"=",
"8",
";",
"else",
"if",
"(",
"card_type",
".",
"equals",
"(",
"\"",
"Job",
"\"",
")",
")",
"card_type_index",
"=",
"7",
";",
"else",
"card_type_index",
"=",
"9",
";",
"this",
".",
"card_type",
"=",
"card_type",
";",
"this",
".",
"context",
"=",
"context",
";",
"helper",
"=",
"new",
"NIMSSQLiteOpenHelper",
"(",
"this",
".",
"context",
")",
";",
"this",
".",
"list",
"=",
"list",
";",
"}",
"class",
"ViewHolder",
"{",
"protected",
"TextView",
"text",
";",
"protected",
"RadioButton",
"apply",
";",
"protected",
"RadioButton",
"issued",
";",
"}",
"@",
"Override",
"public",
"View",
"getView",
"(",
"int",
"position",
",",
"View",
"convertView",
",",
"ViewGroup",
"parent",
")",
"{",
"View",
"view",
"=",
"null",
";",
"if",
"(",
"convertView",
"==",
"null",
")",
"{",
"LayoutInflater",
"inflator",
"=",
"context",
".",
"getLayoutInflater",
"(",
")",
";",
"view",
"=",
"inflator",
".",
"inflate",
"(",
"R",
".",
"layout",
".",
"member_list_row_status",
",",
"null",
")",
";",
"final",
"ViewHolder",
"viewHolder",
"=",
"new",
"ViewHolder",
"(",
")",
";",
"viewHolder",
".",
"text",
"=",
"(",
"TextView",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"label",
")",
";",
"viewHolder",
".",
"apply",
"=",
"(",
"RadioButton",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"apply",
")",
";",
"viewHolder",
".",
"issued",
"=",
"(",
"RadioButton",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"issued",
")",
";",
"RadioGroup",
"scheme_status",
"=",
"(",
"RadioGroup",
")",
"view",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"types",
")",
";",
"scheme_status",
".",
"setOnCheckedChangeListener",
"(",
"new",
"OnCheckedChangeListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onCheckedChanged",
"(",
"RadioGroup",
"group",
",",
"int",
"checkedId",
")",
"{",
"Cursor",
"cursorDB_member",
"=",
"helper",
".",
"getMemInfoCursor",
"(",
")",
";",
"cursorDB_member",
"=",
"helper",
".",
"getCursorToName",
"(",
"cursorDB_member",
",",
"viewHolder",
".",
"text",
".",
"getText",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"checkedId",
"==",
"R",
".",
"id",
".",
"apply",
")",
"helper",
".",
"updateMemDatabase",
"(",
"\"",
"null",
"\"",
",",
"\"",
"null",
"\"",
",",
"\"",
"null",
"\"",
",",
"\"",
"null",
"\"",
",",
"0",
",",
"cursorDB_member",
".",
"getInt",
"(",
"0",
")",
",",
"card_type",
",",
"\"",
"APPLIED_NOT_ISSUED",
"\"",
")",
";",
"else",
"helper",
".",
"updateMemDatabase",
"(",
"\"",
"null",
"\"",
",",
"\"",
"null",
"\"",
",",
"\"",
"null",
"\"",
",",
"\"",
"null",
"\"",
",",
"0",
",",
"cursorDB_member",
".",
"getInt",
"(",
"0",
")",
",",
"card_type",
",",
"\"",
"ISSUED",
"\"",
")",
";",
"}",
"}",
")",
";",
"view",
".",
"setTag",
"(",
"viewHolder",
")",
";",
"}",
"else",
"{",
"view",
"=",
"convertView",
";",
"}",
"ViewHolder",
"holder",
"=",
"(",
"ViewHolder",
")",
"view",
".",
"getTag",
"(",
")",
";",
"holder",
".",
"text",
".",
"setText",
"(",
"list",
".",
"get",
"(",
"position",
")",
".",
"getName",
"(",
")",
")",
";",
"holder",
".",
"apply",
".",
"setChecked",
"(",
"list",
".",
"get",
"(",
"position",
")",
".",
"isApplySelected",
"(",
")",
")",
";",
"holder",
".",
"issued",
".",
"setChecked",
"(",
"list",
".",
"get",
"(",
"position",
")",
".",
"isIssuedSelected",
"(",
")",
")",
";",
"Cursor",
"cursorDB_member",
"=",
"helper",
".",
"getMemInfoCursor",
"(",
")",
";",
"cursorDB_member",
"=",
"helper",
".",
"getCursorToName",
"(",
"cursorDB_member",
",",
"list",
".",
"get",
"(",
"position",
")",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"cursorDB_member",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"(",
"cursorDB_member",
".",
"getString",
"(",
"card_type_index",
")",
".",
"equals",
"(",
"\"",
"NOT_APPLIED",
"\"",
")",
")",
")",
"{",
"if",
"(",
"cursorDB_member",
".",
"getString",
"(",
"card_type_index",
")",
".",
"equals",
"(",
"\"",
"APPLIED_NOT_ISSUED",
"\"",
")",
")",
"holder",
".",
"apply",
".",
"setChecked",
"(",
"true",
")",
";",
"else",
"holder",
".",
"issued",
".",
"setChecked",
"(",
"true",
")",
";",
"}",
"cursorDB_member",
".",
"close",
"(",
")",
";",
"}",
"else",
"Log",
".",
"e",
"(",
"\"",
"Member Cursor",
"\"",
",",
"\"",
"NULL",
"\"",
")",
";",
"return",
"view",
";",
"}",
"}"
] | Array Adapter Member List Status Class | [
"Array",
"Adapter",
"Member",
"List",
"Status",
"Class"
] | [
"//Constructor",
"//ViewHolder Class",
"//Set the view"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9792237fdce53e04c802f8bc0437bfbcb43d863 | quazibd/android-sunshine | app/src/main/java/com/example/android/sunshine/utilities/OpenWeatherJsonUtils.java | [
"Apache-2.0"
] | Java | OpenWeatherJsonUtils | /**
* Utility functions to handle OpenWeatherMap JSON data.
*/ | Utility functions to handle OpenWeatherMap JSON data. | [
"Utility",
"functions",
"to",
"handle",
"OpenWeatherMap",
"JSON",
"data",
"."
] | @RequiresApi(api = Build.VERSION_CODES.O)
public final class OpenWeatherJsonUtils {
/* Location information */
private static final String OWM_CITY = "city";
private static final String OWM_COORD = "coord";
/* Location coordinate */
private static final String OWM_LATITUDE = "lat";
private static final String OWM_LONGITUDE = "lon";
/* Weather information. Each day's forecast info is an element of the "list" array */
private static final String OWM_LIST = "list";
private static final String OWM_PRESSURE = "pressure";
private static final String OWM_HUMIDITY = "humidity";
private static final String OWM_WINDSPEED = "speed";
private static final String OWM_WIND_DIRECTION = "deg";
/* All temperatures are children of the "temp" object */
private static final String OWM_TEMPERATURE = "temp";
/* Max temperature for the day */
private static final String OWM_MAX = "max";
private static final String OWM_MIN = "min";
private static final String OWM_WEATHER = "weather";
private static final String OWM_WEATHER_ID = "id";
private static final String OWM_WEATHER_DESCRIPTION = "description";
private static final String OWM_MESSAGE_CODE = "cod";
/**
* <p>
* This method parses JSON from a web response and returns an array of {@link WeatherData}
* describing the weather over various days from the forecast.
* </p>
*
* @param forecastJsonStr JSON response from server
* @return Array of Strings describing weather data
* @throws JSONException If JSON data cannot be properly parsed
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public static WeatherData[] getWeatherDataFromJson(Context context, String forecastJsonStr)
throws JSONException {
WeatherData[] parsedWeatherData;
JSONObject forecastJson = new JSONObject(forecastJsonStr);
/* Is there an error? */
if (forecastJson.has(OWM_MESSAGE_CODE)) {
int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE);
switch (errorCode) {
case HttpURLConnection.HTTP_OK:
break;
case HttpURLConnection.HTTP_NOT_FOUND:
/* Location invalid */
return null;
default:
/* Server probably down */
return null;
}
}
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
parsedWeatherData = new WeatherData[weatherArray.length()];
for (int i = 0; i < weatherArray.length(); i++) {
parsedWeatherData[i] = getWeatherDataFromJsonObject(weatherArray.getJSONObject(i), i);
}
return parsedWeatherData;
}
private static WeatherData getWeatherDataFromJsonObject(JSONObject dayForecast, int index) throws JSONException {
long localDate = System.currentTimeMillis();
long utcDate = SunshineDateUtils.getUTCDateFromLocal(localDate);
long startDay = SunshineDateUtils.normalizeDate(utcDate);
WeatherData weatherData = new WeatherData();
/*
* We ignore all the datetime values embedded in the JSON and assume that
* the values are returned in-order by day (which is not guaranteed to be correct).
*/
long dateTimeMillis = startDay + SunshineDateUtils.DAY_IN_MILLIS * index;
Date fakeDayForIndex = Date.from(Instant.ofEpochMilli(dateTimeMillis));
weatherData.setDay(fakeDayForIndex);
/*
* Description is in a child array called "weather", which is 1 element long.
* That element also contains a weather code.
*/
JSONObject weatherObject =
dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
weatherData.setWeatherLabel(weatherObject.getString(OWM_WEATHER_DESCRIPTION));
weatherData.setWeatherCode(weatherObject.getInt(OWM_WEATHER_ID));
/*
* Temperatures are sent by Open Weather Map in a child object called "temp".
*
* Editor's Note: Try not to name variables "temp" when working with temperature.
* It confuses everybody. Temp could easily mean any number of things, including
* temperature, temporary and is just a bad variable name.
*/
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
weatherData.setHighTemp(temperatureObject.getDouble(OWM_MAX));
weatherData.setLowTemp(temperatureObject.getDouble(OWM_MIN));
weatherData.setPressure(dayForecast.getDouble(OWM_PRESSURE));
weatherData.setHumidityPercentage(dayForecast.getInt(OWM_HUMIDITY));
weatherData.setWindSpeed(dayForecast.getDouble(OWM_WINDSPEED));
return weatherData;
}
} | [
"@",
"RequiresApi",
"(",
"api",
"=",
"Build",
".",
"VERSION_CODES",
".",
"O",
")",
"public",
"final",
"class",
"OpenWeatherJsonUtils",
"{",
"/* Location information */",
"private",
"static",
"final",
"String",
"OWM_CITY",
"=",
"\"",
"city",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_COORD",
"=",
"\"",
"coord",
"\"",
";",
"/* Location coordinate */",
"private",
"static",
"final",
"String",
"OWM_LATITUDE",
"=",
"\"",
"lat",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_LONGITUDE",
"=",
"\"",
"lon",
"\"",
";",
"/* Weather information. Each day's forecast info is an element of the \"list\" array */",
"private",
"static",
"final",
"String",
"OWM_LIST",
"=",
"\"",
"list",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_PRESSURE",
"=",
"\"",
"pressure",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_HUMIDITY",
"=",
"\"",
"humidity",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_WINDSPEED",
"=",
"\"",
"speed",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_WIND_DIRECTION",
"=",
"\"",
"deg",
"\"",
";",
"/* All temperatures are children of the \"temp\" object */",
"private",
"static",
"final",
"String",
"OWM_TEMPERATURE",
"=",
"\"",
"temp",
"\"",
";",
"/* Max temperature for the day */",
"private",
"static",
"final",
"String",
"OWM_MAX",
"=",
"\"",
"max",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_MIN",
"=",
"\"",
"min",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_WEATHER",
"=",
"\"",
"weather",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_WEATHER_ID",
"=",
"\"",
"id",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_WEATHER_DESCRIPTION",
"=",
"\"",
"description",
"\"",
";",
"private",
"static",
"final",
"String",
"OWM_MESSAGE_CODE",
"=",
"\"",
"cod",
"\"",
";",
"/**\n * <p>\n * This method parses JSON from a web response and returns an array of {@link WeatherData}\n * describing the weather over various days from the forecast.\n * </p>\n *\n * @param forecastJsonStr JSON response from server\n * @return Array of Strings describing weather data\n * @throws JSONException If JSON data cannot be properly parsed\n */",
"@",
"RequiresApi",
"(",
"api",
"=",
"Build",
".",
"VERSION_CODES",
".",
"O",
")",
"public",
"static",
"WeatherData",
"[",
"]",
"getWeatherDataFromJson",
"(",
"Context",
"context",
",",
"String",
"forecastJsonStr",
")",
"throws",
"JSONException",
"{",
"WeatherData",
"[",
"]",
"parsedWeatherData",
";",
"JSONObject",
"forecastJson",
"=",
"new",
"JSONObject",
"(",
"forecastJsonStr",
")",
";",
"/* Is there an error? */",
"if",
"(",
"forecastJson",
".",
"has",
"(",
"OWM_MESSAGE_CODE",
")",
")",
"{",
"int",
"errorCode",
"=",
"forecastJson",
".",
"getInt",
"(",
"OWM_MESSAGE_CODE",
")",
";",
"switch",
"(",
"errorCode",
")",
"{",
"case",
"HttpURLConnection",
".",
"HTTP_OK",
":",
"break",
";",
"case",
"HttpURLConnection",
".",
"HTTP_NOT_FOUND",
":",
"/* Location invalid */",
"return",
"null",
";",
"default",
":",
"/* Server probably down */",
"return",
"null",
";",
"}",
"}",
"JSONArray",
"weatherArray",
"=",
"forecastJson",
".",
"getJSONArray",
"(",
"OWM_LIST",
")",
";",
"parsedWeatherData",
"=",
"new",
"WeatherData",
"[",
"weatherArray",
".",
"length",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"weatherArray",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"parsedWeatherData",
"[",
"i",
"]",
"=",
"getWeatherDataFromJsonObject",
"(",
"weatherArray",
".",
"getJSONObject",
"(",
"i",
")",
",",
"i",
")",
";",
"}",
"return",
"parsedWeatherData",
";",
"}",
"private",
"static",
"WeatherData",
"getWeatherDataFromJsonObject",
"(",
"JSONObject",
"dayForecast",
",",
"int",
"index",
")",
"throws",
"JSONException",
"{",
"long",
"localDate",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"long",
"utcDate",
"=",
"SunshineDateUtils",
".",
"getUTCDateFromLocal",
"(",
"localDate",
")",
";",
"long",
"startDay",
"=",
"SunshineDateUtils",
".",
"normalizeDate",
"(",
"utcDate",
")",
";",
"WeatherData",
"weatherData",
"=",
"new",
"WeatherData",
"(",
")",
";",
"/*\n * We ignore all the datetime values embedded in the JSON and assume that\n * the values are returned in-order by day (which is not guaranteed to be correct).\n */",
"long",
"dateTimeMillis",
"=",
"startDay",
"+",
"SunshineDateUtils",
".",
"DAY_IN_MILLIS",
"*",
"index",
";",
"Date",
"fakeDayForIndex",
"=",
"Date",
".",
"from",
"(",
"Instant",
".",
"ofEpochMilli",
"(",
"dateTimeMillis",
")",
")",
";",
"weatherData",
".",
"setDay",
"(",
"fakeDayForIndex",
")",
";",
"/*\n * Description is in a child array called \"weather\", which is 1 element long.\n * That element also contains a weather code.\n */",
"JSONObject",
"weatherObject",
"=",
"dayForecast",
".",
"getJSONArray",
"(",
"OWM_WEATHER",
")",
".",
"getJSONObject",
"(",
"0",
")",
";",
"weatherData",
".",
"setWeatherLabel",
"(",
"weatherObject",
".",
"getString",
"(",
"OWM_WEATHER_DESCRIPTION",
")",
")",
";",
"weatherData",
".",
"setWeatherCode",
"(",
"weatherObject",
".",
"getInt",
"(",
"OWM_WEATHER_ID",
")",
")",
";",
"/*\n * Temperatures are sent by Open Weather Map in a child object called \"temp\".\n *\n * Editor's Note: Try not to name variables \"temp\" when working with temperature.\n * It confuses everybody. Temp could easily mean any number of things, including\n * temperature, temporary and is just a bad variable name.\n */",
"JSONObject",
"temperatureObject",
"=",
"dayForecast",
".",
"getJSONObject",
"(",
"OWM_TEMPERATURE",
")",
";",
"weatherData",
".",
"setHighTemp",
"(",
"temperatureObject",
".",
"getDouble",
"(",
"OWM_MAX",
")",
")",
";",
"weatherData",
".",
"setLowTemp",
"(",
"temperatureObject",
".",
"getDouble",
"(",
"OWM_MIN",
")",
")",
";",
"weatherData",
".",
"setPressure",
"(",
"dayForecast",
".",
"getDouble",
"(",
"OWM_PRESSURE",
")",
")",
";",
"weatherData",
".",
"setHumidityPercentage",
"(",
"dayForecast",
".",
"getInt",
"(",
"OWM_HUMIDITY",
")",
")",
";",
"weatherData",
".",
"setWindSpeed",
"(",
"dayForecast",
".",
"getDouble",
"(",
"OWM_WINDSPEED",
")",
")",
";",
"return",
"weatherData",
";",
"}",
"}"
] | Utility functions to handle OpenWeatherMap JSON data. | [
"Utility",
"functions",
"to",
"handle",
"OpenWeatherMap",
"JSON",
"data",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b97baf4627f58a3958ea39ef63e931ca8386a20a | ysden123/ys-pjava | basics/src/main/java/com/stulsoft/pjava/basics/optional/POptional2.java | [
"MIT"
] | Java | POptional2 | /**
* Playing with Optional
*
* @author Yuriy Stul.
*/ | Playing with Optional
@author Yuriy Stul. | [
"Playing",
"with",
"Optional",
"@author",
"Yuriy",
"Stul",
"."
] | public class POptional2 {
private final static Logger logger = LoggerFactory.getLogger(POptional2.class);
private record DataObject(String name) {
}
public static void main(String[] args) {
logger.info("==>main");
testF1();
test2();
test3();
logger.info("<==main");
}
private static Optional<Integer> f1(boolean tofail) {
return tofail ? Optional.empty() : Optional.of(123);
}
private static void testF1() {
logger.info("==>testF1");
Optional<Integer> r = f1(false);
r.ifPresent(i -> logger.info("(1) Result is {}", i));
boolean isPresent = r.isPresent();
logger.info("(1.1) isPresent is {}", isPresent);
r = f1(true);
r.ifPresent(i -> logger.info("(2) Result is {}", i));
isPresent = r.isPresent();
logger.info("(2.1) isPresent is {}", isPresent);
logger.info("<==testF1");
}
private static void test2() {
logger.info("==>test2");
AtomicInteger i = new AtomicInteger();
Optional.of(123).ifPresent(i::set);
logger.info("<==test2");
}
private static void test3() {
logger.info("==>test3");
AtomicReference<DataObject> dataObjectNull = new AtomicReference<>();
logger.info("{}", dataObjectNull.get());
AtomicReference<DataObject> dataObject = new AtomicReference<>();
Optional.of("some name").ifPresent(name -> dataObject.set(new DataObject(name)));
logger.info("{}", dataObject);
logger.info("<==test3");
}
} | [
"public",
"class",
"POptional2",
"{",
"private",
"final",
"static",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"POptional2",
".",
"class",
")",
";",
"private",
"record",
"DataObject",
"(",
"String",
"name",
")",
"{",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"==>main",
"\"",
")",
";",
"testF1",
"(",
")",
";",
"test2",
"(",
")",
";",
"test3",
"(",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"<==main",
"\"",
")",
";",
"}",
"private",
"static",
"Optional",
"<",
"Integer",
">",
"f1",
"(",
"boolean",
"tofail",
")",
"{",
"return",
"tofail",
"?",
"Optional",
".",
"empty",
"(",
")",
":",
"Optional",
".",
"of",
"(",
"123",
")",
";",
"}",
"private",
"static",
"void",
"testF1",
"(",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"==>testF1",
"\"",
")",
";",
"Optional",
"<",
"Integer",
">",
"r",
"=",
"f1",
"(",
"false",
")",
";",
"r",
".",
"ifPresent",
"(",
"i",
"->",
"logger",
".",
"info",
"(",
"\"",
"(1) Result is {}",
"\"",
",",
"i",
")",
")",
";",
"boolean",
"isPresent",
"=",
"r",
".",
"isPresent",
"(",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"(1.1) isPresent is {}",
"\"",
",",
"isPresent",
")",
";",
"r",
"=",
"f1",
"(",
"true",
")",
";",
"r",
".",
"ifPresent",
"(",
"i",
"->",
"logger",
".",
"info",
"(",
"\"",
"(2) Result is {}",
"\"",
",",
"i",
")",
")",
";",
"isPresent",
"=",
"r",
".",
"isPresent",
"(",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"(2.1) isPresent is {}",
"\"",
",",
"isPresent",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"<==testF1",
"\"",
")",
";",
"}",
"private",
"static",
"void",
"test2",
"(",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"==>test2",
"\"",
")",
";",
"AtomicInteger",
"i",
"=",
"new",
"AtomicInteger",
"(",
")",
";",
"Optional",
".",
"of",
"(",
"123",
")",
".",
"ifPresent",
"(",
"i",
"::",
"set",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"<==test2",
"\"",
")",
";",
"}",
"private",
"static",
"void",
"test3",
"(",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"==>test3",
"\"",
")",
";",
"AtomicReference",
"<",
"DataObject",
">",
"dataObjectNull",
"=",
"new",
"AtomicReference",
"<",
">",
"(",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"{}",
"\"",
",",
"dataObjectNull",
".",
"get",
"(",
")",
")",
";",
"AtomicReference",
"<",
"DataObject",
">",
"dataObject",
"=",
"new",
"AtomicReference",
"<",
">",
"(",
")",
";",
"Optional",
".",
"of",
"(",
"\"",
"some name",
"\"",
")",
".",
"ifPresent",
"(",
"name",
"->",
"dataObject",
".",
"set",
"(",
"new",
"DataObject",
"(",
"name",
")",
")",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"{}",
"\"",
",",
"dataObject",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"<==test3",
"\"",
")",
";",
"}",
"}"
] | Playing with Optional
@author Yuriy Stul. | [
"Playing",
"with",
"Optional",
"@author",
"Yuriy",
"Stul",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b97d4f827777cdbde3f05145f6b4deab1e5f18d4 | briluu/quizdroid | app/src/main/java/edu/washington/briluu/quizdroid/OverviewFragment.java | [
"MIT"
] | Java | OverviewFragment | /**
* A simple {@link Fragment} subclass.
*/ | A simple Fragment subclass. | [
"A",
"simple",
"Fragment",
"subclass",
"."
] | public class OverviewFragment extends Fragment {
private static final String TOPIC = "TOPIC";
private String topic;
Button beginBtn;
public OverviewFragment() {
// Required empty public constructor
}
public static OverviewFragment newInstance(String topic) {
OverviewFragment fragment = new OverviewFragment();
Bundle args = new Bundle();
args.putString(TOPIC, topic);
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
topic = getArguments().getString(TOPIC);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("OverviewFragment", "Topic is: " + topic);
View v = inflater.inflate(R.layout.fragment_overview, container, false);
// Grab the activity's repo of topics and current topic
QuizActivity quiz = (QuizActivity) getActivity();
HashMap<String, Topic> allTopics = quiz.topics;
Topic currentTopic = quiz.currentTopic;
int numQuestions = currentTopic.getQuestions().size();
TextView numQuestionsTV = (TextView) v.findViewById(R.id.numQuestions);
numQuestionsTV.setText("This quiz will contain " + numQuestions + " question(s).");
// Set description text according to corresponding topic
switch(topic) {
case "Mathematics":
TextView mathDescription = (TextView) v.findViewById(R.id.description);
mathDescription.setText(allTopics.get("Mathematics").getLongDescription());
break;
case "Science!":
TextView physicsDescription = (TextView) v.findViewById(R.id.description);
physicsDescription.setText(allTopics.get("Science!").getLongDescription());
break;
case "Marvel Super Heroes":
TextView marvelDescription = (TextView) v.findViewById(R.id.description);
marvelDescription.setText(allTopics.get("Marvel Super Heroes").getLongDescription());
break;
}
beginBtn = (Button) v.findViewById(R.id.begin);
beginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment qf = QuestionFragment.newInstance(0, 0);
FragmentTransaction tx = getFragmentManager().beginTransaction();
tx.replace(R.id.quiz_fragment, qf);
tx.commit();
}
});
return v;
}
} | [
"public",
"class",
"OverviewFragment",
"extends",
"Fragment",
"{",
"private",
"static",
"final",
"String",
"TOPIC",
"=",
"\"",
"TOPIC",
"\"",
";",
"private",
"String",
"topic",
";",
"Button",
"beginBtn",
";",
"public",
"OverviewFragment",
"(",
")",
"{",
"}",
"public",
"static",
"OverviewFragment",
"newInstance",
"(",
"String",
"topic",
")",
"{",
"OverviewFragment",
"fragment",
"=",
"new",
"OverviewFragment",
"(",
")",
";",
"Bundle",
"args",
"=",
"new",
"Bundle",
"(",
")",
";",
"args",
".",
"putString",
"(",
"TOPIC",
",",
"topic",
")",
";",
"fragment",
".",
"setArguments",
"(",
"args",
")",
";",
"return",
"fragment",
";",
"}",
"public",
"void",
"onCreate",
"(",
"Bundle",
"savedInstanceState",
")",
"{",
"super",
".",
"onCreate",
"(",
"savedInstanceState",
")",
";",
"if",
"(",
"getArguments",
"(",
")",
"!=",
"null",
")",
"{",
"topic",
"=",
"getArguments",
"(",
")",
".",
"getString",
"(",
"TOPIC",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"View",
"onCreateView",
"(",
"LayoutInflater",
"inflater",
",",
"ViewGroup",
"container",
",",
"Bundle",
"savedInstanceState",
")",
"{",
"Log",
".",
"d",
"(",
"\"",
"OverviewFragment",
"\"",
",",
"\"",
"Topic is: ",
"\"",
"+",
"topic",
")",
";",
"View",
"v",
"=",
"inflater",
".",
"inflate",
"(",
"R",
".",
"layout",
".",
"fragment_overview",
",",
"container",
",",
"false",
")",
";",
"QuizActivity",
"quiz",
"=",
"(",
"QuizActivity",
")",
"getActivity",
"(",
")",
";",
"HashMap",
"<",
"String",
",",
"Topic",
">",
"allTopics",
"=",
"quiz",
".",
"topics",
";",
"Topic",
"currentTopic",
"=",
"quiz",
".",
"currentTopic",
";",
"int",
"numQuestions",
"=",
"currentTopic",
".",
"getQuestions",
"(",
")",
".",
"size",
"(",
")",
";",
"TextView",
"numQuestionsTV",
"=",
"(",
"TextView",
")",
"v",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"numQuestions",
")",
";",
"numQuestionsTV",
".",
"setText",
"(",
"\"",
"This quiz will contain ",
"\"",
"+",
"numQuestions",
"+",
"\"",
" question(s).",
"\"",
")",
";",
"switch",
"(",
"topic",
")",
"{",
"case",
"\"",
"Mathematics",
"\"",
":",
"TextView",
"mathDescription",
"=",
"(",
"TextView",
")",
"v",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"description",
")",
";",
"mathDescription",
".",
"setText",
"(",
"allTopics",
".",
"get",
"(",
"\"",
"Mathematics",
"\"",
")",
".",
"getLongDescription",
"(",
")",
")",
";",
"break",
";",
"case",
"\"",
"Science!",
"\"",
":",
"TextView",
"physicsDescription",
"=",
"(",
"TextView",
")",
"v",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"description",
")",
";",
"physicsDescription",
".",
"setText",
"(",
"allTopics",
".",
"get",
"(",
"\"",
"Science!",
"\"",
")",
".",
"getLongDescription",
"(",
")",
")",
";",
"break",
";",
"case",
"\"",
"Marvel Super Heroes",
"\"",
":",
"TextView",
"marvelDescription",
"=",
"(",
"TextView",
")",
"v",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"description",
")",
";",
"marvelDescription",
".",
"setText",
"(",
"allTopics",
".",
"get",
"(",
"\"",
"Marvel Super Heroes",
"\"",
")",
".",
"getLongDescription",
"(",
")",
")",
";",
"break",
";",
"}",
"beginBtn",
"=",
"(",
"Button",
")",
"v",
".",
"findViewById",
"(",
"R",
".",
"id",
".",
"begin",
")",
";",
"beginBtn",
".",
"setOnClickListener",
"(",
"new",
"View",
".",
"OnClickListener",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onClick",
"(",
"View",
"v",
")",
"{",
"Fragment",
"qf",
"=",
"QuestionFragment",
".",
"newInstance",
"(",
"0",
",",
"0",
")",
";",
"FragmentTransaction",
"tx",
"=",
"getFragmentManager",
"(",
")",
".",
"beginTransaction",
"(",
")",
";",
"tx",
".",
"replace",
"(",
"R",
".",
"id",
".",
"quiz_fragment",
",",
"qf",
")",
";",
"tx",
".",
"commit",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"v",
";",
"}",
"}"
] | A simple {@link Fragment} subclass. | [
"A",
"simple",
"{",
"@link",
"Fragment",
"}",
"subclass",
"."
] | [
"// Required empty public constructor",
"// Grab the activity's repo of topics and current topic",
"// Set description text according to corresponding topic"
] | [
{
"param": "Fragment",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Fragment",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b980ad5290bbfcd864ca944b3f4656df321b010a | ayush-usf/galileo | src/main/java/edu/colostate/cs/galileo/event/EventContext.java | [
"BSD-2-Clause"
] | Java | EventContext | /**
* Tracks the context of an event and allows retrieving event metadata. Allows
* replies to be sent directly to their originating source.
*
* @author malensek
*/ | Tracks the context of an event and allows retrieving event metadata. Allows
replies to be sent directly to their originating source.
@author malensek | [
"Tracks",
"the",
"context",
"of",
"an",
"event",
"and",
"allows",
"retrieving",
"event",
"metadata",
".",
"Allows",
"replies",
"to",
"be",
"sent",
"directly",
"to",
"their",
"originating",
"source",
".",
"@author",
"malensek"
] | public class EventContext {
private GalileoMessage message;
private EventWrapper wrapper;
public EventContext(GalileoMessage message, EventWrapper wrapper) {
this.message = message;
this.wrapper = wrapper;
}
/**
* Send a reply back to the source that created the original event.
*/
public void sendReply(Event e)
throws IOException {
GalileoMessage m = wrapper.wrap(e);
this.message.context().sendMessage(m);
}
/**
* @return NetworkDestination of the client that generated the event.
*/
public NetworkEndpoint getSource() {
return message.context().remoteEndpoint();
}
} | [
"public",
"class",
"EventContext",
"{",
"private",
"GalileoMessage",
"message",
";",
"private",
"EventWrapper",
"wrapper",
";",
"public",
"EventContext",
"(",
"GalileoMessage",
"message",
",",
"EventWrapper",
"wrapper",
")",
"{",
"this",
".",
"message",
"=",
"message",
";",
"this",
".",
"wrapper",
"=",
"wrapper",
";",
"}",
"/**\n * Send a reply back to the source that created the original event.\n */",
"public",
"void",
"sendReply",
"(",
"Event",
"e",
")",
"throws",
"IOException",
"{",
"GalileoMessage",
"m",
"=",
"wrapper",
".",
"wrap",
"(",
"e",
")",
";",
"this",
".",
"message",
".",
"context",
"(",
")",
".",
"sendMessage",
"(",
"m",
")",
";",
"}",
"/**\n * @return NetworkDestination of the client that generated the event.\n */",
"public",
"NetworkEndpoint",
"getSource",
"(",
")",
"{",
"return",
"message",
".",
"context",
"(",
")",
".",
"remoteEndpoint",
"(",
")",
";",
"}",
"}"
] | Tracks the context of an event and allows retrieving event metadata. | [
"Tracks",
"the",
"context",
"of",
"an",
"event",
"and",
"allows",
"retrieving",
"event",
"metadata",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b981e25ae809e846d8af3a68607ba240ca4b74f8 | intari/KalmanLocationManager | library/src/main/java/net/intari/KalmanLocationManager/KalmanLocationManager.java | [
"MIT"
] | Java | KalmanLocationManager | /**
* Provides a means of requesting location updates.
* <p>
* Similar to Android's {@link android.location.LocationManager LocationManager}.
*/ | Provides a means of requesting location updates. | [
"Provides",
"a",
"means",
"of",
"requesting",
"location",
"updates",
"."
] | public class KalmanLocationManager {
/**
* Specifies which of the native location providers to use, or a combination of them.
*/
public enum UseProvider { GPS, NET, GPS_AND_NET }
/**
* Provider string assigned to predicted Location objects.
*/
public static final String KALMAN_PROVIDER = "kalman";
/**
* Logger tag.
*/
private static final String TAG = KalmanLocationManager.class.getSimpleName();
/**
* The Context the KalmanLocationManager is running in.
*/
private final Context mContext;
/**
* Map that associates provided LocationListeners with created LooperThreads.
*/
private final Map<LocationListener, LooperThread> mListener2Thread;
/**
* Constructor.
*
* @param context The Context for this KalmanLocationManager.
*/
public KalmanLocationManager(Context context) {
mContext = context;
mListener2Thread = new HashMap<LocationListener, LooperThread>();
}
/**
* Register for {@link android.location.Location Location} estimates using the given LocationListener callback.
*
*
* @param useProvider Specifies which of the native location providers to use, or a combination of them.
*
* @param minTimeFilter Minimum time interval between location estimates, in milliseconds.
* Indicates the frequency of predictions to be calculated by the filter,
* thus the frequency of callbacks to be received by the given location listener.
*
* @param minTimeGpsProvider Minimum time interval between GPS readings, in milliseconds.
* If {@link UseProvider#NET UseProvider.NET} was set, this value is ignored.
*
* @param minTimeNetProvider Minimum time interval between Network readings, in milliseconds.
* If {@link UseProvider#GPS UseProvider.GPS} was set, this value is ignored.
*
* @param listener A {@link android.location.LocationListener LocationListener} whose
* {@link android.location.LocationListener#onLocationChanged(android.location.Location) onLocationChanged(Location)}
* method will be called for each location estimate produced by the filter. It will also receive
* the status updates from the native providers.
*
* @param forwardProviderReadings Also forward location readings from the native providers to the given listener.
* Note that <i>status</i> updates will always be forwarded.
*
*/
public void requestLocationUpdates(
UseProvider useProvider,
long minTimeFilter,
long minTimeGpsProvider,
long minTimeNetProvider,
LocationListener listener,
boolean forwardProviderReadings)
{
// Validate arguments
if (useProvider == null)
throw new IllegalArgumentException("useProvider can't be null");
if (listener == null)
throw new IllegalArgumentException("listener can't be null");
if (minTimeFilter < 0) {
CustomLog.w(TAG, "minTimeFilter < 0. Setting to 0");
minTimeFilter = 0;
}
if (minTimeGpsProvider < 0) {
CustomLog.w(TAG, "minTimeGpsProvider < 0. Setting to 0");
minTimeGpsProvider = 0;
}
if (minTimeNetProvider < 0) {
CustomLog.w(TAG, "minTimeNetProvider < 0. Setting to 0");
minTimeNetProvider = 0;
}
// Remove this listener if it is already in use
if (mListener2Thread.containsKey(listener)) {
CustomLog.d(TAG, "Requested location updates with a listener that is already in use. Removing.");
removeUpdates(listener);
}
LooperThread looperThread = new LooperThread(
mContext, useProvider, minTimeFilter, minTimeGpsProvider, minTimeNetProvider,
listener, forwardProviderReadings);
mListener2Thread.put(listener, looperThread);
}
/**
* Removes location estimates for the specified LocationListener.
* <p>
* Following this call, updates will no longer occur for this listener.
*
* @param listener Listener object that no longer needs location estimates.
*/
public void removeUpdates(LocationListener listener) {
LooperThread looperThread = mListener2Thread.remove(listener);
if (looperThread == null) {
CustomLog.d(TAG, "Did not remove updates for given LocationListener. Wasn't registered in this instance.");
return;
}
looperThread.close();
}
} | [
"public",
"class",
"KalmanLocationManager",
"{",
"/**\n * Specifies which of the native location providers to use, or a combination of them.\n */",
"public",
"enum",
"UseProvider",
"{",
"GPS",
",",
"NET",
",",
"GPS_AND_NET",
"}",
"/**\n * Provider string assigned to predicted Location objects.\n */",
"public",
"static",
"final",
"String",
"KALMAN_PROVIDER",
"=",
"\"",
"kalman",
"\"",
";",
"/**\n * Logger tag.\n */",
"private",
"static",
"final",
"String",
"TAG",
"=",
"KalmanLocationManager",
".",
"class",
".",
"getSimpleName",
"(",
")",
";",
"/**\n * The Context the KalmanLocationManager is running in.\n */",
"private",
"final",
"Context",
"mContext",
";",
"/**\n * Map that associates provided LocationListeners with created LooperThreads.\n */",
"private",
"final",
"Map",
"<",
"LocationListener",
",",
"LooperThread",
">",
"mListener2Thread",
";",
"/**\n * Constructor.\n *\n * @param context The Context for this KalmanLocationManager.\n */",
"public",
"KalmanLocationManager",
"(",
"Context",
"context",
")",
"{",
"mContext",
"=",
"context",
";",
"mListener2Thread",
"=",
"new",
"HashMap",
"<",
"LocationListener",
",",
"LooperThread",
">",
"(",
")",
";",
"}",
"/**\n * Register for {@link android.location.Location Location} estimates using the given LocationListener callback.\n *\n *\n * @param useProvider Specifies which of the native location providers to use, or a combination of them.\n *\n * @param minTimeFilter Minimum time interval between location estimates, in milliseconds.\n * Indicates the frequency of predictions to be calculated by the filter,\n * thus the frequency of callbacks to be received by the given location listener.\n *\n * @param minTimeGpsProvider Minimum time interval between GPS readings, in milliseconds.\n * If {@link UseProvider#NET UseProvider.NET} was set, this value is ignored.\n *\n * @param minTimeNetProvider Minimum time interval between Network readings, in milliseconds.\n * If {@link UseProvider#GPS UseProvider.GPS} was set, this value is ignored.\n *\n * @param listener A {@link android.location.LocationListener LocationListener} whose\n * {@link android.location.LocationListener#onLocationChanged(android.location.Location) onLocationChanged(Location)}\n * method will be called for each location estimate produced by the filter. It will also receive\n * the status updates from the native providers.\n *\n * @param forwardProviderReadings Also forward location readings from the native providers to the given listener.\n * Note that <i>status</i> updates will always be forwarded.\n *\n */",
"public",
"void",
"requestLocationUpdates",
"(",
"UseProvider",
"useProvider",
",",
"long",
"minTimeFilter",
",",
"long",
"minTimeGpsProvider",
",",
"long",
"minTimeNetProvider",
",",
"LocationListener",
"listener",
",",
"boolean",
"forwardProviderReadings",
")",
"{",
"if",
"(",
"useProvider",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"useProvider can't be null",
"\"",
")",
";",
"if",
"(",
"listener",
"==",
"null",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"listener can't be null",
"\"",
")",
";",
"if",
"(",
"minTimeFilter",
"<",
"0",
")",
"{",
"CustomLog",
".",
"w",
"(",
"TAG",
",",
"\"",
"minTimeFilter < 0. Setting to 0",
"\"",
")",
";",
"minTimeFilter",
"=",
"0",
";",
"}",
"if",
"(",
"minTimeGpsProvider",
"<",
"0",
")",
"{",
"CustomLog",
".",
"w",
"(",
"TAG",
",",
"\"",
"minTimeGpsProvider < 0. Setting to 0",
"\"",
")",
";",
"minTimeGpsProvider",
"=",
"0",
";",
"}",
"if",
"(",
"minTimeNetProvider",
"<",
"0",
")",
"{",
"CustomLog",
".",
"w",
"(",
"TAG",
",",
"\"",
"minTimeNetProvider < 0. Setting to 0",
"\"",
")",
";",
"minTimeNetProvider",
"=",
"0",
";",
"}",
"if",
"(",
"mListener2Thread",
".",
"containsKey",
"(",
"listener",
")",
")",
"{",
"CustomLog",
".",
"d",
"(",
"TAG",
",",
"\"",
"Requested location updates with a listener that is already in use. Removing.",
"\"",
")",
";",
"removeUpdates",
"(",
"listener",
")",
";",
"}",
"LooperThread",
"looperThread",
"=",
"new",
"LooperThread",
"(",
"mContext",
",",
"useProvider",
",",
"minTimeFilter",
",",
"minTimeGpsProvider",
",",
"minTimeNetProvider",
",",
"listener",
",",
"forwardProviderReadings",
")",
";",
"mListener2Thread",
".",
"put",
"(",
"listener",
",",
"looperThread",
")",
";",
"}",
"/**\n * Removes location estimates for the specified LocationListener.\n * <p>\n * Following this call, updates will no longer occur for this listener.\n *\n * @param listener Listener object that no longer needs location estimates.\n */",
"public",
"void",
"removeUpdates",
"(",
"LocationListener",
"listener",
")",
"{",
"LooperThread",
"looperThread",
"=",
"mListener2Thread",
".",
"remove",
"(",
"listener",
")",
";",
"if",
"(",
"looperThread",
"==",
"null",
")",
"{",
"CustomLog",
".",
"d",
"(",
"TAG",
",",
"\"",
"Did not remove updates for given LocationListener. Wasn't registered in this instance.",
"\"",
")",
";",
"return",
";",
"}",
"looperThread",
".",
"close",
"(",
")",
";",
"}",
"}"
] | Provides a means of requesting location updates. | [
"Provides",
"a",
"means",
"of",
"requesting",
"location",
"updates",
"."
] | [
"// Validate arguments",
"// Remove this listener if it is already in use"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b987848f27ef8dc665bbca0f769fec069d09d350 | gurubamal/dcaegen2-analytics-tca | dcae-analytics-cdap-tca/src/main/java/org/onap/dcae/apod/analytics/cdap/tca/utils/AppPreferencesToPublisherConfigMapper.java | [
"Apache-2.0",
"CC-BY-4.0"
] | Java | AppPreferencesToPublisherConfigMapper | /**
* Function which translates {@link TCAAppPreferences} to {@link DMaaPMRPublisherConfig}
* <p>
* @author Rajiv Singla . Creation Date: 11/17/2016.
*/ | Function which translates TCAAppPreferences to DMaaPMRPublisherConfig
@author Rajiv Singla . | [
"Function",
"which",
"translates",
"TCAAppPreferences",
"to",
"DMaaPMRPublisherConfig",
"@author",
"Rajiv",
"Singla",
"."
] | public class AppPreferencesToPublisherConfigMapper implements Function<TCAAppPreferences, DMaaPMRPublisherConfig> {
/**
* Factory method to convert {@link TCAAppPreferences} to {@link DMaaPMRPublisherConfig} object
*
* @param tcaAppPreferences tca App Preferences
*
* @return publisher config object
*/
public static DMaaPMRPublisherConfig map(final TCAAppPreferences tcaAppPreferences) {
return new AppPreferencesToPublisherConfigMapper().apply(tcaAppPreferences);
}
/**
* Implementation to convert {@link TCAAppPreferences} to {@link DMaaPMRPublisherConfig} object
*
* @param tcaAppPreferences tca App Preferences
*
* @return publisher config object
*/
@Nonnull
@Override
public DMaaPMRPublisherConfig apply(@Nonnull TCAAppPreferences tcaAppPreferences) {
// Create a new publisher settings builder
final DMaaPMRPublisherConfig.Builder publisherConfigBuilder = new DMaaPMRPublisherConfig.Builder(
tcaAppPreferences.getPublisherHostName(), tcaAppPreferences.getPublisherTopicName());
// Setup up any optional publisher parameters if they are present
final Integer publisherHostPort = tcaAppPreferences.getPublisherHostPort();
if (publisherHostPort != null) {
publisherConfigBuilder.setPortNumber(publisherHostPort);
}
final String publisherProtocol = tcaAppPreferences.getPublisherProtocol();
if (isPresent(publisherProtocol)) {
publisherConfigBuilder.setProtocol(publisherProtocol);
}
final String publisherUserName = tcaAppPreferences.getPublisherUserName();
if (isPresent(publisherUserName)) {
publisherConfigBuilder.setUserName(publisherUserName);
}
final String publisherUserPassword = tcaAppPreferences.getPublisherUserPassword();
if (isPresent(publisherUserPassword)) {
publisherConfigBuilder.setUserPassword(publisherUserPassword);
}
final String publisherContentType = tcaAppPreferences.getPublisherContentType();
if (isPresent(publisherContentType)) {
publisherConfigBuilder.setContentType(publisherContentType);
}
final Integer publisherMaxBatchSize = tcaAppPreferences.getPublisherMaxBatchSize();
if (publisherMaxBatchSize != null) {
publisherConfigBuilder.setMaxBatchSize(publisherMaxBatchSize);
}
final Integer publisherMaxRecoveryQueueSize = tcaAppPreferences.getPublisherMaxRecoveryQueueSize();
if (publisherMaxRecoveryQueueSize != null) {
publisherConfigBuilder.setMaxRecoveryQueueSize(publisherMaxRecoveryQueueSize);
}
return publisherConfigBuilder.build();
}
} | [
"public",
"class",
"AppPreferencesToPublisherConfigMapper",
"implements",
"Function",
"<",
"TCAAppPreferences",
",",
"DMaaPMRPublisherConfig",
">",
"{",
"/**\n * Factory method to convert {@link TCAAppPreferences} to {@link DMaaPMRPublisherConfig} object\n *\n * @param tcaAppPreferences tca App Preferences\n *\n * @return publisher config object\n */",
"public",
"static",
"DMaaPMRPublisherConfig",
"map",
"(",
"final",
"TCAAppPreferences",
"tcaAppPreferences",
")",
"{",
"return",
"new",
"AppPreferencesToPublisherConfigMapper",
"(",
")",
".",
"apply",
"(",
"tcaAppPreferences",
")",
";",
"}",
"/**\n * Implementation to convert {@link TCAAppPreferences} to {@link DMaaPMRPublisherConfig} object\n *\n * @param tcaAppPreferences tca App Preferences\n *\n * @return publisher config object\n */",
"@",
"Nonnull",
"@",
"Override",
"public",
"DMaaPMRPublisherConfig",
"apply",
"(",
"@",
"Nonnull",
"TCAAppPreferences",
"tcaAppPreferences",
")",
"{",
"final",
"DMaaPMRPublisherConfig",
".",
"Builder",
"publisherConfigBuilder",
"=",
"new",
"DMaaPMRPublisherConfig",
".",
"Builder",
"(",
"tcaAppPreferences",
".",
"getPublisherHostName",
"(",
")",
",",
"tcaAppPreferences",
".",
"getPublisherTopicName",
"(",
")",
")",
";",
"final",
"Integer",
"publisherHostPort",
"=",
"tcaAppPreferences",
".",
"getPublisherHostPort",
"(",
")",
";",
"if",
"(",
"publisherHostPort",
"!=",
"null",
")",
"{",
"publisherConfigBuilder",
".",
"setPortNumber",
"(",
"publisherHostPort",
")",
";",
"}",
"final",
"String",
"publisherProtocol",
"=",
"tcaAppPreferences",
".",
"getPublisherProtocol",
"(",
")",
";",
"if",
"(",
"isPresent",
"(",
"publisherProtocol",
")",
")",
"{",
"publisherConfigBuilder",
".",
"setProtocol",
"(",
"publisherProtocol",
")",
";",
"}",
"final",
"String",
"publisherUserName",
"=",
"tcaAppPreferences",
".",
"getPublisherUserName",
"(",
")",
";",
"if",
"(",
"isPresent",
"(",
"publisherUserName",
")",
")",
"{",
"publisherConfigBuilder",
".",
"setUserName",
"(",
"publisherUserName",
")",
";",
"}",
"final",
"String",
"publisherUserPassword",
"=",
"tcaAppPreferences",
".",
"getPublisherUserPassword",
"(",
")",
";",
"if",
"(",
"isPresent",
"(",
"publisherUserPassword",
")",
")",
"{",
"publisherConfigBuilder",
".",
"setUserPassword",
"(",
"publisherUserPassword",
")",
";",
"}",
"final",
"String",
"publisherContentType",
"=",
"tcaAppPreferences",
".",
"getPublisherContentType",
"(",
")",
";",
"if",
"(",
"isPresent",
"(",
"publisherContentType",
")",
")",
"{",
"publisherConfigBuilder",
".",
"setContentType",
"(",
"publisherContentType",
")",
";",
"}",
"final",
"Integer",
"publisherMaxBatchSize",
"=",
"tcaAppPreferences",
".",
"getPublisherMaxBatchSize",
"(",
")",
";",
"if",
"(",
"publisherMaxBatchSize",
"!=",
"null",
")",
"{",
"publisherConfigBuilder",
".",
"setMaxBatchSize",
"(",
"publisherMaxBatchSize",
")",
";",
"}",
"final",
"Integer",
"publisherMaxRecoveryQueueSize",
"=",
"tcaAppPreferences",
".",
"getPublisherMaxRecoveryQueueSize",
"(",
")",
";",
"if",
"(",
"publisherMaxRecoveryQueueSize",
"!=",
"null",
")",
"{",
"publisherConfigBuilder",
".",
"setMaxRecoveryQueueSize",
"(",
"publisherMaxRecoveryQueueSize",
")",
";",
"}",
"return",
"publisherConfigBuilder",
".",
"build",
"(",
")",
";",
"}",
"}"
] | Function which translates {@link TCAAppPreferences} to {@link DMaaPMRPublisherConfig}
<p>
@author Rajiv Singla . | [
"Function",
"which",
"translates",
"{",
"@link",
"TCAAppPreferences",
"}",
"to",
"{",
"@link",
"DMaaPMRPublisherConfig",
"}",
"<p",
">",
"@author",
"Rajiv",
"Singla",
"."
] | [
"// Create a new publisher settings builder",
"// Setup up any optional publisher parameters if they are present"
] | [
{
"param": "Function<TCAAppPreferences, DMaaPMRPublisherConfig>",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Function<TCAAppPreferences, DMaaPMRPublisherConfig>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b98899714a802c1b922c8c728014b8f545a33cf5 | webfolderio/ihmc-video-codecs | src/main/java/org/jcodec/containers/mp4/boxes/SampleDescriptionBox.java | [
"Apache-2.0",
"BSD-2-Clause-FreeBSD",
"BSD-2-Clause",
"BSD-3-Clause"
] | Java | SampleDescriptionBox | /**
* This class is part of JCodec ( www.jcodec.org )
* This software is distributed under FreeBSD License
* @author Jay Codec
*
*/ |
@author Jay Codec | [
"@author",
"Jay",
"Codec"
] | public class SampleDescriptionBox extends NodeBox {
public static final MyFactory FACTORY = new MyFactory();
public static class MyFactory extends BoxFactory {
private Map<String, Class<? extends Box>> handlers = new HashMap<String, Class<? extends Box>>();
public MyFactory() {
handlers.put("ap4h", VideoSampleEntry.class);
handlers.put("apch", VideoSampleEntry.class);
handlers.put("apcn", VideoSampleEntry.class);
handlers.put("apcs", VideoSampleEntry.class);
handlers.put("apco", VideoSampleEntry.class);
handlers.put("avc1", VideoSampleEntry.class);
handlers.put("cvid", VideoSampleEntry.class);
handlers.put("jpeg", VideoSampleEntry.class);
handlers.put("smc ", VideoSampleEntry.class);
handlers.put("rle ", VideoSampleEntry.class);
handlers.put("rpza", VideoSampleEntry.class);
handlers.put("kpcd", VideoSampleEntry.class);
handlers.put("png ", VideoSampleEntry.class);
handlers.put("mjpa", VideoSampleEntry.class);
handlers.put("mjpb", VideoSampleEntry.class);
handlers.put("SVQ1", VideoSampleEntry.class);
handlers.put("SVQ3", VideoSampleEntry.class);
handlers.put("mp4v", VideoSampleEntry.class);
handlers.put("dvc ", VideoSampleEntry.class);
handlers.put("dvcp", VideoSampleEntry.class);
handlers.put("gif ", VideoSampleEntry.class);
handlers.put("h263", VideoSampleEntry.class);
handlers.put("tiff", VideoSampleEntry.class);
handlers.put("raw ", VideoSampleEntry.class);
handlers.put("2vuY", VideoSampleEntry.class);
handlers.put("yuv2", VideoSampleEntry.class);
handlers.put("v308", VideoSampleEntry.class);
handlers.put("v408", VideoSampleEntry.class);
handlers.put("v216", VideoSampleEntry.class);
handlers.put("v410", VideoSampleEntry.class);
handlers.put("v210", VideoSampleEntry.class);
handlers.put("m2v1", VideoSampleEntry.class);
handlers.put("m1v1", VideoSampleEntry.class);
handlers.put("xd5b", VideoSampleEntry.class);
handlers.put("dv5n", VideoSampleEntry.class);
handlers.put("jp2h", VideoSampleEntry.class);
handlers.put("mjp2", VideoSampleEntry.class);
handlers.put("ac-3", AudioSampleEntry.class);
handlers.put("cac3", AudioSampleEntry.class);
handlers.put("ima4", AudioSampleEntry.class);
handlers.put("aac ", AudioSampleEntry.class);
handlers.put("celp", AudioSampleEntry.class);
handlers.put("hvxc", AudioSampleEntry.class);
handlers.put("twvq", AudioSampleEntry.class);
handlers.put(".mp1", AudioSampleEntry.class);
handlers.put(".mp2", AudioSampleEntry.class);
handlers.put("midi", AudioSampleEntry.class);
handlers.put("apvs", AudioSampleEntry.class);
handlers.put("alac", AudioSampleEntry.class);
handlers.put("aach", AudioSampleEntry.class);
handlers.put("aacl", AudioSampleEntry.class);
handlers.put("aace", AudioSampleEntry.class);
handlers.put("aacf", AudioSampleEntry.class);
handlers.put("aacp", AudioSampleEntry.class);
handlers.put("aacs", AudioSampleEntry.class);
handlers.put("samr", AudioSampleEntry.class);
handlers.put("AUDB", AudioSampleEntry.class);
handlers.put("ilbc", AudioSampleEntry.class);
handlers.put(new String(new byte[] {0x6D, 0x73, 0x00, 0x11}), AudioSampleEntry.class);
handlers.put(new String(new byte[] {0x6D, 0x73, 0x00, 0x31}), AudioSampleEntry.class);
handlers.put("aes3", AudioSampleEntry.class);
handlers.put("NONE", AudioSampleEntry.class);
handlers.put("raw ", AudioSampleEntry.class);
handlers.put("twos", AudioSampleEntry.class);
handlers.put("sowt", AudioSampleEntry.class);
handlers.put("MAC3 ", AudioSampleEntry.class);
handlers.put("MAC6 ", AudioSampleEntry.class);
handlers.put("ima4", AudioSampleEntry.class);
handlers.put("fl32", AudioSampleEntry.class);
handlers.put("fl64", AudioSampleEntry.class);
handlers.put("in24", AudioSampleEntry.class);
handlers.put("in32", AudioSampleEntry.class);
handlers.put("ulaw", AudioSampleEntry.class);
handlers.put("alaw", AudioSampleEntry.class);
handlers.put("dvca", AudioSampleEntry.class);
handlers.put("QDMC", AudioSampleEntry.class);
handlers.put("QDM2", AudioSampleEntry.class);
handlers.put("Qclp", AudioSampleEntry.class);
handlers.put(".mp3", AudioSampleEntry.class);
handlers.put("mp4a", AudioSampleEntry.class);
handlers.put("lpcm", AudioSampleEntry.class);
handlers.put("tmcd", TimecodeSampleEntry.class);
handlers.put("time", TimecodeSampleEntry.class);
handlers.put("c608", SampleEntry.class);
handlers.put("c708", SampleEntry.class);
handlers.put("text", SampleEntry.class);
}
public Class<? extends Box> toClass(String fourcc) {
return handlers.get(fourcc);
}
}
public static String fourcc() {
return "stsd";
}
public SampleDescriptionBox(Header header) {
super(header);
factory = FACTORY;
}
public SampleDescriptionBox() {
this(new Header(fourcc()));
}
public SampleDescriptionBox(SampleEntry...entries) {
this();
for (SampleEntry e : entries) {
boxes.add(e);
}
}
public void parse(ByteBuffer input) {
input.getInt();
input.getInt();
super.parse(input);
}
@Override
public void doWrite(ByteBuffer out) {
out.putInt(0);
out.putInt(boxes.size());
super.doWrite(out);
}
} | [
"public",
"class",
"SampleDescriptionBox",
"extends",
"NodeBox",
"{",
"public",
"static",
"final",
"MyFactory",
"FACTORY",
"=",
"new",
"MyFactory",
"(",
")",
";",
"public",
"static",
"class",
"MyFactory",
"extends",
"BoxFactory",
"{",
"private",
"Map",
"<",
"String",
",",
"Class",
"<",
"?",
"extends",
"Box",
">",
">",
"handlers",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Class",
"<",
"?",
"extends",
"Box",
">",
">",
"(",
")",
";",
"public",
"MyFactory",
"(",
")",
"{",
"handlers",
".",
"put",
"(",
"\"",
"ap4h",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"apch",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"apcn",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"apcs",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"apco",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"avc1",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"cvid",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"jpeg",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"smc ",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"rle ",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"rpza",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"kpcd",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"png ",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"mjpa",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"mjpb",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"SVQ1",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"SVQ3",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"mp4v",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"dvc ",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"dvcp",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"gif ",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"h263",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"tiff",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"raw ",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"2vuY",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"yuv2",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"v308",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"v408",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"v216",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"v410",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"v210",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"m2v1",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"m1v1",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"xd5b",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"dv5n",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"jp2h",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"mjp2",
"\"",
",",
"VideoSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"ac-3",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"cac3",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"ima4",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aac ",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"celp",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"hvxc",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"twvq",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
".mp1",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
".mp2",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"midi",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"apvs",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"alac",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aach",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aacl",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aace",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aacf",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aacp",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aacs",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"samr",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"AUDB",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"ilbc",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"new",
"String",
"(",
"new",
"byte",
"[",
"]",
"{",
"0x6D",
",",
"0x73",
",",
"0x00",
",",
"0x11",
"}",
")",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"new",
"String",
"(",
"new",
"byte",
"[",
"]",
"{",
"0x6D",
",",
"0x73",
",",
"0x00",
",",
"0x31",
"}",
")",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"aes3",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"NONE",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"raw ",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"twos",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"sowt",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"MAC3 ",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"MAC6 ",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"ima4",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"fl32",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"fl64",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"in24",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"in32",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"ulaw",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"alaw",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"dvca",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"QDMC",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"QDM2",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"Qclp",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
".mp3",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"mp4a",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"lpcm",
"\"",
",",
"AudioSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"tmcd",
"\"",
",",
"TimecodeSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"time",
"\"",
",",
"TimecodeSampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"c608",
"\"",
",",
"SampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"c708",
"\"",
",",
"SampleEntry",
".",
"class",
")",
";",
"handlers",
".",
"put",
"(",
"\"",
"text",
"\"",
",",
"SampleEntry",
".",
"class",
")",
";",
"}",
"public",
"Class",
"<",
"?",
"extends",
"Box",
">",
"toClass",
"(",
"String",
"fourcc",
")",
"{",
"return",
"handlers",
".",
"get",
"(",
"fourcc",
")",
";",
"}",
"}",
"public",
"static",
"String",
"fourcc",
"(",
")",
"{",
"return",
"\"",
"stsd",
"\"",
";",
"}",
"public",
"SampleDescriptionBox",
"(",
"Header",
"header",
")",
"{",
"super",
"(",
"header",
")",
";",
"factory",
"=",
"FACTORY",
";",
"}",
"public",
"SampleDescriptionBox",
"(",
")",
"{",
"this",
"(",
"new",
"Header",
"(",
"fourcc",
"(",
")",
")",
")",
";",
"}",
"public",
"SampleDescriptionBox",
"(",
"SampleEntry",
"...",
"entries",
")",
"{",
"this",
"(",
")",
";",
"for",
"(",
"SampleEntry",
"e",
":",
"entries",
")",
"{",
"boxes",
".",
"add",
"(",
"e",
")",
";",
"}",
"}",
"public",
"void",
"parse",
"(",
"ByteBuffer",
"input",
")",
"{",
"input",
".",
"getInt",
"(",
")",
";",
"input",
".",
"getInt",
"(",
")",
";",
"super",
".",
"parse",
"(",
"input",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"doWrite",
"(",
"ByteBuffer",
"out",
")",
"{",
"out",
".",
"putInt",
"(",
"0",
")",
";",
"out",
".",
"putInt",
"(",
"boxes",
".",
"size",
"(",
")",
")",
";",
"super",
".",
"doWrite",
"(",
"out",
")",
";",
"}",
"}"
] | This class is part of JCodec ( www.jcodec.org )
This software is distributed under FreeBSD License | [
"This",
"class",
"is",
"part",
"of",
"JCodec",
"(",
"www",
".",
"jcodec",
".",
"org",
")",
"This",
"software",
"is",
"distributed",
"under",
"FreeBSD",
"License"
] | [] | [
{
"param": "NodeBox",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "NodeBox",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b98a17bca7bf80f4c9e4edaf242755da56cf8ba8 | Kevin-SJW/Enterprise-programming-exercises | coding/FileModel.java | [
"MIT"
] | Java | FileModel | /**
* @Classname FileModel
* @Description TODO
* @Date 2019/4/22 13:59
* @Created by 14241
*/ | @Classname FileModel
@Description TODO
@Date 2019/4/22 13:59
@Created by 14241 | [
"@Classname",
"FileModel",
"@Description",
"TODO",
"@Date",
"2019",
"/",
"4",
"/",
"22",
"13",
":",
"59",
"@Created",
"by",
"14241"
] | public class FileModel {
public File file;
public String md5;
public FileModel(File file, String md5) {
this.file = file;
this.md5 = md5;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
} | [
"public",
"class",
"FileModel",
"{",
"public",
"File",
"file",
";",
"public",
"String",
"md5",
";",
"public",
"FileModel",
"(",
"File",
"file",
",",
"String",
"md5",
")",
"{",
"this",
".",
"file",
"=",
"file",
";",
"this",
".",
"md5",
"=",
"md5",
";",
"}",
"public",
"File",
"getFile",
"(",
")",
"{",
"return",
"file",
";",
"}",
"public",
"void",
"setFile",
"(",
"File",
"file",
")",
"{",
"this",
".",
"file",
"=",
"file",
";",
"}",
"public",
"String",
"getMd5",
"(",
")",
"{",
"return",
"md5",
";",
"}",
"public",
"void",
"setMd5",
"(",
"String",
"md5",
")",
"{",
"this",
".",
"md5",
"=",
"md5",
";",
"}",
"}"
] | @Classname FileModel
@Description TODO
@Date 2019/4/22 13:59
@Created by 14241 | [
"@Classname",
"FileModel",
"@Description",
"TODO",
"@Date",
"2019",
"/",
"4",
"/",
"22",
"13",
":",
"59",
"@Created",
"by",
"14241"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b98aafd2788b455aba6c459a4b7e030d206e6800 | caskdata/cdap-ingest | cdap-flume/src/main/java/co/cask/cdap/flume/StreamSink.java | [
"Apache-2.0"
] | Java | StreamSink | /**
* CDAP Sink, a Flume sink implementation.
*/ | CDAP Sink, a Flume sink implementation. | [
"CDAP",
"Sink",
"a",
"Flume",
"sink",
"implementation",
"."
] | public class StreamSink implements Sink, LifecycleAware, Configurable {
private static final Logger LOG = LoggerFactory.getLogger(StreamSink.class);
private static final int DEFAULT_WRITER_POOL_SIZE = 1;
private static final boolean DEFAULT_SSL = false;
private static final boolean DEFAULT_VERIFY_SSL_CERT = true;
private static final String DEFAULT_VERSION = "v3";
private static final int DEFAULT_PORT = 11015;
private static final String DEFAULT_NAMESPACE = "default";
private static final String DEFAULT_AUTH_CLIENT = BasicAuthenticationClient.class.getName();
private String host;
private Integer port;
private boolean sslEnabled;
private boolean verifySSLCert;
private int writerPoolSize;
private String version;
private String namespace;
private String streamName;
private StreamWriter writer;
private StreamClient streamClient;
private String authClientClassName;
private String authClientPropertiesPath;
private Channel channel;
private String name;
private LifecycleState lifecycleState;
AuthenticationClient authClient;
/**
* Stream writer result status code
*/
@Override
public void configure(Context context) {
host = context.getString("host");
port = context.getInteger("port", DEFAULT_PORT);
sslEnabled = context.getBoolean("sslEnabled", DEFAULT_SSL);
verifySSLCert = context.getBoolean("verifySSLCert", DEFAULT_VERIFY_SSL_CERT);
version = context.getString("version", DEFAULT_VERSION);
writerPoolSize = context.getInteger("writerPoolSize", DEFAULT_WRITER_POOL_SIZE);
namespace = context.getString("namespace", DEFAULT_NAMESPACE);
streamName = context.getString("streamName");
authClientClassName = context.getString("authClientClass", DEFAULT_AUTH_CLIENT);
authClientPropertiesPath = context.getString("authClientProperties", "");
Preconditions.checkState(host != null, "No hostname specified");
Preconditions.checkState(streamName != null, "No stream name specified");
}
@Override
public void setChannel(Channel channel) {
this.channel = channel;
}
@Override
public Channel getChannel() {
return channel;
}
@Override
public Status process() throws EventDeliveryException {
Status status = Status.READY;
Channel channel = getChannel();
Transaction transaction = channel.getTransaction();
try {
tryReopenClientConnection();
transaction.begin();
Event event = channel.take();
if (event != null) {
try {
writer.write(ByteBuffer.wrap(event.getBody()), event.getHeaders()).get();
LOG.trace("Success write to stream: {} ", streamName);
} catch (Throwable t) {
if (t instanceof ExecutionException) {
t = t.getCause();
}
LOG.error("Error during writing event to stream {}", streamName, t);
throw new EventDeliveryException("Failed to send events to stream: " + streamName, t);
}
}
transaction.commit();
} catch (Throwable t) {
transaction.rollback();
if (t instanceof Error) {
throw (Error) t;
} else if (t instanceof ChannelException) {
LOG.error("Stream Sink {}: Unable to get event from channel {} ", getName(), channel.getName());
status = Status.BACKOFF;
} else {
LOG.debug("Closing writer due to stream error ", t);
closeClientQuietly();
closeWriterQuietly();
throw new EventDeliveryException("Sink event sending error", t);
}
} finally {
transaction.close();
}
return status;
}
private void tryReopenClientConnection() throws IOException {
if (writer == null) {
LOG.debug("Trying to reopen stream writer {} ", streamName);
try {
createStreamClient();
} catch (IOException e) {
writer = null;
LOG.error("Error during reopening client by name: {} for host: {}, port: {}. Reason: {} ",
new Object[]{streamName, host, port, e.getMessage(), e});
throw e;
}
}
}
private void createStreamClient() throws IOException {
if (streamClient == null) {
RestStreamClient.Builder builder = RestStreamClient.builder(host, port);
builder.ssl(sslEnabled);
builder.verifySSLCert(verifySSLCert);
builder.writerPoolSize(writerPoolSize);
builder.version(version);
builder.namespace(namespace);
try {
authClient = (AuthenticationClient) Class.forName(authClientClassName).newInstance();
authClient.setConnectionInfo(host, port, sslEnabled);
if (authClient.isAuthEnabled()) {
Properties properties = new Properties();
properties.setProperty(BasicAuthenticationClient.VERIFY_SSL_CERT_PROP_NAME, String.valueOf(verifySSLCert));
if ((authClientPropertiesPath == null) || (authClientPropertiesPath.isEmpty())) {
throw new Exception("Authentication client is enabled, but the path for properties " +
"file is either empty or null");
}
InputStream inStream = new FileInputStream(authClientPropertiesPath);
try {
properties.load(inStream);
} finally {
Closeables.closeQuietly(inStream);
}
authClient.configure(properties);
}
builder.authClient(authClient);
} catch (IOException e) {
LOG.error("Cannot load properties", e);
throw Throwables.propagate(e);
} catch (ClassNotFoundException e) {
LOG.error("Can not resolve class {}: {}", new Object[]{authClientClassName, e.getMessage(), e});
throw Throwables.propagate(e);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw Throwables.propagate(e);
}
streamClient = builder.build();
}
try {
if (writer == null) {
writer = streamClient.createWriter(streamName);
}
} catch (Throwable t) {
closeWriterQuietly();
throw new IOException("Can not create stream writer by name: " + streamName, t);
}
}
private void closeClientQuietly() {
if (streamClient != null) {
try {
streamClient.close();
} catch (Throwable t) {
LOG.error("Error closing stream client. {}", t.getMessage(), t);
}
streamClient = null;
}
if (authClient != null) {
authClient = null;
}
}
private void closeWriterQuietly() {
try {
if (writer != null) {
writer.close();
}
} catch (Throwable t) {
LOG.error("Error closing writer. {}", t.getMessage(), t);
}
writer = null;
}
public synchronized void start() {
Preconditions.checkState(channel != null, "No channel configured");
try {
createStreamClient();
} catch (Throwable t) {
LOG.error("Unable to create Stream client by name: {} for host: {}, port: {}. Reason: {} ",
new Object[]{streamName, host, port, t.getMessage(), t});
closeWriterQuietly();
closeClientQuietly();
lifecycleState = LifecycleState.ERROR;
return;
}
LOG.info("StreamSink {} started.", getName());
lifecycleState = LifecycleState.START;
}
public synchronized void stop() {
LOG.info("StreamSink {} stopping...", getName());
closeWriterQuietly();
closeClientQuietly();
}
@Override
public LifecycleState getLifecycleState() {
return lifecycleState;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
} | [
"public",
"class",
"StreamSink",
"implements",
"Sink",
",",
"LifecycleAware",
",",
"Configurable",
"{",
"private",
"static",
"final",
"Logger",
"LOG",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"StreamSink",
".",
"class",
")",
";",
"private",
"static",
"final",
"int",
"DEFAULT_WRITER_POOL_SIZE",
"=",
"1",
";",
"private",
"static",
"final",
"boolean",
"DEFAULT_SSL",
"=",
"false",
";",
"private",
"static",
"final",
"boolean",
"DEFAULT_VERIFY_SSL_CERT",
"=",
"true",
";",
"private",
"static",
"final",
"String",
"DEFAULT_VERSION",
"=",
"\"",
"v3",
"\"",
";",
"private",
"static",
"final",
"int",
"DEFAULT_PORT",
"=",
"11015",
";",
"private",
"static",
"final",
"String",
"DEFAULT_NAMESPACE",
"=",
"\"",
"default",
"\"",
";",
"private",
"static",
"final",
"String",
"DEFAULT_AUTH_CLIENT",
"=",
"BasicAuthenticationClient",
".",
"class",
".",
"getName",
"(",
")",
";",
"private",
"String",
"host",
";",
"private",
"Integer",
"port",
";",
"private",
"boolean",
"sslEnabled",
";",
"private",
"boolean",
"verifySSLCert",
";",
"private",
"int",
"writerPoolSize",
";",
"private",
"String",
"version",
";",
"private",
"String",
"namespace",
";",
"private",
"String",
"streamName",
";",
"private",
"StreamWriter",
"writer",
";",
"private",
"StreamClient",
"streamClient",
";",
"private",
"String",
"authClientClassName",
";",
"private",
"String",
"authClientPropertiesPath",
";",
"private",
"Channel",
"channel",
";",
"private",
"String",
"name",
";",
"private",
"LifecycleState",
"lifecycleState",
";",
"AuthenticationClient",
"authClient",
";",
"/**\n * Stream writer result status code\n */",
"@",
"Override",
"public",
"void",
"configure",
"(",
"Context",
"context",
")",
"{",
"host",
"=",
"context",
".",
"getString",
"(",
"\"",
"host",
"\"",
")",
";",
"port",
"=",
"context",
".",
"getInteger",
"(",
"\"",
"port",
"\"",
",",
"DEFAULT_PORT",
")",
";",
"sslEnabled",
"=",
"context",
".",
"getBoolean",
"(",
"\"",
"sslEnabled",
"\"",
",",
"DEFAULT_SSL",
")",
";",
"verifySSLCert",
"=",
"context",
".",
"getBoolean",
"(",
"\"",
"verifySSLCert",
"\"",
",",
"DEFAULT_VERIFY_SSL_CERT",
")",
";",
"version",
"=",
"context",
".",
"getString",
"(",
"\"",
"version",
"\"",
",",
"DEFAULT_VERSION",
")",
";",
"writerPoolSize",
"=",
"context",
".",
"getInteger",
"(",
"\"",
"writerPoolSize",
"\"",
",",
"DEFAULT_WRITER_POOL_SIZE",
")",
";",
"namespace",
"=",
"context",
".",
"getString",
"(",
"\"",
"namespace",
"\"",
",",
"DEFAULT_NAMESPACE",
")",
";",
"streamName",
"=",
"context",
".",
"getString",
"(",
"\"",
"streamName",
"\"",
")",
";",
"authClientClassName",
"=",
"context",
".",
"getString",
"(",
"\"",
"authClientClass",
"\"",
",",
"DEFAULT_AUTH_CLIENT",
")",
";",
"authClientPropertiesPath",
"=",
"context",
".",
"getString",
"(",
"\"",
"authClientProperties",
"\"",
",",
"\"",
"\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"host",
"!=",
"null",
",",
"\"",
"No hostname specified",
"\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"streamName",
"!=",
"null",
",",
"\"",
"No stream name specified",
"\"",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"setChannel",
"(",
"Channel",
"channel",
")",
"{",
"this",
".",
"channel",
"=",
"channel",
";",
"}",
"@",
"Override",
"public",
"Channel",
"getChannel",
"(",
")",
"{",
"return",
"channel",
";",
"}",
"@",
"Override",
"public",
"Status",
"process",
"(",
")",
"throws",
"EventDeliveryException",
"{",
"Status",
"status",
"=",
"Status",
".",
"READY",
";",
"Channel",
"channel",
"=",
"getChannel",
"(",
")",
";",
"Transaction",
"transaction",
"=",
"channel",
".",
"getTransaction",
"(",
")",
";",
"try",
"{",
"tryReopenClientConnection",
"(",
")",
";",
"transaction",
".",
"begin",
"(",
")",
";",
"Event",
"event",
"=",
"channel",
".",
"take",
"(",
")",
";",
"if",
"(",
"event",
"!=",
"null",
")",
"{",
"try",
"{",
"writer",
".",
"write",
"(",
"ByteBuffer",
".",
"wrap",
"(",
"event",
".",
"getBody",
"(",
")",
")",
",",
"event",
".",
"getHeaders",
"(",
")",
")",
".",
"get",
"(",
")",
";",
"LOG",
".",
"trace",
"(",
"\"",
"Success write to stream: {} ",
"\"",
",",
"streamName",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"if",
"(",
"t",
"instanceof",
"ExecutionException",
")",
"{",
"t",
"=",
"t",
".",
"getCause",
"(",
")",
";",
"}",
"LOG",
".",
"error",
"(",
"\"",
"Error during writing event to stream {}",
"\"",
",",
"streamName",
",",
"t",
")",
";",
"throw",
"new",
"EventDeliveryException",
"(",
"\"",
"Failed to send events to stream: ",
"\"",
"+",
"streamName",
",",
"t",
")",
";",
"}",
"}",
"transaction",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"transaction",
".",
"rollback",
"(",
")",
";",
"if",
"(",
"t",
"instanceof",
"Error",
")",
"{",
"throw",
"(",
"Error",
")",
"t",
";",
"}",
"else",
"if",
"(",
"t",
"instanceof",
"ChannelException",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Stream Sink {}: Unable to get event from channel {} ",
"\"",
",",
"getName",
"(",
")",
",",
"channel",
".",
"getName",
"(",
")",
")",
";",
"status",
"=",
"Status",
".",
"BACKOFF",
";",
"}",
"else",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"Closing writer due to stream error ",
"\"",
",",
"t",
")",
";",
"closeClientQuietly",
"(",
")",
";",
"closeWriterQuietly",
"(",
")",
";",
"throw",
"new",
"EventDeliveryException",
"(",
"\"",
"Sink event sending error",
"\"",
",",
"t",
")",
";",
"}",
"}",
"finally",
"{",
"transaction",
".",
"close",
"(",
")",
";",
"}",
"return",
"status",
";",
"}",
"private",
"void",
"tryReopenClientConnection",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"Trying to reopen stream writer {} ",
"\"",
",",
"streamName",
")",
";",
"try",
"{",
"createStreamClient",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"writer",
"=",
"null",
";",
"LOG",
".",
"error",
"(",
"\"",
"Error during reopening client by name: {} for host: {}, port: {}. Reason: {} ",
"\"",
",",
"new",
"Object",
"[",
"]",
"{",
"streamName",
",",
"host",
",",
"port",
",",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
"}",
")",
";",
"throw",
"e",
";",
"}",
"}",
"}",
"private",
"void",
"createStreamClient",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"streamClient",
"==",
"null",
")",
"{",
"RestStreamClient",
".",
"Builder",
"builder",
"=",
"RestStreamClient",
".",
"builder",
"(",
"host",
",",
"port",
")",
";",
"builder",
".",
"ssl",
"(",
"sslEnabled",
")",
";",
"builder",
".",
"verifySSLCert",
"(",
"verifySSLCert",
")",
";",
"builder",
".",
"writerPoolSize",
"(",
"writerPoolSize",
")",
";",
"builder",
".",
"version",
"(",
"version",
")",
";",
"builder",
".",
"namespace",
"(",
"namespace",
")",
";",
"try",
"{",
"authClient",
"=",
"(",
"AuthenticationClient",
")",
"Class",
".",
"forName",
"(",
"authClientClassName",
")",
".",
"newInstance",
"(",
")",
";",
"authClient",
".",
"setConnectionInfo",
"(",
"host",
",",
"port",
",",
"sslEnabled",
")",
";",
"if",
"(",
"authClient",
".",
"isAuthEnabled",
"(",
")",
")",
"{",
"Properties",
"properties",
"=",
"new",
"Properties",
"(",
")",
";",
"properties",
".",
"setProperty",
"(",
"BasicAuthenticationClient",
".",
"VERIFY_SSL_CERT_PROP_NAME",
",",
"String",
".",
"valueOf",
"(",
"verifySSLCert",
")",
")",
";",
"if",
"(",
"(",
"authClientPropertiesPath",
"==",
"null",
")",
"||",
"(",
"authClientPropertiesPath",
".",
"isEmpty",
"(",
")",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"",
"Authentication client is enabled, but the path for properties ",
"\"",
"+",
"\"",
"file is either empty or null",
"\"",
")",
";",
"}",
"InputStream",
"inStream",
"=",
"new",
"FileInputStream",
"(",
"authClientPropertiesPath",
")",
";",
"try",
"{",
"properties",
".",
"load",
"(",
"inStream",
")",
";",
"}",
"finally",
"{",
"Closeables",
".",
"closeQuietly",
"(",
"inStream",
")",
";",
"}",
"authClient",
".",
"configure",
"(",
"properties",
")",
";",
"}",
"builder",
".",
"authClient",
"(",
"authClient",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Cannot load properties",
"\"",
",",
"e",
")",
";",
"throw",
"Throwables",
".",
"propagate",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Can not resolve class {}: {}",
"\"",
",",
"new",
"Object",
"[",
"]",
"{",
"authClientClassName",
",",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
"}",
")",
";",
"throw",
"Throwables",
".",
"propagate",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"throw",
"Throwables",
".",
"propagate",
"(",
"e",
")",
";",
"}",
"streamClient",
"=",
"builder",
".",
"build",
"(",
")",
";",
"}",
"try",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"writer",
"=",
"streamClient",
".",
"createWriter",
"(",
"streamName",
")",
";",
"}",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"closeWriterQuietly",
"(",
")",
";",
"throw",
"new",
"IOException",
"(",
"\"",
"Can not create stream writer by name: ",
"\"",
"+",
"streamName",
",",
"t",
")",
";",
"}",
"}",
"private",
"void",
"closeClientQuietly",
"(",
")",
"{",
"if",
"(",
"streamClient",
"!=",
"null",
")",
"{",
"try",
"{",
"streamClient",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Error closing stream client. {}",
"\"",
",",
"t",
".",
"getMessage",
"(",
")",
",",
"t",
")",
";",
"}",
"streamClient",
"=",
"null",
";",
"}",
"if",
"(",
"authClient",
"!=",
"null",
")",
"{",
"authClient",
"=",
"null",
";",
"}",
"}",
"private",
"void",
"closeWriterQuietly",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"writer",
"!=",
"null",
")",
"{",
"writer",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Error closing writer. {}",
"\"",
",",
"t",
".",
"getMessage",
"(",
")",
",",
"t",
")",
";",
"}",
"writer",
"=",
"null",
";",
"}",
"public",
"synchronized",
"void",
"start",
"(",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"channel",
"!=",
"null",
",",
"\"",
"No channel configured",
"\"",
")",
";",
"try",
"{",
"createStreamClient",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"Unable to create Stream client by name: {} for host: {}, port: {}. Reason: {} ",
"\"",
",",
"new",
"Object",
"[",
"]",
"{",
"streamName",
",",
"host",
",",
"port",
",",
"t",
".",
"getMessage",
"(",
")",
",",
"t",
"}",
")",
";",
"closeWriterQuietly",
"(",
")",
";",
"closeClientQuietly",
"(",
")",
";",
"lifecycleState",
"=",
"LifecycleState",
".",
"ERROR",
";",
"return",
";",
"}",
"LOG",
".",
"info",
"(",
"\"",
"StreamSink {} started.",
"\"",
",",
"getName",
"(",
")",
")",
";",
"lifecycleState",
"=",
"LifecycleState",
".",
"START",
";",
"}",
"public",
"synchronized",
"void",
"stop",
"(",
")",
"{",
"LOG",
".",
"info",
"(",
"\"",
"StreamSink {} stopping...",
"\"",
",",
"getName",
"(",
")",
")",
";",
"closeWriterQuietly",
"(",
")",
";",
"closeClientQuietly",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"LifecycleState",
"getLifecycleState",
"(",
")",
"{",
"return",
"lifecycleState",
";",
"}",
"@",
"Override",
"public",
"void",
"setName",
"(",
"String",
"name",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"}",
"@",
"Override",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"name",
";",
"}",
"}"
] | CDAP Sink, a Flume sink implementation. | [
"CDAP",
"Sink",
"a",
"Flume",
"sink",
"implementation",
"."
] | [] | [
{
"param": "Sink, LifecycleAware, Configurable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Sink, LifecycleAware, Configurable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b98ab9f58b8d94395971fa915619e52ed69fe7ab | 1and1/Troilus | troilus-core-java7/src/main/java/net/oneandone/troilus/CounterBatchMutationQuery.java | [
"Apache-2.0"
] | Java | CounterBatchMutationQuery | /**
* Counter batch mutation query
*
*/ | Counter batch mutation query | [
"Counter",
"batch",
"mutation",
"query"
] | class CounterBatchMutationQuery extends MutationQuery<CounterMutation> implements CounterMutation {
private final ImmutableList<CounterMutation> batchables;
/**
* @param ctx the context to use
* @param batchables the statements to be performed within the batch
*/
CounterBatchMutationQuery(Context ctx, ImmutableList<CounterMutation> batchables) {
super(ctx);
this.batchables = batchables;
}
////////////////////
// factory methods
@Override
protected CounterBatchMutationQuery newQuery(Context newContext) {
return new CounterBatchMutationQuery(newContext, batchables);
}
private CounterBatchMutationQuery newQuery(ImmutableList<CounterMutation> batchables) {
return new CounterBatchMutationQuery(getContext(), batchables);
}
//
////////////////////
@Override
public CounterBatchMutationQuery combinedWith(CounterMutation other) {
return newQuery(Immutables.join(batchables, other));
}
@Override
public ListenableFuture<Statement> getStatementAsync(final DBSession dbSession) {
Function<CounterMutation, ListenableFuture<Statement>> statementFetcher = new Function<CounterMutation, ListenableFuture<Statement>>() {
public ListenableFuture<Statement> apply(CounterMutation batchable) {
return batchable.getStatementAsync(dbSession);
};
};
return mergeToBatch(Type.COUNTER, batchables.iterator(), statementFetcher);
}
} | [
"class",
"CounterBatchMutationQuery",
"extends",
"MutationQuery",
"<",
"CounterMutation",
">",
"implements",
"CounterMutation",
"{",
"private",
"final",
"ImmutableList",
"<",
"CounterMutation",
">",
"batchables",
";",
"/**\n * @param ctx the context to use\n * @param batchables the statements to be performed within the batch\n */",
"CounterBatchMutationQuery",
"(",
"Context",
"ctx",
",",
"ImmutableList",
"<",
"CounterMutation",
">",
"batchables",
")",
"{",
"super",
"(",
"ctx",
")",
";",
"this",
".",
"batchables",
"=",
"batchables",
";",
"}",
"@",
"Override",
"protected",
"CounterBatchMutationQuery",
"newQuery",
"(",
"Context",
"newContext",
")",
"{",
"return",
"new",
"CounterBatchMutationQuery",
"(",
"newContext",
",",
"batchables",
")",
";",
"}",
"private",
"CounterBatchMutationQuery",
"newQuery",
"(",
"ImmutableList",
"<",
"CounterMutation",
">",
"batchables",
")",
"{",
"return",
"new",
"CounterBatchMutationQuery",
"(",
"getContext",
"(",
")",
",",
"batchables",
")",
";",
"}",
"@",
"Override",
"public",
"CounterBatchMutationQuery",
"combinedWith",
"(",
"CounterMutation",
"other",
")",
"{",
"return",
"newQuery",
"(",
"Immutables",
".",
"join",
"(",
"batchables",
",",
"other",
")",
")",
";",
"}",
"@",
"Override",
"public",
"ListenableFuture",
"<",
"Statement",
">",
"getStatementAsync",
"(",
"final",
"DBSession",
"dbSession",
")",
"{",
"Function",
"<",
"CounterMutation",
",",
"ListenableFuture",
"<",
"Statement",
">",
">",
"statementFetcher",
"=",
"new",
"Function",
"<",
"CounterMutation",
",",
"ListenableFuture",
"<",
"Statement",
">",
">",
"(",
")",
"{",
"public",
"ListenableFuture",
"<",
"Statement",
">",
"apply",
"(",
"CounterMutation",
"batchable",
")",
"{",
"return",
"batchable",
".",
"getStatementAsync",
"(",
"dbSession",
")",
";",
"}",
";",
"}",
";",
"return",
"mergeToBatch",
"(",
"Type",
".",
"COUNTER",
",",
"batchables",
".",
"iterator",
"(",
")",
",",
"statementFetcher",
")",
";",
"}",
"}"
] | Counter batch mutation query | [
"Counter",
"batch",
"mutation",
"query"
] | [
"////////////////////",
"// factory methods",
"//",
"////////////////////"
] | [
{
"param": "CounterMutation",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "CounterMutation",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b98be33cd46a464fa67c780132abe20da04c0db5 | fangshuoshirounet/openid-server | jos-web/src/main/java/cn/net/openid/jos/web/AbstractJosSimpleFormController.java | [
"BSD-3-Clause"
] | Java | AbstractJosSimpleFormController | /**
* Abstract JOS simple form controller, provides domain and session accessor.
*
* @author Sutra Zhou
*/ | Abstract JOS simple form controller, provides domain and session accessor.
@author Sutra Zhou | [
"Abstract",
"JOS",
"simple",
"form",
"controller",
"provides",
"domain",
"and",
"session",
"accessor",
".",
"@author",
"Sutra",
"Zhou"
] | public abstract class AbstractJosSimpleFormController extends
SimpleFormController {
/**
* The logger.
*/
private final Log log = super.logger;
/**
* The JOS service.
*/
private JosService josService;
/**
* Gets the logger.
*
* @return the log
*/
public Log getLog() {
return log;
}
/**
* Get the JOS serviet.
*
* @return the josService
*/
public JosService getJosService() {
return josService;
}
/**
* Set the JOS service.
*
* @param josService
* the josService to set
*/
public void setJosService(final JosService josService) {
this.josService = josService;
}
/**
* Get the current domain.
*
* @param request
* the HTTP request
* @return current domain which parsed from the request url by
* {@link DomainFilter}.
*/
public Domain getDomain(final HttpServletRequest request) {
return DomainFilter.getDomain(request);
}
/* User Session */
/**
* Get user session object.
*
* @param session
* the HTTP session.
* @return User session object in the HTTP session, if not found, create a
* new one
*/
public UserSession getUserSession(final HttpSession session) {
return WebUtils.getOrCreateUserSession(session);
}
/**
* Get user session object.
*
* @param request
* the HTTP Servlet request.
* @return User session object in the HTTP session of the sepcifeid HTTP
* request, if not found, create a new one
*/
public UserSession getUserSession(final HttpServletRequest request) {
return getUserSession(request.getSession());
}
/**
* Get the user object from the HTTP session.
*
* @param session
* the HTTP session
* @return the user object
*/
public User getUser(final HttpSession session) {
return this.getUserSession(session).getUser();
}
/**
* Get the user object from the HTTP Servlet request.
*
* @param request
* the HTTP Servlet request
* @return the user object
*/
public User getUser(final HttpServletRequest request) {
return this.getUserSession(request).getUser();
}
} | [
"public",
"abstract",
"class",
"AbstractJosSimpleFormController",
"extends",
"SimpleFormController",
"{",
"/**\n\t * The logger.\n\t */",
"private",
"final",
"Log",
"log",
"=",
"super",
".",
"logger",
";",
"/**\n\t * The JOS service.\n\t */",
"private",
"JosService",
"josService",
";",
"/**\n\t * Gets the logger.\n\t * \n\t * @return the log\n\t */",
"public",
"Log",
"getLog",
"(",
")",
"{",
"return",
"log",
";",
"}",
"/**\n\t * Get the JOS serviet.\n\t * \n\t * @return the josService\n\t */",
"public",
"JosService",
"getJosService",
"(",
")",
"{",
"return",
"josService",
";",
"}",
"/**\n\t * Set the JOS service.\n\t * \n\t * @param josService\n\t * the josService to set\n\t */",
"public",
"void",
"setJosService",
"(",
"final",
"JosService",
"josService",
")",
"{",
"this",
".",
"josService",
"=",
"josService",
";",
"}",
"/**\n\t * Get the current domain.\n\t * \n\t * @param request\n\t * the HTTP request\n\t * @return current domain which parsed from the request url by\n\t * {@link DomainFilter}.\n\t */",
"public",
"Domain",
"getDomain",
"(",
"final",
"HttpServletRequest",
"request",
")",
"{",
"return",
"DomainFilter",
".",
"getDomain",
"(",
"request",
")",
";",
"}",
"/* User Session */",
"/**\n\t * Get user session object.\n\t * \n\t * @param session\n\t * the HTTP session.\n\t * @return User session object in the HTTP session, if not found, create a\n\t * new one\n\t */",
"public",
"UserSession",
"getUserSession",
"(",
"final",
"HttpSession",
"session",
")",
"{",
"return",
"WebUtils",
".",
"getOrCreateUserSession",
"(",
"session",
")",
";",
"}",
"/**\n\t * Get user session object.\n\t * \n\t * @param request\n\t * the HTTP Servlet request.\n\t * @return User session object in the HTTP session of the sepcifeid HTTP\n\t * request, if not found, create a new one\n\t */",
"public",
"UserSession",
"getUserSession",
"(",
"final",
"HttpServletRequest",
"request",
")",
"{",
"return",
"getUserSession",
"(",
"request",
".",
"getSession",
"(",
")",
")",
";",
"}",
"/**\n\t * Get the user object from the HTTP session.\n\t * \n\t * @param session\n\t * the HTTP session\n\t * @return the user object\n\t */",
"public",
"User",
"getUser",
"(",
"final",
"HttpSession",
"session",
")",
"{",
"return",
"this",
".",
"getUserSession",
"(",
"session",
")",
".",
"getUser",
"(",
")",
";",
"}",
"/**\n\t * Get the user object from the HTTP Servlet request.\n\t * \n\t * @param request\n\t * the HTTP Servlet request\n\t * @return the user object\n\t */",
"public",
"User",
"getUser",
"(",
"final",
"HttpServletRequest",
"request",
")",
"{",
"return",
"this",
".",
"getUserSession",
"(",
"request",
")",
".",
"getUser",
"(",
")",
";",
"}",
"}"
] | Abstract JOS simple form controller, provides domain and session accessor. | [
"Abstract",
"JOS",
"simple",
"form",
"controller",
"provides",
"domain",
"and",
"session",
"accessor",
"."
] | [] | [
{
"param": "SimpleFormController",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "SimpleFormController",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b98c966496d113020fb71b679827929e5fccdd18 | iliasger/JDEECo | jdeeco-core/src/cz/cuni/mff/d3s/deeco/invokable/SchedulableProcess.java | [
"Apache-2.0"
] | Java | SchedulableProcess | /**
* Base class defining common functionalities for all schedulable processes.
*
* @author Michal Kit
*
*/ | Base class defining common functionalities for all schedulable processes.
@author Michal Kit | [
"Base",
"class",
"defining",
"common",
"functionalities",
"for",
"all",
"schedulable",
"processes",
".",
"@author",
"Michal",
"Kit"
] | public abstract class SchedulableProcess implements Serializable {
private static final long serialVersionUID = -642546184205115045L;
// these are assigned after preprocessing, thus musn't be final
public KnowledgeManager km;
public ClassLoader contextClassLoader;
public final ProcessSchedule scheduling;
public static ThreadLocal<IRuntime> runtime = new ThreadLocal<>();
public SchedulableProcess(KnowledgeManager km, ProcessSchedule scheduling,
ClassLoader contextClassLoader) {
this.scheduling = scheduling;
this.km = km;
this.contextClassLoader = contextClassLoader;
}
protected Object[] getParameterMethodValues(List<Parameter> in,
List<Parameter> inOut, List<Parameter> out) throws KMException {
return getParameterMethodValues(in, out, inOut, null, null, null);
}
protected Object[] getParameterMethodValues(List<Parameter> in,
List<Parameter> inOut, List<Parameter> out, ISession session)
throws KMException {
return getParameterMethodValues(in, inOut, out, session, null, null);
}
protected Object[] getParameterMethodValues(List<Parameter> in,
List<Parameter> inOut, List<Parameter> out, ISession session,
String coordinator, String member) throws KMException {
final List<Parameter> parametersIn = new ArrayList<Parameter>();
parametersIn.addAll(in);
parametersIn.addAll(inOut);
Object value;
Object[] result = new Object[parametersIn.size()
+ ((out != null) ? out.size() : 0)];
ISession localSession;
if (session == null) {
localSession = km.createSession();
localSession.begin();
} else
localSession = session;
try {
while (localSession.repeat()) {
for (Parameter p : parametersIn) {
value = getParameterInstance(p, coordinator, member, km,
localSession);
result[p.index] = value;
}
if (session == null)
localSession.end();
else
break;
}
final List<Parameter> parametersOut = out;
for (Parameter p : parametersOut)
result[p.index] = getParameterInstance(p.type);
return result;
} catch (KMException kme) {
if (kme instanceof KMCastException)
Log.e(kme.getMessage());
if (session == null)
localSession.cancel();
throw kme;
} catch (Exception e) {
Log.e("", e);
return null;
}
}
/**
* Function used to store computed values during the process method
* execution in the knowledge repository.
*
* @param parameterValues
* list of method all parameterTypes
* @param out
* list of output parameter descriptions
* @param inOut
* list of both output and input parameter descriptions
* @param root
* knowledge level for which parameterTypes should stored.
*/
protected void putParameterMethodValues(Object[] parameterValues,
List<Parameter> inOut, List<Parameter> out) {
putParameterMethodValues(parameterValues, inOut, out, null, null, null);
}
protected void putParameterMethodValues(Object[] parameterValues,
List<Parameter> inOut, List<Parameter> out, ISession session) {
putParameterMethodValues(parameterValues, inOut, out, session, null,
null);
}
/**
* Function used to store computed values during the process method
* execution in the knowledge repository. This version is session oriented.
*
* @param parameterValues
* list of method all parameterTypes
* @param out
* list of output parameter descriptions
* @param inOut
* list of both output and input parameter descriptions
* @param root
* knowledge level for which parameterTypes should stored
* @param session
* session instance within which all the storing operations
* should be performed.
*/
protected void putParameterMethodValues(Object[] parameterValues,
List<Parameter> inOut, List<Parameter> out, ISession session,
String coordinator, String member) {
if (parameterValues != null) {
final List<Parameter> parameters = new ArrayList<Parameter>();
parameters.addAll(out);
parameters.addAll(inOut);
ISession localSession;
if (session == null) {
localSession = km.createSession();
localSession.begin();
} else
localSession = session;
try {
while (localSession.repeat()) {
for (Parameter p : parameters) {
Object parameterValue = parameterValues[p.index];
km.alterKnowledge(
p.kPath.getEvaluatedPath(km, coordinator,
member, session),
p.type.isOutWrapper() ? ((OutWrapper) parameterValue).value
: parameterValue, session);
}
if (session == null)
localSession.end();
else
break;
}
} catch (Exception e) {
if (session == null)
localSession.cancel();
Log.e("", e);
}
}
}
/**
* Checks if the process has periodic scheduling.
*
* @return true or false depending on the process scheduling.
*/
public boolean isPeriodic() {
return scheduling instanceof ProcessPeriodicSchedule;
}
/**
* Checks if the process has triggered scheduling.
*
* @return true or false depending on the process scheduling.
*/
public boolean isTriggered() {
return scheduling instanceof ProcessTriggeredSchedule;
}
/**
* Function invokes single process execution.
*/
public void invoke() {
invoke(null, null);
}
private Object getParameterInstance(TypeDescription expectedParamType)
throws KMCastException {
try {
if (expectedParamType.isMap()) {
if (expectedParamType.isInterface())
return new HashMap<String, Object>();
else
return expectedParamType.newInstance();
} else if (expectedParamType.isList()) {
if (expectedParamType.isInterface())
return new ArrayList<Object>();
else
return expectedParamType.newInstance();
} else
return expectedParamType.newInstance();
} catch (Exception e) {
throw new KMCastException("Out parameter instantiation exception");
}
}
private Object getParameterInstance(Parameter p, String coordinator,
String member, KnowledgeManager km, ISession session)
throws KMException, Exception {
if (p.type.isOutWrapper()) {
OutWrapper ow = (OutWrapper) p.type.newInstance();
ow.value = km.getKnowledge(
p.kPath.getEvaluatedPath(km, coordinator, member, session),
p.type.getParametricTypeAt(0), session);
return ow;
} else {
return km.getKnowledge(
p.kPath.getEvaluatedPath(km, coordinator, member, session),
p.type, session);
}
}
public abstract void invoke(String triggererId, ETriggerType recipientMode);
} | [
"public",
"abstract",
"class",
"SchedulableProcess",
"implements",
"Serializable",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"-",
"642546184205115045L",
";",
"public",
"KnowledgeManager",
"km",
";",
"public",
"ClassLoader",
"contextClassLoader",
";",
"public",
"final",
"ProcessSchedule",
"scheduling",
";",
"public",
"static",
"ThreadLocal",
"<",
"IRuntime",
">",
"runtime",
"=",
"new",
"ThreadLocal",
"<",
">",
"(",
")",
";",
"public",
"SchedulableProcess",
"(",
"KnowledgeManager",
"km",
",",
"ProcessSchedule",
"scheduling",
",",
"ClassLoader",
"contextClassLoader",
")",
"{",
"this",
".",
"scheduling",
"=",
"scheduling",
";",
"this",
".",
"km",
"=",
"km",
";",
"this",
".",
"contextClassLoader",
"=",
"contextClassLoader",
";",
"}",
"protected",
"Object",
"[",
"]",
"getParameterMethodValues",
"(",
"List",
"<",
"Parameter",
">",
"in",
",",
"List",
"<",
"Parameter",
">",
"inOut",
",",
"List",
"<",
"Parameter",
">",
"out",
")",
"throws",
"KMException",
"{",
"return",
"getParameterMethodValues",
"(",
"in",
",",
"out",
",",
"inOut",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}",
"protected",
"Object",
"[",
"]",
"getParameterMethodValues",
"(",
"List",
"<",
"Parameter",
">",
"in",
",",
"List",
"<",
"Parameter",
">",
"inOut",
",",
"List",
"<",
"Parameter",
">",
"out",
",",
"ISession",
"session",
")",
"throws",
"KMException",
"{",
"return",
"getParameterMethodValues",
"(",
"in",
",",
"inOut",
",",
"out",
",",
"session",
",",
"null",
",",
"null",
")",
";",
"}",
"protected",
"Object",
"[",
"]",
"getParameterMethodValues",
"(",
"List",
"<",
"Parameter",
">",
"in",
",",
"List",
"<",
"Parameter",
">",
"inOut",
",",
"List",
"<",
"Parameter",
">",
"out",
",",
"ISession",
"session",
",",
"String",
"coordinator",
",",
"String",
"member",
")",
"throws",
"KMException",
"{",
"final",
"List",
"<",
"Parameter",
">",
"parametersIn",
"=",
"new",
"ArrayList",
"<",
"Parameter",
">",
"(",
")",
";",
"parametersIn",
".",
"addAll",
"(",
"in",
")",
";",
"parametersIn",
".",
"addAll",
"(",
"inOut",
")",
";",
"Object",
"value",
";",
"Object",
"[",
"]",
"result",
"=",
"new",
"Object",
"[",
"parametersIn",
".",
"size",
"(",
")",
"+",
"(",
"(",
"out",
"!=",
"null",
")",
"?",
"out",
".",
"size",
"(",
")",
":",
"0",
")",
"]",
";",
"ISession",
"localSession",
";",
"if",
"(",
"session",
"==",
"null",
")",
"{",
"localSession",
"=",
"km",
".",
"createSession",
"(",
")",
";",
"localSession",
".",
"begin",
"(",
")",
";",
"}",
"else",
"localSession",
"=",
"session",
";",
"try",
"{",
"while",
"(",
"localSession",
".",
"repeat",
"(",
")",
")",
"{",
"for",
"(",
"Parameter",
"p",
":",
"parametersIn",
")",
"{",
"value",
"=",
"getParameterInstance",
"(",
"p",
",",
"coordinator",
",",
"member",
",",
"km",
",",
"localSession",
")",
";",
"result",
"[",
"p",
".",
"index",
"]",
"=",
"value",
";",
"}",
"if",
"(",
"session",
"==",
"null",
")",
"localSession",
".",
"end",
"(",
")",
";",
"else",
"break",
";",
"}",
"final",
"List",
"<",
"Parameter",
">",
"parametersOut",
"=",
"out",
";",
"for",
"(",
"Parameter",
"p",
":",
"parametersOut",
")",
"result",
"[",
"p",
".",
"index",
"]",
"=",
"getParameterInstance",
"(",
"p",
".",
"type",
")",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"KMException",
"kme",
")",
"{",
"if",
"(",
"kme",
"instanceof",
"KMCastException",
")",
"Log",
".",
"e",
"(",
"kme",
".",
"getMessage",
"(",
")",
")",
";",
"if",
"(",
"session",
"==",
"null",
")",
"localSession",
".",
"cancel",
"(",
")",
";",
"throw",
"kme",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"\"",
"\"",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}",
"/**\n\t * Function used to store computed values during the process method\n\t * execution in the knowledge repository.\n\t * \n\t * @param parameterValues\n\t * list of method all parameterTypes\n\t * @param out\n\t * list of output parameter descriptions\n\t * @param inOut\n\t * list of both output and input parameter descriptions\n\t * @param root\n\t * knowledge level for which parameterTypes should stored.\n\t */",
"protected",
"void",
"putParameterMethodValues",
"(",
"Object",
"[",
"]",
"parameterValues",
",",
"List",
"<",
"Parameter",
">",
"inOut",
",",
"List",
"<",
"Parameter",
">",
"out",
")",
"{",
"putParameterMethodValues",
"(",
"parameterValues",
",",
"inOut",
",",
"out",
",",
"null",
",",
"null",
",",
"null",
")",
";",
"}",
"protected",
"void",
"putParameterMethodValues",
"(",
"Object",
"[",
"]",
"parameterValues",
",",
"List",
"<",
"Parameter",
">",
"inOut",
",",
"List",
"<",
"Parameter",
">",
"out",
",",
"ISession",
"session",
")",
"{",
"putParameterMethodValues",
"(",
"parameterValues",
",",
"inOut",
",",
"out",
",",
"session",
",",
"null",
",",
"null",
")",
";",
"}",
"/**\n\t * Function used to store computed values during the process method\n\t * execution in the knowledge repository. This version is session oriented.\n\t * \n\t * @param parameterValues\n\t * list of method all parameterTypes\n\t * @param out\n\t * list of output parameter descriptions\n\t * @param inOut\n\t * list of both output and input parameter descriptions\n\t * @param root\n\t * knowledge level for which parameterTypes should stored\n\t * @param session\n\t * session instance within which all the storing operations\n\t * should be performed.\n\t */",
"protected",
"void",
"putParameterMethodValues",
"(",
"Object",
"[",
"]",
"parameterValues",
",",
"List",
"<",
"Parameter",
">",
"inOut",
",",
"List",
"<",
"Parameter",
">",
"out",
",",
"ISession",
"session",
",",
"String",
"coordinator",
",",
"String",
"member",
")",
"{",
"if",
"(",
"parameterValues",
"!=",
"null",
")",
"{",
"final",
"List",
"<",
"Parameter",
">",
"parameters",
"=",
"new",
"ArrayList",
"<",
"Parameter",
">",
"(",
")",
";",
"parameters",
".",
"addAll",
"(",
"out",
")",
";",
"parameters",
".",
"addAll",
"(",
"inOut",
")",
";",
"ISession",
"localSession",
";",
"if",
"(",
"session",
"==",
"null",
")",
"{",
"localSession",
"=",
"km",
".",
"createSession",
"(",
")",
";",
"localSession",
".",
"begin",
"(",
")",
";",
"}",
"else",
"localSession",
"=",
"session",
";",
"try",
"{",
"while",
"(",
"localSession",
".",
"repeat",
"(",
")",
")",
"{",
"for",
"(",
"Parameter",
"p",
":",
"parameters",
")",
"{",
"Object",
"parameterValue",
"=",
"parameterValues",
"[",
"p",
".",
"index",
"]",
";",
"km",
".",
"alterKnowledge",
"(",
"p",
".",
"kPath",
".",
"getEvaluatedPath",
"(",
"km",
",",
"coordinator",
",",
"member",
",",
"session",
")",
",",
"p",
".",
"type",
".",
"isOutWrapper",
"(",
")",
"?",
"(",
"(",
"OutWrapper",
")",
"parameterValue",
")",
".",
"value",
":",
"parameterValue",
",",
"session",
")",
";",
"}",
"if",
"(",
"session",
"==",
"null",
")",
"localSession",
".",
"end",
"(",
")",
";",
"else",
"break",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"session",
"==",
"null",
")",
"localSession",
".",
"cancel",
"(",
")",
";",
"Log",
".",
"e",
"(",
"\"",
"\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"/**\n\t * Checks if the process has periodic scheduling.\n\t * \n\t * @return true or false depending on the process scheduling.\n\t */",
"public",
"boolean",
"isPeriodic",
"(",
")",
"{",
"return",
"scheduling",
"instanceof",
"ProcessPeriodicSchedule",
";",
"}",
"/**\n\t * Checks if the process has triggered scheduling.\n\t * \n\t * @return true or false depending on the process scheduling.\n\t */",
"public",
"boolean",
"isTriggered",
"(",
")",
"{",
"return",
"scheduling",
"instanceof",
"ProcessTriggeredSchedule",
";",
"}",
"/**\n\t * Function invokes single process execution.\n\t */",
"public",
"void",
"invoke",
"(",
")",
"{",
"invoke",
"(",
"null",
",",
"null",
")",
";",
"}",
"private",
"Object",
"getParameterInstance",
"(",
"TypeDescription",
"expectedParamType",
")",
"throws",
"KMCastException",
"{",
"try",
"{",
"if",
"(",
"expectedParamType",
".",
"isMap",
"(",
")",
")",
"{",
"if",
"(",
"expectedParamType",
".",
"isInterface",
"(",
")",
")",
"return",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"else",
"return",
"expectedParamType",
".",
"newInstance",
"(",
")",
";",
"}",
"else",
"if",
"(",
"expectedParamType",
".",
"isList",
"(",
")",
")",
"{",
"if",
"(",
"expectedParamType",
".",
"isInterface",
"(",
")",
")",
"return",
"new",
"ArrayList",
"<",
"Object",
">",
"(",
")",
";",
"else",
"return",
"expectedParamType",
".",
"newInstance",
"(",
")",
";",
"}",
"else",
"return",
"expectedParamType",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"KMCastException",
"(",
"\"",
"Out parameter instantiation exception",
"\"",
")",
";",
"}",
"}",
"private",
"Object",
"getParameterInstance",
"(",
"Parameter",
"p",
",",
"String",
"coordinator",
",",
"String",
"member",
",",
"KnowledgeManager",
"km",
",",
"ISession",
"session",
")",
"throws",
"KMException",
",",
"Exception",
"{",
"if",
"(",
"p",
".",
"type",
".",
"isOutWrapper",
"(",
")",
")",
"{",
"OutWrapper",
"ow",
"=",
"(",
"OutWrapper",
")",
"p",
".",
"type",
".",
"newInstance",
"(",
")",
";",
"ow",
".",
"value",
"=",
"km",
".",
"getKnowledge",
"(",
"p",
".",
"kPath",
".",
"getEvaluatedPath",
"(",
"km",
",",
"coordinator",
",",
"member",
",",
"session",
")",
",",
"p",
".",
"type",
".",
"getParametricTypeAt",
"(",
"0",
")",
",",
"session",
")",
";",
"return",
"ow",
";",
"}",
"else",
"{",
"return",
"km",
".",
"getKnowledge",
"(",
"p",
".",
"kPath",
".",
"getEvaluatedPath",
"(",
"km",
",",
"coordinator",
",",
"member",
",",
"session",
")",
",",
"p",
".",
"type",
",",
"session",
")",
";",
"}",
"}",
"public",
"abstract",
"void",
"invoke",
"(",
"String",
"triggererId",
",",
"ETriggerType",
"recipientMode",
")",
";",
"}"
] | Base class defining common functionalities for all schedulable processes. | [
"Base",
"class",
"defining",
"common",
"functionalities",
"for",
"all",
"schedulable",
"processes",
"."
] | [
"// these are assigned after preprocessing, thus musn't be final"
] | [
{
"param": "Serializable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Serializable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9930096de083d2f13b308607f0c8f173647afac | dolphingarlic/sketch-frontend | src/main/java/sketch/util/DebugOut.java | [
"X11"
] | Java | DebugOut | /**
* Debugging utilities, including an "assert" that doesn't require -ea.
* @author gatoatigrado (nicholas tung) [email: ntung at ntung]
* @license This file is licensed under BSD license, available at
* http://creativecommons.org/licenses/BSD/. While not required, if you
* make changes, please consider contributing back!
*/ | Debugging utilities, including an "assert" that doesn't require -ea. | [
"Debugging",
"utilities",
"including",
"an",
"\"",
"assert",
"\"",
"that",
"doesn",
"'",
"t",
"require",
"-",
"ea",
"."
] | public class DebugOut {
/*
* for a in $(seq 0 1); do for i in $(seq 30 37); do echo -e
* "\x1b[${a};${i}m${a} - ${i}\x1b[0m"; done; done
*/
public final static String BASH_BOLD = "1;30";
public final static String BASH_RED = "0;31";
public final static String BASH_BLUE = "0;34";
public final static String BASH_GREEN = "0;32";
public final static String BASH_BROWN = "0;33";
public final static String BASH_GREY = "1;30";
public final static String BASH_SALMON = "1;31";
public final static String BASH_LIGHT_BLUE = "1;34";
/** don't use BASH_BLACK for people using black-background terminals */
public final static String BASH_DEFAULT = "0";
public static boolean no_bash_color = false;
/** prevent infinite recursion when printing errors */
protected static boolean inAssertFalse = false;
protected static StrictlyMonotonicTime time_ = new StrictlyMonotonicTime(0.0001);
public static String bash_code(String bash_color) {
return "\u001b[" + bash_color + "m";
}
public static void print_stderr_colored(String color, String prefix, String sep,
boolean nice_arrays, Object... text)
{
if (nice_arrays) {
for (int a = 0; a < text.length; a++) {
if (text[a] == null) {
text[a] = "null";
} else if (text[a].getClass().isArray()) {
Object[] arr = (Object[]) text[a];
text[a] = (new ScRichString("\n")).join(arr);
}
}
}
if (no_bash_color) {
System.err.println(String.format(" %s ", prefix)
+ (new ScRichString(sep)).join(text));
} else {
System.err.println(String
.format(" \u001b[%sm%s ", color, prefix)
+ (new ScRichString(sep)).join(text) + "\u001b[0m");
}
}
public static void print_err_colored(String color, String prefix,
String sep, boolean nice_arrays, Object... text)
{
System.err.flush();
System.out.flush();
print_stderr_colored(color, prefix, sep, nice_arrays, text);
System.err.flush();
System.out.flush();
}
public static void print_assert_false_colored(String color, String prefix,
String sep, boolean nice_arrays, Object... text)
{
System.err.flush();
System.out.flush();
if (inAssertFalse) {
return;
} else {
inAssertFalse = true;
}
print_stderr_colored(color, prefix, sep, nice_arrays, text);
System.err.flush();
System.out.flush();
}
public static void print(Object... text) {
print_stderr_colored(BASH_BLUE, "[debug]", " ", false, text);
}
public static void fmt(String fmt, Object... args) {
print(String.format(fmt, args));
}
public static synchronized void print_mt(Object... text) {
print_stderr_colored(BASH_LIGHT_BLUE, thread_indentation.get() + "[debug-"
+ Thread.currentThread().getId() + "]", " ", false, text);
}
/** try not to go overboard with the # of these... */
public enum StatusPrefix {
NOTE, DEBUG, FAILURE, WARNING, ERROR
}
/**
* try to use specialized functions, printNote, printError, etc. unless you want
* custom formatting
*/
public static void printStatusMessage(String color, StatusPrefix prefix, String sep,
boolean nice_arrays, Object... description)
{
double time = time_.getTime();
print_stderr_colored(color, String.format("[%.4f - %s]", time, prefix), sep,
nice_arrays, description);
}
/**
* try to use specialized functions, printNote, printError, etc. unless you want
* custom formatting
*/
public static void printErrStatusMessage(String color, StatusPrefix prefix, String sep,
boolean nice_arrays, Object... description)
{
double time = time_.getTime();
print_err_colored(color, String.format("[%.4f - %s]", time, prefix), sep,
nice_arrays, description);
}
public static void printDebug(Object... description) {
printErrStatusMessage(BASH_GREEN, StatusPrefix.DEBUG, " ", false, description);
}
public static void printFailure(Object... description) {
printErrStatusMessage(BASH_RED, StatusPrefix.FAILURE, " ", false, description);
}
public static void printError(Object... description) {
printErrStatusMessage(BASH_RED, StatusPrefix.ERROR, " ", false, description);
}
public static void printNote(Object... description) {
printErrStatusMessage(BASH_BROWN, StatusPrefix.NOTE, " ", false, description);
}
public static void printWarning(Object... description) {
printErrStatusMessage(BASH_SALMON, StatusPrefix.WARNING, " ", false, description);
}
public static void assertFalseMsg(String msg, Object... description) {
print_assert_false_colored(BASH_RED, msg, " ", false, description);
inAssertFalse = false;
assert (false);
throw new java.lang.IllegalStateException("please enable asserts.");
}
public static <T> T assertFalse(Object... description) {
assertFalseMsg("[ASSERT FAILURE] ", description);
return null;
}
/** NOTE - don't use this in fast loops, as arrays are created */
public static void assertSlow(boolean truth, Object... description) {
if (!truth) {
assertFalse(description);
}
}
public static <T> T not_implemented(Object... what) {
Object[] what_prefixed = new Object[what.length + 1];
what_prefixed[0] = "Not implemented -";
System.arraycopy(what, 0, what_prefixed, 1, what.length);
return (T) assertFalse(what_prefixed);
}
public static void todo(Object... what) {
print_stderr_colored(BASH_BROWN, "[TODO] ", " ", false, what);
}
protected static class ThreadIndentation extends ThreadLocal<String> {
private static AtomicInteger ctr = new AtomicInteger(0);
@Override
protected String initialValue() {
String result = "";
int n_spaces = ctr.getAndIncrement();
for (int a = 0; a < n_spaces; a++) {
result += " ";
}
return result;
}
public static void print_colored(String color, String prefix,
String sep, boolean nice_arrays, Object... text)
{
if (inAssertFalse) {
return;
}
if (nice_arrays) {
for (int a = 0; a < text.length; a++) {
if (text[a] == null) {
text[a] = "null";
} else if (text[a].getClass().isArray()) {
Object[] arr = (Object[]) text[a];
text[a] = (new ScRichString("\n")).join(arr);
}
}
}
if (no_bash_color) {
System.err.println(String.format(" %s ", prefix)
+ (new ScRichString(sep)).join(text));
} else {
System.err.println(String.format(" \u001b[%sm%s ", color,
prefix)
+ (new ScRichString(sep)).join(text) + "\u001b[0m");
}
}
}
protected static ThreadIndentation thread_indentation =
new ThreadIndentation();
public static void print_exception(String text, Exception e) {
print_stderr_colored(BASH_RED, "[EXCEPTION]", "\n", false, text);
e.printStackTrace();
}
public static void fail_exception(String text, Exception e) {
print_assert_false_colored(BASH_RED, "[EXCEPTION]", "\n", false, text);
e.printStackTrace();
throw new RuntimeException(e);
}
public static void debug_quit_exception(String text, Exception e) {
print_exception(text, e);
System.exit(1);
}
} | [
"public",
"class",
"DebugOut",
"{",
"/*\n * for a in $(seq 0 1); do for i in $(seq 30 37); do echo -e\n * \"\\x1b[${a};${i}m${a} - ${i}\\x1b[0m\"; done; done\n */",
"public",
"final",
"static",
"String",
"BASH_BOLD",
"=",
"\"",
"1;30",
"\"",
";",
"public",
"final",
"static",
"String",
"BASH_RED",
"=",
"\"",
"0;31",
"\"",
";",
"public",
"final",
"static",
"String",
"BASH_BLUE",
"=",
"\"",
"0;34",
"\"",
";",
"public",
"final",
"static",
"String",
"BASH_GREEN",
"=",
"\"",
"0;32",
"\"",
";",
"public",
"final",
"static",
"String",
"BASH_BROWN",
"=",
"\"",
"0;33",
"\"",
";",
"public",
"final",
"static",
"String",
"BASH_GREY",
"=",
"\"",
"1;30",
"\"",
";",
"public",
"final",
"static",
"String",
"BASH_SALMON",
"=",
"\"",
"1;31",
"\"",
";",
"public",
"final",
"static",
"String",
"BASH_LIGHT_BLUE",
"=",
"\"",
"1;34",
"\"",
";",
"/** don't use BASH_BLACK for people using black-background terminals */",
"public",
"final",
"static",
"String",
"BASH_DEFAULT",
"=",
"\"",
"0",
"\"",
";",
"public",
"static",
"boolean",
"no_bash_color",
"=",
"false",
";",
"/** prevent infinite recursion when printing errors */",
"protected",
"static",
"boolean",
"inAssertFalse",
"=",
"false",
";",
"protected",
"static",
"StrictlyMonotonicTime",
"time_",
"=",
"new",
"StrictlyMonotonicTime",
"(",
"0.0001",
")",
";",
"public",
"static",
"String",
"bash_code",
"(",
"String",
"bash_color",
")",
"{",
"return",
"\"",
"\\u001b",
"[",
"\"",
"+",
"bash_color",
"+",
"\"",
"m",
"\"",
";",
"}",
"public",
"static",
"void",
"print_stderr_colored",
"(",
"String",
"color",
",",
"String",
"prefix",
",",
"String",
"sep",
",",
"boolean",
"nice_arrays",
",",
"Object",
"...",
"text",
")",
"{",
"if",
"(",
"nice_arrays",
")",
"{",
"for",
"(",
"int",
"a",
"=",
"0",
";",
"a",
"<",
"text",
".",
"length",
";",
"a",
"++",
")",
"{",
"if",
"(",
"text",
"[",
"a",
"]",
"==",
"null",
")",
"{",
"text",
"[",
"a",
"]",
"=",
"\"",
"null",
"\"",
";",
"}",
"else",
"if",
"(",
"text",
"[",
"a",
"]",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
")",
"{",
"Object",
"[",
"]",
"arr",
"=",
"(",
"Object",
"[",
"]",
")",
"text",
"[",
"a",
"]",
";",
"text",
"[",
"a",
"]",
"=",
"(",
"new",
"ScRichString",
"(",
"\"",
"\\n",
"\"",
")",
")",
".",
"join",
"(",
"arr",
")",
";",
"}",
"}",
"}",
"if",
"(",
"no_bash_color",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"String",
".",
"format",
"(",
"\"",
" %s ",
"\"",
",",
"prefix",
")",
"+",
"(",
"new",
"ScRichString",
"(",
"sep",
")",
")",
".",
"join",
"(",
"text",
")",
")",
";",
"}",
"else",
"{",
"System",
".",
"err",
".",
"println",
"(",
"String",
".",
"format",
"(",
"\"",
" ",
"\\u001b",
"[%sm%s ",
"\"",
",",
"color",
",",
"prefix",
")",
"+",
"(",
"new",
"ScRichString",
"(",
"sep",
")",
")",
".",
"join",
"(",
"text",
")",
"+",
"\"",
"\\u001b",
"[0m",
"\"",
")",
";",
"}",
"}",
"public",
"static",
"void",
"print_err_colored",
"(",
"String",
"color",
",",
"String",
"prefix",
",",
"String",
"sep",
",",
"boolean",
"nice_arrays",
",",
"Object",
"...",
"text",
")",
"{",
"System",
".",
"err",
".",
"flush",
"(",
")",
";",
"System",
".",
"out",
".",
"flush",
"(",
")",
";",
"print_stderr_colored",
"(",
"color",
",",
"prefix",
",",
"sep",
",",
"nice_arrays",
",",
"text",
")",
";",
"System",
".",
"err",
".",
"flush",
"(",
")",
";",
"System",
".",
"out",
".",
"flush",
"(",
")",
";",
"}",
"public",
"static",
"void",
"print_assert_false_colored",
"(",
"String",
"color",
",",
"String",
"prefix",
",",
"String",
"sep",
",",
"boolean",
"nice_arrays",
",",
"Object",
"...",
"text",
")",
"{",
"System",
".",
"err",
".",
"flush",
"(",
")",
";",
"System",
".",
"out",
".",
"flush",
"(",
")",
";",
"if",
"(",
"inAssertFalse",
")",
"{",
"return",
";",
"}",
"else",
"{",
"inAssertFalse",
"=",
"true",
";",
"}",
"print_stderr_colored",
"(",
"color",
",",
"prefix",
",",
"sep",
",",
"nice_arrays",
",",
"text",
")",
";",
"System",
".",
"err",
".",
"flush",
"(",
")",
";",
"System",
".",
"out",
".",
"flush",
"(",
")",
";",
"}",
"public",
"static",
"void",
"print",
"(",
"Object",
"...",
"text",
")",
"{",
"print_stderr_colored",
"(",
"BASH_BLUE",
",",
"\"",
"[debug]",
"\"",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"text",
")",
";",
"}",
"public",
"static",
"void",
"fmt",
"(",
"String",
"fmt",
",",
"Object",
"...",
"args",
")",
"{",
"print",
"(",
"String",
".",
"format",
"(",
"fmt",
",",
"args",
")",
")",
";",
"}",
"public",
"static",
"synchronized",
"void",
"print_mt",
"(",
"Object",
"...",
"text",
")",
"{",
"print_stderr_colored",
"(",
"BASH_LIGHT_BLUE",
",",
"thread_indentation",
".",
"get",
"(",
")",
"+",
"\"",
"[debug-",
"\"",
"+",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getId",
"(",
")",
"+",
"\"",
"]",
"\"",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"text",
")",
";",
"}",
"/** try not to go overboard with the # of these... */",
"public",
"enum",
"StatusPrefix",
"{",
"NOTE",
",",
"DEBUG",
",",
"FAILURE",
",",
"WARNING",
",",
"ERROR",
"}",
"/**\n * try to use specialized functions, printNote, printError, etc. unless you want\n * custom formatting\n */",
"public",
"static",
"void",
"printStatusMessage",
"(",
"String",
"color",
",",
"StatusPrefix",
"prefix",
",",
"String",
"sep",
",",
"boolean",
"nice_arrays",
",",
"Object",
"...",
"description",
")",
"{",
"double",
"time",
"=",
"time_",
".",
"getTime",
"(",
")",
";",
"print_stderr_colored",
"(",
"color",
",",
"String",
".",
"format",
"(",
"\"",
"[%.4f - %s]",
"\"",
",",
"time",
",",
"prefix",
")",
",",
"sep",
",",
"nice_arrays",
",",
"description",
")",
";",
"}",
"/**\n * try to use specialized functions, printNote, printError, etc. unless you want\n * custom formatting\n */",
"public",
"static",
"void",
"printErrStatusMessage",
"(",
"String",
"color",
",",
"StatusPrefix",
"prefix",
",",
"String",
"sep",
",",
"boolean",
"nice_arrays",
",",
"Object",
"...",
"description",
")",
"{",
"double",
"time",
"=",
"time_",
".",
"getTime",
"(",
")",
";",
"print_err_colored",
"(",
"color",
",",
"String",
".",
"format",
"(",
"\"",
"[%.4f - %s]",
"\"",
",",
"time",
",",
"prefix",
")",
",",
"sep",
",",
"nice_arrays",
",",
"description",
")",
";",
"}",
"public",
"static",
"void",
"printDebug",
"(",
"Object",
"...",
"description",
")",
"{",
"printErrStatusMessage",
"(",
"BASH_GREEN",
",",
"StatusPrefix",
".",
"DEBUG",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"description",
")",
";",
"}",
"public",
"static",
"void",
"printFailure",
"(",
"Object",
"...",
"description",
")",
"{",
"printErrStatusMessage",
"(",
"BASH_RED",
",",
"StatusPrefix",
".",
"FAILURE",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"description",
")",
";",
"}",
"public",
"static",
"void",
"printError",
"(",
"Object",
"...",
"description",
")",
"{",
"printErrStatusMessage",
"(",
"BASH_RED",
",",
"StatusPrefix",
".",
"ERROR",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"description",
")",
";",
"}",
"public",
"static",
"void",
"printNote",
"(",
"Object",
"...",
"description",
")",
"{",
"printErrStatusMessage",
"(",
"BASH_BROWN",
",",
"StatusPrefix",
".",
"NOTE",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"description",
")",
";",
"}",
"public",
"static",
"void",
"printWarning",
"(",
"Object",
"...",
"description",
")",
"{",
"printErrStatusMessage",
"(",
"BASH_SALMON",
",",
"StatusPrefix",
".",
"WARNING",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"description",
")",
";",
"}",
"public",
"static",
"void",
"assertFalseMsg",
"(",
"String",
"msg",
",",
"Object",
"...",
"description",
")",
"{",
"print_assert_false_colored",
"(",
"BASH_RED",
",",
"msg",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"description",
")",
";",
"inAssertFalse",
"=",
"false",
";",
"assert",
"(",
"false",
")",
";",
"throw",
"new",
"java",
".",
"lang",
".",
"IllegalStateException",
"(",
"\"",
"please enable asserts.",
"\"",
")",
";",
"}",
"public",
"static",
"<",
"T",
">",
"T",
"assertFalse",
"(",
"Object",
"...",
"description",
")",
"{",
"assertFalseMsg",
"(",
"\"",
"[ASSERT FAILURE] ",
"\"",
",",
"description",
")",
";",
"return",
"null",
";",
"}",
"/** NOTE - don't use this in fast loops, as arrays are created */",
"public",
"static",
"void",
"assertSlow",
"(",
"boolean",
"truth",
",",
"Object",
"...",
"description",
")",
"{",
"if",
"(",
"!",
"truth",
")",
"{",
"assertFalse",
"(",
"description",
")",
";",
"}",
"}",
"public",
"static",
"<",
"T",
">",
"T",
"not_implemented",
"(",
"Object",
"...",
"what",
")",
"{",
"Object",
"[",
"]",
"what_prefixed",
"=",
"new",
"Object",
"[",
"what",
".",
"length",
"+",
"1",
"]",
";",
"what_prefixed",
"[",
"0",
"]",
"=",
"\"",
"Not implemented -",
"\"",
";",
"System",
".",
"arraycopy",
"(",
"what",
",",
"0",
",",
"what_prefixed",
",",
"1",
",",
"what",
".",
"length",
")",
";",
"return",
"(",
"T",
")",
"assertFalse",
"(",
"what_prefixed",
")",
";",
"}",
"public",
"static",
"void",
"todo",
"(",
"Object",
"...",
"what",
")",
"{",
"print_stderr_colored",
"(",
"BASH_BROWN",
",",
"\"",
"[TODO] ",
"\"",
",",
"\"",
" ",
"\"",
",",
"false",
",",
"what",
")",
";",
"}",
"protected",
"static",
"class",
"ThreadIndentation",
"extends",
"ThreadLocal",
"<",
"String",
">",
"{",
"private",
"static",
"AtomicInteger",
"ctr",
"=",
"new",
"AtomicInteger",
"(",
"0",
")",
";",
"@",
"Override",
"protected",
"String",
"initialValue",
"(",
")",
"{",
"String",
"result",
"=",
"\"",
"\"",
";",
"int",
"n_spaces",
"=",
"ctr",
".",
"getAndIncrement",
"(",
")",
";",
"for",
"(",
"int",
"a",
"=",
"0",
";",
"a",
"<",
"n_spaces",
";",
"a",
"++",
")",
"{",
"result",
"+=",
"\"",
" ",
"\"",
";",
"}",
"return",
"result",
";",
"}",
"public",
"static",
"void",
"print_colored",
"(",
"String",
"color",
",",
"String",
"prefix",
",",
"String",
"sep",
",",
"boolean",
"nice_arrays",
",",
"Object",
"...",
"text",
")",
"{",
"if",
"(",
"inAssertFalse",
")",
"{",
"return",
";",
"}",
"if",
"(",
"nice_arrays",
")",
"{",
"for",
"(",
"int",
"a",
"=",
"0",
";",
"a",
"<",
"text",
".",
"length",
";",
"a",
"++",
")",
"{",
"if",
"(",
"text",
"[",
"a",
"]",
"==",
"null",
")",
"{",
"text",
"[",
"a",
"]",
"=",
"\"",
"null",
"\"",
";",
"}",
"else",
"if",
"(",
"text",
"[",
"a",
"]",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
")",
"{",
"Object",
"[",
"]",
"arr",
"=",
"(",
"Object",
"[",
"]",
")",
"text",
"[",
"a",
"]",
";",
"text",
"[",
"a",
"]",
"=",
"(",
"new",
"ScRichString",
"(",
"\"",
"\\n",
"\"",
")",
")",
".",
"join",
"(",
"arr",
")",
";",
"}",
"}",
"}",
"if",
"(",
"no_bash_color",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"String",
".",
"format",
"(",
"\"",
" %s ",
"\"",
",",
"prefix",
")",
"+",
"(",
"new",
"ScRichString",
"(",
"sep",
")",
")",
".",
"join",
"(",
"text",
")",
")",
";",
"}",
"else",
"{",
"System",
".",
"err",
".",
"println",
"(",
"String",
".",
"format",
"(",
"\"",
" ",
"\\u001b",
"[%sm%s ",
"\"",
",",
"color",
",",
"prefix",
")",
"+",
"(",
"new",
"ScRichString",
"(",
"sep",
")",
")",
".",
"join",
"(",
"text",
")",
"+",
"\"",
"\\u001b",
"[0m",
"\"",
")",
";",
"}",
"}",
"}",
"protected",
"static",
"ThreadIndentation",
"thread_indentation",
"=",
"new",
"ThreadIndentation",
"(",
")",
";",
"public",
"static",
"void",
"print_exception",
"(",
"String",
"text",
",",
"Exception",
"e",
")",
"{",
"print_stderr_colored",
"(",
"BASH_RED",
",",
"\"",
"[EXCEPTION]",
"\"",
",",
"\"",
"\\n",
"\"",
",",
"false",
",",
"text",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"public",
"static",
"void",
"fail_exception",
"(",
"String",
"text",
",",
"Exception",
"e",
")",
"{",
"print_assert_false_colored",
"(",
"BASH_RED",
",",
"\"",
"[EXCEPTION]",
"\"",
",",
"\"",
"\\n",
"\"",
",",
"false",
",",
"text",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"public",
"static",
"void",
"debug_quit_exception",
"(",
"String",
"text",
",",
"Exception",
"e",
")",
"{",
"print_exception",
"(",
"text",
",",
"e",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}"
] | Debugging utilities, including an "assert" that doesn't require -ea. | [
"Debugging",
"utilities",
"including",
"an",
"\"",
"assert",
"\"",
"that",
"doesn",
"'",
"t",
"require",
"-",
"ea",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b99333230c0c0f914251bf5a5a22a170f64fc730 | dnefedchenko/osmd | src/main/java/com/freeman/configuration/security/OsmdAuthenticationSuccessHandler.java | [
"MIT"
] | Java | OsmdAuthenticationSuccessHandler | /**
* Created by Dmitriy Nefedchenko on 09.03.2018.
*/ | Created by Dmitriy Nefedchenko on 09.03.2018. | [
"Created",
"by",
"Dmitriy",
"Nefedchenko",
"on",
"09",
".",
"03",
".",
"2018",
"."
] | public class OsmdAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpStatus.OK.value());
}
} | [
"public",
"class",
"OsmdAuthenticationSuccessHandler",
"implements",
"AuthenticationSuccessHandler",
"{",
"@",
"Override",
"public",
"void",
"onAuthenticationSuccess",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"Authentication",
"authentication",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"response",
".",
"setStatus",
"(",
"HttpStatus",
".",
"OK",
".",
"value",
"(",
")",
")",
";",
"}",
"}"
] | Created by Dmitriy Nefedchenko on 09.03.2018. | [
"Created",
"by",
"Dmitriy",
"Nefedchenko",
"on",
"09",
".",
"03",
".",
"2018",
"."
] | [] | [
{
"param": "AuthenticationSuccessHandler",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AuthenticationSuccessHandler",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b99356eecb29546fa192d7ac97bd95eb40d95106 | marstona/ovh-java-sdk | ovh-java-sdk-ip/src/main/java/net/minidev/ovh/api/ip/OvhSpamIp.java | [
"BSD-3-Clause"
] | Java | OvhSpamIp | /**
* Your IP spam stats
*/ | Your IP spam stats | [
"Your",
"IP",
"spam",
"stats"
] | public class OvhSpamIp {
/**
* Last date the ip was blocked
*
* canBeNull && readOnly
*/
public Date date;
/**
* IP address which is sending spam
*
* canBeNull && readOnly
*/
public String ipSpamming;
/**
* Time (in seconds) while the IP will be blocked
*
* canBeNull && readOnly
*/
public Long time;
/**
* Current state of the ip
*
* canBeNull && readOnly
*/
public OvhSpamStateEnum state;
} | [
"public",
"class",
"OvhSpamIp",
"{",
"/**\n\t * Last date the ip was blocked\n\t *\n\t * canBeNull && readOnly\n\t */",
"public",
"Date",
"date",
";",
"/**\n\t * IP address which is sending spam\n\t *\n\t * canBeNull && readOnly\n\t */",
"public",
"String",
"ipSpamming",
";",
"/**\n\t * Time (in seconds) while the IP will be blocked\n\t *\n\t * canBeNull && readOnly\n\t */",
"public",
"Long",
"time",
";",
"/**\n\t * Current state of the ip\n\t *\n\t * canBeNull && readOnly\n\t */",
"public",
"OvhSpamStateEnum",
"state",
";",
"}"
] | Your IP spam stats | [
"Your",
"IP",
"spam",
"stats"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9957ae35d46ae95622085fff65f75f9190270bb | emnaayedi/Smart-School-Library | android application/app/src/main/java/com/slensky/focussis/data/AddressContact.java | [
"MIT"
] | Java | AddressContact | /**
* Created by slensky on 5/22/17.
*/ | Created by slensky on 5/22/17. | [
"Created",
"by",
"slensky",
"on",
"5",
"/",
"22",
"/",
"17",
"."
] | public class AddressContact {
private final String address;
private final String apartment;
private final String city;
private final String phone;
private final String email;
private final String name;
private final String relationship;
private final String state;
private final String zip;
private final boolean custody;
private final boolean emergency;
private final List<AddressContactDetail> details;
public AddressContact(String address, String apartment, String city, String phone, String email, String name, String relationship, String state, String zip, boolean custody, boolean emergency, List<AddressContactDetail> details) {
this.address = address;
this.apartment = apartment;
this.city = city;
this.phone = phone;
this.email = email;
this.name = name;
this.relationship = relationship;
this.state = state;
this.zip = zip;
this.custody = custody;
this.emergency = emergency;
this.details = details;
}
public boolean hasAddress() {
return address != null;
}
public String getAddress() {
return address;
}
public String getApartment() {
return apartment;
}
public String getCity() {
return city;
}
public boolean hasPhone() {
return phone != null;
}
public String getPhone() {
return phone;
}
public boolean hasEmail() {
return email != null;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public boolean hasRelationship() {
return relationship != null;
}
public String getRelationship() {
return relationship;
}
public String getState() {
return state;
}
public String getZip() {
return zip;
}
public boolean isCustody() {
return custody;
}
public boolean isEmergency() {
return emergency;
}
public boolean hasDetails() {
return details != null && details.size() > 0;
}
public List<AddressContactDetail> getDetails() {
return details;
}
} | [
"public",
"class",
"AddressContact",
"{",
"private",
"final",
"String",
"address",
";",
"private",
"final",
"String",
"apartment",
";",
"private",
"final",
"String",
"city",
";",
"private",
"final",
"String",
"phone",
";",
"private",
"final",
"String",
"email",
";",
"private",
"final",
"String",
"name",
";",
"private",
"final",
"String",
"relationship",
";",
"private",
"final",
"String",
"state",
";",
"private",
"final",
"String",
"zip",
";",
"private",
"final",
"boolean",
"custody",
";",
"private",
"final",
"boolean",
"emergency",
";",
"private",
"final",
"List",
"<",
"AddressContactDetail",
">",
"details",
";",
"public",
"AddressContact",
"(",
"String",
"address",
",",
"String",
"apartment",
",",
"String",
"city",
",",
"String",
"phone",
",",
"String",
"email",
",",
"String",
"name",
",",
"String",
"relationship",
",",
"String",
"state",
",",
"String",
"zip",
",",
"boolean",
"custody",
",",
"boolean",
"emergency",
",",
"List",
"<",
"AddressContactDetail",
">",
"details",
")",
"{",
"this",
".",
"address",
"=",
"address",
";",
"this",
".",
"apartment",
"=",
"apartment",
";",
"this",
".",
"city",
"=",
"city",
";",
"this",
".",
"phone",
"=",
"phone",
";",
"this",
".",
"email",
"=",
"email",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"relationship",
"=",
"relationship",
";",
"this",
".",
"state",
"=",
"state",
";",
"this",
".",
"zip",
"=",
"zip",
";",
"this",
".",
"custody",
"=",
"custody",
";",
"this",
".",
"emergency",
"=",
"emergency",
";",
"this",
".",
"details",
"=",
"details",
";",
"}",
"public",
"boolean",
"hasAddress",
"(",
")",
"{",
"return",
"address",
"!=",
"null",
";",
"}",
"public",
"String",
"getAddress",
"(",
")",
"{",
"return",
"address",
";",
"}",
"public",
"String",
"getApartment",
"(",
")",
"{",
"return",
"apartment",
";",
"}",
"public",
"String",
"getCity",
"(",
")",
"{",
"return",
"city",
";",
"}",
"public",
"boolean",
"hasPhone",
"(",
")",
"{",
"return",
"phone",
"!=",
"null",
";",
"}",
"public",
"String",
"getPhone",
"(",
")",
"{",
"return",
"phone",
";",
"}",
"public",
"boolean",
"hasEmail",
"(",
")",
"{",
"return",
"email",
"!=",
"null",
";",
"}",
"public",
"String",
"getEmail",
"(",
")",
"{",
"return",
"email",
";",
"}",
"public",
"String",
"getName",
"(",
")",
"{",
"return",
"name",
";",
"}",
"public",
"boolean",
"hasRelationship",
"(",
")",
"{",
"return",
"relationship",
"!=",
"null",
";",
"}",
"public",
"String",
"getRelationship",
"(",
")",
"{",
"return",
"relationship",
";",
"}",
"public",
"String",
"getState",
"(",
")",
"{",
"return",
"state",
";",
"}",
"public",
"String",
"getZip",
"(",
")",
"{",
"return",
"zip",
";",
"}",
"public",
"boolean",
"isCustody",
"(",
")",
"{",
"return",
"custody",
";",
"}",
"public",
"boolean",
"isEmergency",
"(",
")",
"{",
"return",
"emergency",
";",
"}",
"public",
"boolean",
"hasDetails",
"(",
")",
"{",
"return",
"details",
"!=",
"null",
"&&",
"details",
".",
"size",
"(",
")",
">",
"0",
";",
"}",
"public",
"List",
"<",
"AddressContactDetail",
">",
"getDetails",
"(",
")",
"{",
"return",
"details",
";",
"}",
"}"
] | Created by slensky on 5/22/17. | [
"Created",
"by",
"slensky",
"on",
"5",
"/",
"22",
"/",
"17",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b99780fe5b9b0bbe8f33edbadf31c130cd034875 | jenkinsci/starteam-plugin | src/main/java/hudson/plugins/starteam/StarTeamSCMException.java | [
"MIT"
] | Java | StarTeamSCMException | /**
* This exception signals an error with StarTeam SCM.
*
* @author Ilkka Laukkanen <[email protected]>
*
*/ | This exception signals an error with StarTeam SCM.
@author Ilkka Laukkanen | [
"This",
"exception",
"signals",
"an",
"error",
"with",
"StarTeam",
"SCM",
".",
"@author",
"Ilkka",
"Laukkanen"
] | public class StarTeamSCMException extends Exception {
/**
* serial version id
*/
private static final long serialVersionUID = 53829064700557888L;
/**
* @param message
* @param cause
*/
public StarTeamSCMException(String message, Throwable cause) {
super(message, cause);
}
/**
* @param message
*/
public StarTeamSCMException(String message) {
super(message);
}
} | [
"public",
"class",
"StarTeamSCMException",
"extends",
"Exception",
"{",
"/**\n\t * serial version id\n\t */",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"53829064700557888L",
";",
"/**\n\t * @param message\n\t * @param cause\n\t */",
"public",
"StarTeamSCMException",
"(",
"String",
"message",
",",
"Throwable",
"cause",
")",
"{",
"super",
"(",
"message",
",",
"cause",
")",
";",
"}",
"/**\n\t * @param message\n\t */",
"public",
"StarTeamSCMException",
"(",
"String",
"message",
")",
"{",
"super",
"(",
"message",
")",
";",
"}",
"}"
] | This exception signals an error with StarTeam SCM. | [
"This",
"exception",
"signals",
"an",
"error",
"with",
"StarTeam",
"SCM",
"."
] | [] | [
{
"param": "Exception",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Exception",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b99912e7d5aa7ba5a6726d0460925b87ecbd4ddf | JurrianFahner/spring-security-pac4j | src/main/java/org/pac4j/springframework/security/web/CallbackFilter.java | [
"Apache-2.0"
] | Java | CallbackFilter | /**
* <p>This filter finishes the login process for an indirect client, based on the {@link #callbackLogic}.</p>
*
* <p>The configuration can be provided via setter methods: {@link #setConfig(Config)} (security configuration), {@link #setDefaultUrl(String)} (default url after login if none was requested),
* {@link #setMultiProfile(Boolean)} (whether multiple profiles should be kept) and ({@link #setRenewSession(Boolean)} (whether the session must be renewed after login).</p>
*
* <p>This filter only applies if the suffix is blank or if the current request URL ends with the suffix (by default: <code>/callback</code>).</p>
*
* @author Jerome Leleu
* @since 2.0.0
*/ |
This filter only applies if the suffix is blank or if the current request URL ends with the suffix (by default: /callback).
@author Jerome Leleu
@since 2.0.0 | [
"This",
"filter",
"only",
"applies",
"if",
"the",
"suffix",
"is",
"blank",
"or",
"if",
"the",
"current",
"request",
"URL",
"ends",
"with",
"the",
"suffix",
"(",
"by",
"default",
":",
"/",
"callback",
")",
".",
"@author",
"Jerome",
"Leleu",
"@since",
"2",
".",
"0",
".",
"0"
] | public class CallbackFilter implements Filter {
public final static String DEFAULT_CALLBACK_SUFFIX = "/callback";
private final static Logger logger = LoggerFactory.getLogger(CallbackFilter.class);
private CallbackLogic<Object, J2EContext> callbackLogic;
private Config config;
private String defaultUrl;
private Boolean multiProfile;
private Boolean renewSession;
private String suffix = DEFAULT_CALLBACK_SUFFIX;
public CallbackFilter() {
callbackLogic = new DefaultCallbackLogic<>();
((DefaultCallbackLogic<Object, J2EContext>) callbackLogic).setProfileManagerFactory(SpringSecurityProfileManager::new);
}
public CallbackFilter(final Config config) {
this();
this.config = config;
}
public CallbackFilter(final Config config, final String defaultUrl) {
this(config);
this.defaultUrl = defaultUrl;
}
public CallbackFilter(final Config config, final String defaultUrl, final boolean multiProfile) {
this(config, defaultUrl);
this.multiProfile = multiProfile;
}
public CallbackFilter(final Config config, final String defaultUrl, final boolean multiProfile, final boolean renewSession) {
this(config, defaultUrl, multiProfile);
this.renewSession = renewSession;
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException { }
@Override
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException {
assertNotNull("config", this.config);
final J2EContext context = new J2EContext((HttpServletRequest) req, (HttpServletResponse) resp, config.getSessionStore());
final String path = context.getPath();
logger.debug("path: {} | suffix: {}", path, suffix);
final boolean pathEndsWithSuffix = path != null && path.endsWith(suffix);
if (isBlank(suffix) || pathEndsWithSuffix) {
assertNotNull("callbackLogic", this.callbackLogic);
callbackLogic.perform(context, this.config, J2ENopHttpActionAdapter.INSTANCE, this.defaultUrl, this.multiProfile, this.renewSession);
} else {
chain.doFilter(req, resp);
}
}
@Override
public void destroy() { }
public CallbackLogic<Object, J2EContext> getCallbackLogic() {
return callbackLogic;
}
public void setCallbackLogic(final CallbackLogic<Object, J2EContext> callbackLogic) {
this.callbackLogic = callbackLogic;
}
public Config getConfig() {
return config;
}
public void setConfig(final Config config) {
this.config = config;
}
public String getDefaultUrl() {
return defaultUrl;
}
public void setDefaultUrl(final String defaultUrl) {
this.defaultUrl = defaultUrl;
}
public Boolean getMultiProfile() {
return multiProfile;
}
public void setMultiProfile(final Boolean multiProfile) {
this.multiProfile = multiProfile;
}
public Boolean getRenewSession() {
return renewSession;
}
public void setRenewSession(final Boolean renewSession) {
this.renewSession = renewSession;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(final String suffix) {
this.suffix = suffix;
}
} | [
"public",
"class",
"CallbackFilter",
"implements",
"Filter",
"{",
"public",
"final",
"static",
"String",
"DEFAULT_CALLBACK_SUFFIX",
"=",
"\"",
"/callback",
"\"",
";",
"private",
"final",
"static",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"CallbackFilter",
".",
"class",
")",
";",
"private",
"CallbackLogic",
"<",
"Object",
",",
"J2EContext",
">",
"callbackLogic",
";",
"private",
"Config",
"config",
";",
"private",
"String",
"defaultUrl",
";",
"private",
"Boolean",
"multiProfile",
";",
"private",
"Boolean",
"renewSession",
";",
"private",
"String",
"suffix",
"=",
"DEFAULT_CALLBACK_SUFFIX",
";",
"public",
"CallbackFilter",
"(",
")",
"{",
"callbackLogic",
"=",
"new",
"DefaultCallbackLogic",
"<",
">",
"(",
")",
";",
"(",
"(",
"DefaultCallbackLogic",
"<",
"Object",
",",
"J2EContext",
">",
")",
"callbackLogic",
")",
".",
"setProfileManagerFactory",
"(",
"SpringSecurityProfileManager",
"::",
"new",
")",
";",
"}",
"public",
"CallbackFilter",
"(",
"final",
"Config",
"config",
")",
"{",
"this",
"(",
")",
";",
"this",
".",
"config",
"=",
"config",
";",
"}",
"public",
"CallbackFilter",
"(",
"final",
"Config",
"config",
",",
"final",
"String",
"defaultUrl",
")",
"{",
"this",
"(",
"config",
")",
";",
"this",
".",
"defaultUrl",
"=",
"defaultUrl",
";",
"}",
"public",
"CallbackFilter",
"(",
"final",
"Config",
"config",
",",
"final",
"String",
"defaultUrl",
",",
"final",
"boolean",
"multiProfile",
")",
"{",
"this",
"(",
"config",
",",
"defaultUrl",
")",
";",
"this",
".",
"multiProfile",
"=",
"multiProfile",
";",
"}",
"public",
"CallbackFilter",
"(",
"final",
"Config",
"config",
",",
"final",
"String",
"defaultUrl",
",",
"final",
"boolean",
"multiProfile",
",",
"final",
"boolean",
"renewSession",
")",
"{",
"this",
"(",
"config",
",",
"defaultUrl",
",",
"multiProfile",
")",
";",
"this",
".",
"renewSession",
"=",
"renewSession",
";",
"}",
"@",
"Override",
"public",
"void",
"init",
"(",
"final",
"FilterConfig",
"filterConfig",
")",
"throws",
"ServletException",
"{",
"}",
"@",
"Override",
"public",
"void",
"doFilter",
"(",
"final",
"ServletRequest",
"req",
",",
"final",
"ServletResponse",
"resp",
",",
"final",
"FilterChain",
"chain",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"assertNotNull",
"(",
"\"",
"config",
"\"",
",",
"this",
".",
"config",
")",
";",
"final",
"J2EContext",
"context",
"=",
"new",
"J2EContext",
"(",
"(",
"HttpServletRequest",
")",
"req",
",",
"(",
"HttpServletResponse",
")",
"resp",
",",
"config",
".",
"getSessionStore",
"(",
")",
")",
";",
"final",
"String",
"path",
"=",
"context",
".",
"getPath",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"",
"path: {} | suffix: {}",
"\"",
",",
"path",
",",
"suffix",
")",
";",
"final",
"boolean",
"pathEndsWithSuffix",
"=",
"path",
"!=",
"null",
"&&",
"path",
".",
"endsWith",
"(",
"suffix",
")",
";",
"if",
"(",
"isBlank",
"(",
"suffix",
")",
"||",
"pathEndsWithSuffix",
")",
"{",
"assertNotNull",
"(",
"\"",
"callbackLogic",
"\"",
",",
"this",
".",
"callbackLogic",
")",
";",
"callbackLogic",
".",
"perform",
"(",
"context",
",",
"this",
".",
"config",
",",
"J2ENopHttpActionAdapter",
".",
"INSTANCE",
",",
"this",
".",
"defaultUrl",
",",
"this",
".",
"multiProfile",
",",
"this",
".",
"renewSession",
")",
";",
"}",
"else",
"{",
"chain",
".",
"doFilter",
"(",
"req",
",",
"resp",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"destroy",
"(",
")",
"{",
"}",
"public",
"CallbackLogic",
"<",
"Object",
",",
"J2EContext",
">",
"getCallbackLogic",
"(",
")",
"{",
"return",
"callbackLogic",
";",
"}",
"public",
"void",
"setCallbackLogic",
"(",
"final",
"CallbackLogic",
"<",
"Object",
",",
"J2EContext",
">",
"callbackLogic",
")",
"{",
"this",
".",
"callbackLogic",
"=",
"callbackLogic",
";",
"}",
"public",
"Config",
"getConfig",
"(",
")",
"{",
"return",
"config",
";",
"}",
"public",
"void",
"setConfig",
"(",
"final",
"Config",
"config",
")",
"{",
"this",
".",
"config",
"=",
"config",
";",
"}",
"public",
"String",
"getDefaultUrl",
"(",
")",
"{",
"return",
"defaultUrl",
";",
"}",
"public",
"void",
"setDefaultUrl",
"(",
"final",
"String",
"defaultUrl",
")",
"{",
"this",
".",
"defaultUrl",
"=",
"defaultUrl",
";",
"}",
"public",
"Boolean",
"getMultiProfile",
"(",
")",
"{",
"return",
"multiProfile",
";",
"}",
"public",
"void",
"setMultiProfile",
"(",
"final",
"Boolean",
"multiProfile",
")",
"{",
"this",
".",
"multiProfile",
"=",
"multiProfile",
";",
"}",
"public",
"Boolean",
"getRenewSession",
"(",
")",
"{",
"return",
"renewSession",
";",
"}",
"public",
"void",
"setRenewSession",
"(",
"final",
"Boolean",
"renewSession",
")",
"{",
"this",
".",
"renewSession",
"=",
"renewSession",
";",
"}",
"public",
"String",
"getSuffix",
"(",
")",
"{",
"return",
"suffix",
";",
"}",
"public",
"void",
"setSuffix",
"(",
"final",
"String",
"suffix",
")",
"{",
"this",
".",
"suffix",
"=",
"suffix",
";",
"}",
"}"
] | <p>This filter finishes the login process for an indirect client, based on the {@link #callbackLogic}.</p>
<p>The configuration can be provided via setter methods: {@link #setConfig(Config)} (security configuration), {@link #setDefaultUrl(String)} (default url after login if none was requested),
{@link #setMultiProfile(Boolean)} (whether multiple profiles should be kept) and ({@link #setRenewSession(Boolean)} (whether the session must be renewed after login).</p> | [
"<p",
">",
"This",
"filter",
"finishes",
"the",
"login",
"process",
"for",
"an",
"indirect",
"client",
"based",
"on",
"the",
"{",
"@link",
"#callbackLogic",
"}",
".",
"<",
"/",
"p",
">",
"<p",
">",
"The",
"configuration",
"can",
"be",
"provided",
"via",
"setter",
"methods",
":",
"{",
"@link",
"#setConfig",
"(",
"Config",
")",
"}",
"(",
"security",
"configuration",
")",
"{",
"@link",
"#setDefaultUrl",
"(",
"String",
")",
"}",
"(",
"default",
"url",
"after",
"login",
"if",
"none",
"was",
"requested",
")",
"{",
"@link",
"#setMultiProfile",
"(",
"Boolean",
")",
"}",
"(",
"whether",
"multiple",
"profiles",
"should",
"be",
"kept",
")",
"and",
"(",
"{",
"@link",
"#setRenewSession",
"(",
"Boolean",
")",
"}",
"(",
"whether",
"the",
"session",
"must",
"be",
"renewed",
"after",
"login",
")",
".",
"<",
"/",
"p",
">"
] | [] | [
{
"param": "Filter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "Filter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b99e089c4cdc58761ad88c7bd2cb14e205e6b3fb | runjia1987/spring-framework | spring-core/src/main/java/org/springframework/core/annotation/DefaultOrderProviderComparator.java | [
"Apache-2.0"
] | Java | DefaultOrderProviderComparator | /**
* A default {@link OrderProviderComparator} implementation that uses the
* value provided by the {@link OrderProvider} and fallbacks to
* {@link AnnotationAwareOrderComparator} if none is set.
*
* <p>This essentially means that the value of the {@link OrderProvider}
* takes precedence over the behavior of {@link AnnotationAwareOrderComparator}
*
* @author Stephane Nicoll
* @since 4.1
*/ | A default OrderProviderComparator implementation that uses the
value provided by the OrderProvider and fallbacks to
AnnotationAwareOrderComparator if none is set.
This essentially means that the value of the OrderProvider
takes precedence over the behavior of AnnotationAwareOrderComparator
@author Stephane Nicoll
@since 4.1 | [
"A",
"default",
"OrderProviderComparator",
"implementation",
"that",
"uses",
"the",
"value",
"provided",
"by",
"the",
"OrderProvider",
"and",
"fallbacks",
"to",
"AnnotationAwareOrderComparator",
"if",
"none",
"is",
"set",
".",
"This",
"essentially",
"means",
"that",
"the",
"value",
"of",
"the",
"OrderProvider",
"takes",
"precedence",
"over",
"the",
"behavior",
"of",
"AnnotationAwareOrderComparator",
"@author",
"Stephane",
"Nicoll",
"@since",
"4",
".",
"1"
] | public class DefaultOrderProviderComparator implements OrderProviderComparator {
/**
* Shared default instance of DefaultOrderProviderComparator.
*/
public static final DefaultOrderProviderComparator INSTANCE = new DefaultOrderProviderComparator();
@Override
public void sortList(List<?> items, OrderProvider orderProvider) {
Collections.sort(items, new OrderProviderAwareComparator(orderProvider));
}
@Override
public void sortArray(Object[] items, OrderProvider orderProvider) {
Arrays.sort(items, new OrderProviderAwareComparator(orderProvider));
}
private static class OrderProviderAwareComparator extends AnnotationAwareOrderComparator {
private final OrderProvider orderProvider;
public OrderProviderAwareComparator(OrderProvider orderProvider) {
this.orderProvider = orderProvider;
}
@Override
protected int getOrder(Object obj) {
Integer order = this.orderProvider.getOrder(obj);
if (order != null) {
return order;
}
return super.getOrder(obj);
}
}
} | [
"public",
"class",
"DefaultOrderProviderComparator",
"implements",
"OrderProviderComparator",
"{",
"/**\n\t * Shared default instance of DefaultOrderProviderComparator.\n\t */",
"public",
"static",
"final",
"DefaultOrderProviderComparator",
"INSTANCE",
"=",
"new",
"DefaultOrderProviderComparator",
"(",
")",
";",
"@",
"Override",
"public",
"void",
"sortList",
"(",
"List",
"<",
"?",
">",
"items",
",",
"OrderProvider",
"orderProvider",
")",
"{",
"Collections",
".",
"sort",
"(",
"items",
",",
"new",
"OrderProviderAwareComparator",
"(",
"orderProvider",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"sortArray",
"(",
"Object",
"[",
"]",
"items",
",",
"OrderProvider",
"orderProvider",
")",
"{",
"Arrays",
".",
"sort",
"(",
"items",
",",
"new",
"OrderProviderAwareComparator",
"(",
"orderProvider",
")",
")",
";",
"}",
"private",
"static",
"class",
"OrderProviderAwareComparator",
"extends",
"AnnotationAwareOrderComparator",
"{",
"private",
"final",
"OrderProvider",
"orderProvider",
";",
"public",
"OrderProviderAwareComparator",
"(",
"OrderProvider",
"orderProvider",
")",
"{",
"this",
".",
"orderProvider",
"=",
"orderProvider",
";",
"}",
"@",
"Override",
"protected",
"int",
"getOrder",
"(",
"Object",
"obj",
")",
"{",
"Integer",
"order",
"=",
"this",
".",
"orderProvider",
".",
"getOrder",
"(",
"obj",
")",
";",
"if",
"(",
"order",
"!=",
"null",
")",
"{",
"return",
"order",
";",
"}",
"return",
"super",
".",
"getOrder",
"(",
"obj",
")",
";",
"}",
"}",
"}"
] | A default {@link OrderProviderComparator} implementation that uses the
value provided by the {@link OrderProvider} and fallbacks to
{@link AnnotationAwareOrderComparator} if none is set. | [
"A",
"default",
"{",
"@link",
"OrderProviderComparator",
"}",
"implementation",
"that",
"uses",
"the",
"value",
"provided",
"by",
"the",
"{",
"@link",
"OrderProvider",
"}",
"and",
"fallbacks",
"to",
"{",
"@link",
"AnnotationAwareOrderComparator",
"}",
"if",
"none",
"is",
"set",
"."
] | [] | [
{
"param": "OrderProviderComparator",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "OrderProviderComparator",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b99f790b35bd8442d4586d882045f92f3aec4dc5 | clarksue/mobile-sdk-android | mediation/mediatedviews/Amazon/src/com/appnexus/opensdk/mediatedviews/AmazonInterstitial.java | [
"Apache-2.0"
] | Java | AmazonInterstitial | /**
* This class is the Amazon interstitial adaptor it provides the functionality needed to allow
* an application using the App Nexus SDK to load an interstitial ad through the Amazon SDK. The
* instantiation of this class is done in response from the AppNexus server for an interstitial
* placement that is configured to use Amazon to serve it. This class is never directly instantiated
* by the developer.
*/ | This class is the Amazon interstitial adaptor it provides the functionality needed to allow
an application using the App Nexus SDK to load an interstitial ad through the Amazon SDK. The
instantiation of this class is done in response from the AppNexus server for an interstitial
placement that is configured to use Amazon to serve it. This class is never directly instantiated
by the developer. | [
"This",
"class",
"is",
"the",
"Amazon",
"interstitial",
"adaptor",
"it",
"provides",
"the",
"functionality",
"needed",
"to",
"allow",
"an",
"application",
"using",
"the",
"App",
"Nexus",
"SDK",
"to",
"load",
"an",
"interstitial",
"ad",
"through",
"the",
"Amazon",
"SDK",
".",
"The",
"instantiation",
"of",
"this",
"class",
"is",
"done",
"in",
"response",
"from",
"the",
"AppNexus",
"server",
"for",
"an",
"interstitial",
"placement",
"that",
"is",
"configured",
"to",
"use",
"Amazon",
"to",
"serve",
"it",
".",
"This",
"class",
"is",
"never",
"directly",
"instantiated",
"by",
"the",
"developer",
"."
] | public class AmazonInterstitial implements MediatedInterstitialAdView {
InterstitialAd iad;
AmazonListener amazonListener;
/**
* Called by the AN SDK to request an Interstitial ad from the Amazon SDK. .
*
* @param mBC the object which will be called with events from the Amazon SDK
* @param activity the activity from which this is launched
* @param parameter String parameter received from the server for instantiation of this object
* optional server side parameters to control this call.
* @param uid The 3rd party placement , in adMob this is the adUnitID
* @param width Width of the ad
* @param height Height of the ad
*/
@Override
public void requestAd(MediatedInterstitialAdViewController mIC, Activity activity, String parameter, String uid, TargetingParameters tp) {
this.iad = new InterstitialAd(activity);
this.amazonListener = new AmazonListener(mIC,AmazonBanner.class.getSimpleName());
this.iad.setListener(this.amazonListener);
AdTargetingOptions targetingOptions = AmazonTargeting.createTargeting(this.iad, tp, parameter);
if (!this.iad.loadAd(targetingOptions)) {
if (mIC != null) {
mIC.onAdFailed(ResultCode.UNABLE_TO_FILL);
}
this.iad = null;
}
}
/**
* This is called in response to the application calling InterstitialAdView.show();
*/
@Override
public void show() {
if (this.iad != null && !this.iad.isShowing()) {
if ( this.iad.showAd()) {
this.amazonListener.printToClog("show() called ad is now showing");
} else {
this.amazonListener.printToClogError("show() called showAd returned failure");
}
} else {
if (this.iad == null) {
this.amazonListener.printToClogError("show() called on a failed Interstitial");
} else if (!this.iad.isShowing()) {
this.amazonListener.printToClogError("show() called on a failed Interstitial");
} else {
this.amazonListener.printToClogError("show() failed");
}
}
}
@Override
public boolean isReady() {
boolean ready = iad != null && !iad.isLoading();
this.amazonListener.printToClog("isReady() returned " + ready);
return ready;
}
@Override
public void destroy() {
try{
iad.setListener(null);
}catch(NullPointerException npe){
//Catch NPE until amazon updates SDK to handle nullness
}
iad=null;
amazonListener=null;
}
@Override
public void onPause() {
//No public api
}
@Override
public void onResume() {
//No public api
}
@Override
public void onDestroy() {
destroy();
}
} | [
"public",
"class",
"AmazonInterstitial",
"implements",
"MediatedInterstitialAdView",
"{",
"InterstitialAd",
"iad",
";",
"AmazonListener",
"amazonListener",
";",
"/**\n * Called by the AN SDK to request an Interstitial ad from the Amazon SDK. .\n *\n * @param mBC the object which will be called with events from the Amazon SDK\n * @param activity the activity from which this is launched\n * @param parameter String parameter received from the server for instantiation of this object\n * optional server side parameters to control this call.\n * @param uid The 3rd party placement , in adMob this is the adUnitID\n * @param width Width of the ad\n * @param height Height of the ad\n */",
"@",
"Override",
"public",
"void",
"requestAd",
"(",
"MediatedInterstitialAdViewController",
"mIC",
",",
"Activity",
"activity",
",",
"String",
"parameter",
",",
"String",
"uid",
",",
"TargetingParameters",
"tp",
")",
"{",
"this",
".",
"iad",
"=",
"new",
"InterstitialAd",
"(",
"activity",
")",
";",
"this",
".",
"amazonListener",
"=",
"new",
"AmazonListener",
"(",
"mIC",
",",
"AmazonBanner",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
";",
"this",
".",
"iad",
".",
"setListener",
"(",
"this",
".",
"amazonListener",
")",
";",
"AdTargetingOptions",
"targetingOptions",
"=",
"AmazonTargeting",
".",
"createTargeting",
"(",
"this",
".",
"iad",
",",
"tp",
",",
"parameter",
")",
";",
"if",
"(",
"!",
"this",
".",
"iad",
".",
"loadAd",
"(",
"targetingOptions",
")",
")",
"{",
"if",
"(",
"mIC",
"!=",
"null",
")",
"{",
"mIC",
".",
"onAdFailed",
"(",
"ResultCode",
".",
"UNABLE_TO_FILL",
")",
";",
"}",
"this",
".",
"iad",
"=",
"null",
";",
"}",
"}",
"/**\n * This is called in response to the application calling InterstitialAdView.show();\n */",
"@",
"Override",
"public",
"void",
"show",
"(",
")",
"{",
"if",
"(",
"this",
".",
"iad",
"!=",
"null",
"&&",
"!",
"this",
".",
"iad",
".",
"isShowing",
"(",
")",
")",
"{",
"if",
"(",
"this",
".",
"iad",
".",
"showAd",
"(",
")",
")",
"{",
"this",
".",
"amazonListener",
".",
"printToClog",
"(",
"\"",
"show() called ad is now showing",
"\"",
")",
";",
"}",
"else",
"{",
"this",
".",
"amazonListener",
".",
"printToClogError",
"(",
"\"",
"show() called showAd returned failure",
"\"",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"iad",
"==",
"null",
")",
"{",
"this",
".",
"amazonListener",
".",
"printToClogError",
"(",
"\"",
"show() called on a failed Interstitial",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"!",
"this",
".",
"iad",
".",
"isShowing",
"(",
")",
")",
"{",
"this",
".",
"amazonListener",
".",
"printToClogError",
"(",
"\"",
"show() called on a failed Interstitial",
"\"",
")",
";",
"}",
"else",
"{",
"this",
".",
"amazonListener",
".",
"printToClogError",
"(",
"\"",
"show() failed",
"\"",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"boolean",
"isReady",
"(",
")",
"{",
"boolean",
"ready",
"=",
"iad",
"!=",
"null",
"&&",
"!",
"iad",
".",
"isLoading",
"(",
")",
";",
"this",
".",
"amazonListener",
".",
"printToClog",
"(",
"\"",
"isReady() returned ",
"\"",
"+",
"ready",
")",
";",
"return",
"ready",
";",
"}",
"@",
"Override",
"public",
"void",
"destroy",
"(",
")",
"{",
"try",
"{",
"iad",
".",
"setListener",
"(",
"null",
")",
";",
"}",
"catch",
"(",
"NullPointerException",
"npe",
")",
"{",
"}",
"iad",
"=",
"null",
";",
"amazonListener",
"=",
"null",
";",
"}",
"@",
"Override",
"public",
"void",
"onPause",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onResume",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"void",
"onDestroy",
"(",
")",
"{",
"destroy",
"(",
")",
";",
"}",
"}"
] | This class is the Amazon interstitial adaptor it provides the functionality needed to allow
an application using the App Nexus SDK to load an interstitial ad through the Amazon SDK. | [
"This",
"class",
"is",
"the",
"Amazon",
"interstitial",
"adaptor",
"it",
"provides",
"the",
"functionality",
"needed",
"to",
"allow",
"an",
"application",
"using",
"the",
"App",
"Nexus",
"SDK",
"to",
"load",
"an",
"interstitial",
"ad",
"through",
"the",
"Amazon",
"SDK",
"."
] | [
"//Catch NPE until amazon updates SDK to handle nullness",
"//No public api",
"//No public api"
] | [
{
"param": "MediatedInterstitialAdView",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "MediatedInterstitialAdView",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9a05d21fd905af975a0e7464e44f38402d86025 | intasect/cordysjmscon | src/java/com/cordys/coe/ac/jmsconnector/JMSUtil.java | [
"Apache-2.0"
] | Java | JMSUtil | /**
* DOCUMENTME
* .
*
* @author awisse
*/ | DOCUMENTME
.
@author awisse | [
"DOCUMENTME",
".",
"@author",
"awisse"
] | public class JMSUtil
{
/**
* Appends extra parameters to a dynamic destination URL. The format of this URL is provider
* specific and probably not supported by all providers. Currently this method is hard-coded for
* WebSphere MQ.
*
* @param sPhysicalName Physical URL of the destination.
* @param dDest Dynamic JMSConnector destination.
* @param sParamString Extra parameters as configured in the connector configuration page.
*
* @return
*/
public static String appendDynamicDestinationParameters(String sPhysicalName, Destination dDest,
String sParamString)
{
if ((sParamString == null) || (sParamString.length() == 0))
{
return sPhysicalName;
}
// Parse them in to a hash map, so later we can do parameter merging.
Map<String, String> mParams = new HashMap<String, String>();
String[] saTmpArray = sParamString.split(",");
for (String sTmp : saTmpArray)
{
int iPos = sTmp.indexOf('=');
String sName;
String sValue;
if (iPos > 0)
{
sName = sTmp.substring(0, iPos).trim();
sValue = ((iPos < (sTmp.length() - 1)) ? sTmp.substring(iPos + 1).trim() : "");
}
else
{
sName = sTmp;
sValue = null;
}
mParams.put(sName, sValue);
}
// Discard the possible query part from the physical name.
int iPos = sPhysicalName.indexOf('?');
if (iPos >= 0)
{
sPhysicalName = sPhysicalName.substring(0, iPos);
}
StringBuilder sbRes = new StringBuilder(100);
boolean bFirst = true;
sbRes.append(sPhysicalName);
for (Map.Entry<String, String> eEntry : mParams.entrySet())
{
if (bFirst)
{
sbRes.append('?');
bFirst = false;
}
else
{
sbRes.append('&');
}
String sName = eEntry.getKey();
String sValue = eEntry.getValue();
sbRes.append(sName);
if (sValue != null)
{
sbRes.append('=');
sbRes.append(sValue);
}
}
return sbRes.toString();
}
/**
* DOCUMENTME.
*
* @param str DOCUMENTME
*
* @return DOCUMENTME
*/
public static byte[] base64decode(String str)
{
return Base64.decode(str.toCharArray());
}
/**
* DOCUMENTME.
*
* @param data DOCUMENTME
*
* @return DOCUMENTME
*/
public static String base64encode(byte[] data)
{
return new String(Base64.encode(data));
}
/**
* Finds the cause of an exception.
*
* @param t the exception to look for the cause
*
* @return the cause
*/
public static String findCause(Throwable t)
{
String msg = t.getMessage();
if (((msg == null) || "".equals(msg)) && (t.getCause() != null))
{
msg = findCause(t.getCause());
}
return msg;
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param requestIsAttribute DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static Boolean getBooleanParameter(int request, int implementation, String nodeName,
boolean requestIsAttribute, Boolean defaultValue)
{
String value = getParameter(request, implementation, nodeName, requestIsAttribute, nodeName,
null);
if ((value == null) || (value.length() == 0))
{
return defaultValue;
}
if ("true".equals(value))
{
return true;
}
else if ("false".equals(value))
{
return false;
}
else
{
throw new IllegalArgumentException("Invalid value '" + value + "' for parameter: " +
nodeName);
}
}
/**
* Returns the identifier as used in this connector.
*
* @param uri The uri to look for
*
* @return
*/
public static String getDestinationIdentifier(String uri)
{
Destination dest = Destination.getDestination(uri);
if (dest == null)
{
return null;
}
return dest.getDestinationManager().getName() + "." + dest.getName();
}
/**
* Returns the internal (JMS) queue/topic identifier for a given destination, without any
* parameters.
*
* @param destination
*
* @return
*
* @throws JMSException
*/
public static String getDestinationURI(javax.jms.Destination destination)
throws JMSException
{
String destURI = "";
if (destination instanceof Queue)
{
destURI = ((Queue) destination).getQueueName();
}
else if (destination instanceof Topic)
{
destURI = ((Topic) destination).getTopicName();
}
if (destURI.indexOf("?") > -1) // remove all possible parameters...
{
destURI = destURI.substring(0, destURI.indexOf("?"));
}
return destURI;
}
/**
* Returns the JMSConnector name as well as the provider specific destination URL for the given
* JMS destination. The JMSConnector destination is a destination that is related to the given
* JMS destination (e.g. the receiving destination).
*
* @param dOrigConnectorDest Related JMSConnector destination.
* @param dDest JMS destination.
* @param bAddParameters If <code>true</code> dynamic destinations parameters are added
* to the physical name (provider URL).
*
* @return String array where [0] = JMSConnector name, [1] = JMS provider URL (null if the
* destination is known).
*
* @throws JMSException
*/
public static String[] getJmsDestinationNames(Destination dOrigConnectorDest,
javax.jms.Destination dDest,
boolean bAddParameters)
throws JMSException
{
String sProviderUrl = getDestinationURI(dDest);
String sConnectorName = getDestinationIdentifier(sProviderUrl);
if (sConnectorName != null)
{
return new String[] { sConnectorName, null };
}
// Unknown static destination. Just set it as a dynamic one.
Destination dUseDest = null;
if ((sProviderUrl != null) && (sProviderUrl.length() > 0))
{
// Destination physical name is known, so try to find a dynamic destination.
dUseDest = dOrigConnectorDest.getDestinationManager().getDynamicDestination();
}
if (dUseDest == null)
{
// No dynamic destination configured or the physical name was not known, so just
// use the default one. For triggers this is the destination to which the trigger is
// attached to.
dUseDest = dOrigConnectorDest;
}
sConnectorName = dUseDest.getDestinationManager().getName() + "." + dUseDest.getName();
if ((sProviderUrl != null) && (sProviderUrl.length() > 0) && bAddParameters)
{
sProviderUrl = appendDynamicDestinationParameters(sProviderUrl, dUseDest,
dUseDest
.getDynamicDestinationParameterString());
}
return new String[]
{
(sConnectorName != null) ? sConnectorName : "",
(sProviderUrl != null) ? sProviderUrl : ""
};
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param requestIsAttribute DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static Long getLongParameter(int request, int implementation, String nodeName,
boolean requestIsAttribute, Long defaultValue)
{
String value = getParameter(request, implementation, nodeName, requestIsAttribute, nodeName,
null);
if ((value == null) || (value.length() == 0))
{
return defaultValue;
}
try
{
return Long.parseLong(value);
}
catch (RuntimeException e)
{
throw new IllegalArgumentException("Invalid value '" + value + "' for parameter: " +
nodeName);
}
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static String getParameter(int request, int implementation, String nodeName,
String defaultValue)
{
return getParameter(request, implementation, nodeName, false, nodeName, defaultValue);
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param requestName DOCUMENTME
* @param implementationName DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static String getParameter(int request, int implementation, String requestName,
String implementationName, String defaultValue)
{
return getParameter(request, implementation, requestName, false, implementationName,
defaultValue);
}
/**
* DOCUMENTME.
*
* @param request DOCUMENTME
* @param implementation DOCUMENTME
* @param nodeName DOCUMENTME
* @param requestIsAttribute DOCUMENTME
* @param defaultValue DOCUMENTME
*
* @return DOCUMENTME
*/
public static String getParameter(int request, int implementation, String nodeName,
boolean requestIsAttribute, String defaultValue)
{
return getParameter(request, implementation, nodeName, requestIsAttribute, nodeName,
defaultValue);
}
/**
* Returns a parameter value from the implementation or the request itself, based on the
* implementation settings.
*
* @param request The request xml
* @param implementation The implementation xml
* @param requestName The parameter name in the request
* @param requestIsAttribute true if the parameter is specified in an attribute in the
* request
* @param implementationName The parameter name in the implementation
* @param defaultValue A default value
*
* @return the value from the request if the implementation states that it was overridable,
* else the value from the implementation and if that one is not found either, the
* default value
*/
public static String getParameter(int request, int implementation, String requestName,
boolean requestIsAttribute, String implementationName,
String defaultValue)
{
int impNode = Node.getElement(implementation, implementationName);
if ((impNode == 0) || "true".equals(Node.getAttribute(impNode, "overridable")))
{
String sRes;
if (requestIsAttribute)
{
sRes = Node.getAttribute(request, requestName, null);
}
else
{
sRes = Node.getDataElement(request, requestName, null);
}
if (sRes != null)
{
return sRes;
}
}
return Node.getDataWithDefault(impNode, defaultValue);
}
/**
* Returns a better stacktrace especially for JMSExceptions (contain a linked exception with
* more exception details).
*
* @param t the exception to get it from
*
* @return a string containing the stacktrace
*/
public static String getStackTrace(Throwable t)
{
if (t == null)
{
return "";
}
StringBuffer sb = new StringBuffer();
sb.append(t.getClass().getName());
sb.append(": ");
if (t.getMessage() != null)
{
sb.append(t.getMessage());
}
sb.append("\n");
if (t instanceof JMSException)
{
sb.append("Caused by: ");
sb.append(getStackTrace(((JMSException) t).getLinkedException()));
}
else if (t.getCause() != null)
{
sb.append("Caused by: ");
sb.append(getStackTrace(t.getCause()));
}
else
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
sb.append(sw.getBuffer());
}
return sb.toString();
}
/**
* Get the properties from the given xml.
*
* @param xml the xml to read the properties from
* @param nodeName the node name containing the property list
* @param properties the object to put the properties into
* @param canChange true if existing properties can be changed
*
* @throws JMSConnectorException
*/
public static void processProperties(int xml, String nodeName,
Hashtable<String, Object> properties, boolean canChange)
throws JMSConnectorException
{
int propNode = Node.getElement(xml, nodeName);
if (propNode != 0)
{
for (int cnode = Node.getFirstChild(propNode); cnode != 0;
cnode = Node.getNextSibling(cnode))
{
String key = Node.getAttribute(cnode, "name");
if (!canChange && properties.containsKey(key))
{
continue;
}
if ((key == null) || (key.length() == 0))
{
continue;
}
String type = Node.getAttribute(cnode, "type", null);
if ((type == null) || (type.length() == 0))
{
throw new JMSConnectorException("No type found for property '" + key + "'");
}
String value = Node.getData(cnode);
Object objValue;
if (type.equals("String"))
{
objValue = value;
}
else if (type.equals("Short"))
{
objValue = Short.valueOf(value);
}
else if (type.equals("Byte"))
{
objValue = Byte.valueOf(value);
}
else if (type.equals("Boolean"))
{
objValue = Boolean.valueOf(value);
}
else if (type.equals("Double"))
{
objValue = Double.valueOf(value);
}
else if (type.equals("Float"))
{
objValue = Float.valueOf(value);
}
else if (type.equals("Integer"))
{
objValue = Integer.valueOf(value);
}
else if (type.equals("Long"))
{
objValue = Long.valueOf(value);
}
else
{
throw new JMSConnectorException("Unknown type '" + type + "' for property '" +
key + "'");
}
properties.put(key, objValue);
}
}
}
/**
* Formats a a string so that it can be put into the log safely. Some characters seem to cause
* problem.
*
* @param oMessage Object to be formatted. Uses toString().
*
* @return Formattes string.
*/
public static String safeFormatLogMessage(Object oMessage)
{
return safeFormatLogMessage(oMessage.toString());
}
/**
* Formats a a string so that it can be put into the log safely. Some characters seem to cause
* problem.
*
* @param sMessage Log message to be formatted.
*
* @return Formattes string.
*/
public static String safeFormatLogMessage(String sMessage)
{
StringBuilder sbRes = new StringBuilder(sMessage.length() + 20);
int iLen = sMessage.length();
for (int i = 0; i < iLen; i++)
{
char ch = sMessage.charAt(i);
if ((ch < 9) || (ch == 11) || (ch == 12) || (ch > 127))
{
sbRes.append("[");
sbRes.append((int) ch);
sbRes.append("]");
}
else if ((ch == ']') && (i < (iLen - 2)) && (sMessage.charAt(i + 1) == ']') &&
(sMessage.charAt(i + 2) == '>'))
{
// Escape CDATA end marker.
sbRes.append("]] >");
i += 2;
}
else
{
sbRes.append(ch);
}
}
return sbRes.toString();
}
/**
* Creates a copy of the message, used to put a message into the error queue.
*
* @param inputMsg the message to copy
* @param session the session to use for the new message
*
* @return the copied message
*
* @throws JMSException
* @throws JMSConnectorException
*/
protected static Message getCopyOfMessageForSession(Message inputMsg, Session session)
throws JMSException, JMSConnectorException
{
Message outputMsg;
if (inputMsg instanceof BytesMessage)
{
outputMsg = session.createBytesMessage();
int len = (int) ((BytesMessage) inputMsg).getBodyLength();
byte[] msg = new byte[len];
((BytesMessage) inputMsg).readBytes(msg);
((BytesMessage) outputMsg).writeBytes(msg);
}
else if (inputMsg instanceof TextMessage)
{
outputMsg = session.createTextMessage();
((TextMessage) outputMsg).setText(((TextMessage) inputMsg).getText());
}
else if (inputMsg instanceof MapMessage)
{
outputMsg = session.createMapMessage();
Enumeration<?> mapNames = ((MapMessage) inputMsg).getMapNames();
while (mapNames.hasMoreElements())
{
String key = (String) mapNames.nextElement();
((MapMessage) outputMsg).setObject(key, ((MapMessage) inputMsg).getObject(key));
}
}
else if (inputMsg instanceof ObjectMessage)
{
outputMsg = session.createObjectMessage();
((ObjectMessage) outputMsg).setObject(((ObjectMessage) inputMsg).getObject());
}
else // StreamMessage is not implemented!!!
{
throw new JMSConnectorException("Unsupported message format: " +
inputMsg.getClass().getName());
}
if (inputMsg.getJMSMessageID() != null)
{
outputMsg.setJMSMessageID(inputMsg.getJMSMessageID());
}
if (inputMsg.getJMSCorrelationID() != null)
{
outputMsg.setJMSCorrelationID(inputMsg.getJMSCorrelationID());
}
if (inputMsg.getJMSReplyTo() != null)
{
outputMsg.setJMSReplyTo(inputMsg.getJMSReplyTo());
}
if (inputMsg.getJMSType() != null)
{
outputMsg.setJMSType(inputMsg.getJMSType());
}
outputMsg.setJMSDeliveryMode(inputMsg.getJMSDeliveryMode());
outputMsg.setJMSExpiration(inputMsg.getJMSExpiration());
outputMsg.setJMSPriority(inputMsg.getJMSPriority());
outputMsg.setJMSRedelivered(inputMsg.getJMSRedelivered());
outputMsg.setJMSTimestamp(inputMsg.getJMSTimestamp());
Enumeration<?> properties = inputMsg.getPropertyNames();
while (properties.hasMoreElements())
{
String key = (String) properties.nextElement();
if (key.startsWith("JMSX"))
{
continue;
}
outputMsg.setObjectProperty(key, inputMsg.getObjectProperty(key));
}
return outputMsg;
}
/**
* Convert a message to XML.
*
* @param dDest Destination the this message comes from.
* @param msg The message
* @param resultNode the xml node containing the xml representation
*
* @throws JMSException
*/
protected static void getInformationFromMessage(Destination dDest, Message msg, int resultNode)
throws JMSException
{
Node.createTextElement("messageid", msg.getJMSMessageID(), resultNode);
if (msg.getJMSCorrelationID() != null)
{
Node.createTextElement("correlationid", msg.getJMSCorrelationID(), resultNode);
}
if (msg.getJMSType() != null)
{
Node.createTextElement("jmstype", msg.getJMSType(), resultNode);
}
if (msg.getJMSReplyTo() != null)
{
String[] saNames = getJmsDestinationNames(dDest, msg.getJMSReplyTo(), true);
int xTmpNode;
xTmpNode = Node.createTextElement("reply2destination", saNames[0], resultNode);
if (saNames[1] != null)
{
// Unknown as a static destination. Just set it as a dynamic one.
Node.setAttribute(xTmpNode, Destination.DESTINATION_PHYSICALNAME_ATTRIB,
saNames[1]);
}
}
// Set the from destination too.
{
String[] saNames = getJmsDestinationNames(dDest, msg.getJMSDestination(), true);
int xTmpNode;
xTmpNode = Node.createTextElement("fromdestination", saNames[0], resultNode);
if (saNames[1] != null)
{
// Unknown as a static destination. Just set it as a dynamic one.
Node.setAttribute(xTmpNode, Destination.DESTINATION_PHYSICALNAME_ATTRIB,
saNames[1]);
}
}
Enumeration<?> properties = msg.getPropertyNames();
if (properties.hasMoreElements())
{
int propNode = Node.createElement("properties", resultNode);
while (properties.hasMoreElements())
{
String key = (String) properties.nextElement();
Object value = msg.getObjectProperty(key);
int cnode = Node.createTextElement("property", String.valueOf(value), propNode);
Node.setAttribute(cnode, "name", key);
if (value instanceof String)
{
Node.setAttribute(cnode, "type", "String");
}
else if (value instanceof Short)
{
Node.setAttribute(cnode, "type", "Short");
}
else if (value instanceof Byte)
{
Node.setAttribute(cnode, "type", "Byte");
}
else if (value instanceof Boolean)
{
Node.setAttribute(cnode, "type", "Boolean");
}
else if (value instanceof Double)
{
Node.setAttribute(cnode, "type", "Double");
}
else if (value instanceof Float)
{
Node.setAttribute(cnode, "type", "Float");
}
else if (value instanceof Integer)
{
Node.setAttribute(cnode, "type", "Integer");
}
else if (value instanceof Long)
{
Node.setAttribute(cnode, "type", "Long");
}
else
{
Node.setAttribute(cnode, "type", "Object");
}
}
}
}
} | [
"public",
"class",
"JMSUtil",
"{",
"/**\n * Appends extra parameters to a dynamic destination URL. The format of this URL is provider\n * specific and probably not supported by all providers. Currently this method is hard-coded for\n * WebSphere MQ.\n *\n * @param sPhysicalName Physical URL of the destination.\n * @param dDest Dynamic JMSConnector destination.\n * @param sParamString Extra parameters as configured in the connector configuration page.\n *\n * @return\n */",
"public",
"static",
"String",
"appendDynamicDestinationParameters",
"(",
"String",
"sPhysicalName",
",",
"Destination",
"dDest",
",",
"String",
"sParamString",
")",
"{",
"if",
"(",
"(",
"sParamString",
"==",
"null",
")",
"||",
"(",
"sParamString",
".",
"length",
"(",
")",
"==",
"0",
")",
")",
"{",
"return",
"sPhysicalName",
";",
"}",
"Map",
"<",
"String",
",",
"String",
">",
"mParams",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"String",
"[",
"]",
"saTmpArray",
"=",
"sParamString",
".",
"split",
"(",
"\"",
",",
"\"",
")",
";",
"for",
"(",
"String",
"sTmp",
":",
"saTmpArray",
")",
"{",
"int",
"iPos",
"=",
"sTmp",
".",
"indexOf",
"(",
"'='",
")",
";",
"String",
"sName",
";",
"String",
"sValue",
";",
"if",
"(",
"iPos",
">",
"0",
")",
"{",
"sName",
"=",
"sTmp",
".",
"substring",
"(",
"0",
",",
"iPos",
")",
".",
"trim",
"(",
")",
";",
"sValue",
"=",
"(",
"(",
"iPos",
"<",
"(",
"sTmp",
".",
"length",
"(",
")",
"-",
"1",
")",
")",
"?",
"sTmp",
".",
"substring",
"(",
"iPos",
"+",
"1",
")",
".",
"trim",
"(",
")",
":",
"\"",
"\"",
")",
";",
"}",
"else",
"{",
"sName",
"=",
"sTmp",
";",
"sValue",
"=",
"null",
";",
"}",
"mParams",
".",
"put",
"(",
"sName",
",",
"sValue",
")",
";",
"}",
"int",
"iPos",
"=",
"sPhysicalName",
".",
"indexOf",
"(",
"'?'",
")",
";",
"if",
"(",
"iPos",
">=",
"0",
")",
"{",
"sPhysicalName",
"=",
"sPhysicalName",
".",
"substring",
"(",
"0",
",",
"iPos",
")",
";",
"}",
"StringBuilder",
"sbRes",
"=",
"new",
"StringBuilder",
"(",
"100",
")",
";",
"boolean",
"bFirst",
"=",
"true",
";",
"sbRes",
".",
"append",
"(",
"sPhysicalName",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"eEntry",
":",
"mParams",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"bFirst",
")",
"{",
"sbRes",
".",
"append",
"(",
"'?'",
")",
";",
"bFirst",
"=",
"false",
";",
"}",
"else",
"{",
"sbRes",
".",
"append",
"(",
"'&'",
")",
";",
"}",
"String",
"sName",
"=",
"eEntry",
".",
"getKey",
"(",
")",
";",
"String",
"sValue",
"=",
"eEntry",
".",
"getValue",
"(",
")",
";",
"sbRes",
".",
"append",
"(",
"sName",
")",
";",
"if",
"(",
"sValue",
"!=",
"null",
")",
"{",
"sbRes",
".",
"append",
"(",
"'='",
")",
";",
"sbRes",
".",
"append",
"(",
"sValue",
")",
";",
"}",
"}",
"return",
"sbRes",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * DOCUMENTME.\n *\n * @param str DOCUMENTME\n *\n * @return DOCUMENTME\n */",
"public",
"static",
"byte",
"[",
"]",
"base64decode",
"(",
"String",
"str",
")",
"{",
"return",
"Base64",
".",
"decode",
"(",
"str",
".",
"toCharArray",
"(",
")",
")",
";",
"}",
"/**\n * DOCUMENTME.\n *\n * @param data DOCUMENTME\n *\n * @return DOCUMENTME\n */",
"public",
"static",
"String",
"base64encode",
"(",
"byte",
"[",
"]",
"data",
")",
"{",
"return",
"new",
"String",
"(",
"Base64",
".",
"encode",
"(",
"data",
")",
")",
";",
"}",
"/**\n * Finds the cause of an exception.\n *\n * @param t the exception to look for the cause\n *\n * @return the cause\n */",
"public",
"static",
"String",
"findCause",
"(",
"Throwable",
"t",
")",
"{",
"String",
"msg",
"=",
"t",
".",
"getMessage",
"(",
")",
";",
"if",
"(",
"(",
"(",
"msg",
"==",
"null",
")",
"||",
"\"",
"\"",
".",
"equals",
"(",
"msg",
")",
")",
"&&",
"(",
"t",
".",
"getCause",
"(",
")",
"!=",
"null",
")",
")",
"{",
"msg",
"=",
"findCause",
"(",
"t",
".",
"getCause",
"(",
")",
")",
";",
"}",
"return",
"msg",
";",
"}",
"/**\n * DOCUMENTME.\n *\n * @param request DOCUMENTME\n * @param implementation DOCUMENTME\n * @param nodeName DOCUMENTME\n * @param requestIsAttribute DOCUMENTME\n * @param defaultValue DOCUMENTME\n *\n * @return DOCUMENTME\n */",
"public",
"static",
"Boolean",
"getBooleanParameter",
"(",
"int",
"request",
",",
"int",
"implementation",
",",
"String",
"nodeName",
",",
"boolean",
"requestIsAttribute",
",",
"Boolean",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"getParameter",
"(",
"request",
",",
"implementation",
",",
"nodeName",
",",
"requestIsAttribute",
",",
"nodeName",
",",
"null",
")",
";",
"if",
"(",
"(",
"value",
"==",
"null",
")",
"||",
"(",
"value",
".",
"length",
"(",
")",
"==",
"0",
")",
")",
"{",
"return",
"defaultValue",
";",
"}",
"if",
"(",
"\"",
"true",
"\"",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"\"",
"false",
"\"",
".",
"equals",
"(",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Invalid value '",
"\"",
"+",
"value",
"+",
"\"",
"' for parameter: ",
"\"",
"+",
"nodeName",
")",
";",
"}",
"}",
"/**\n * Returns the identifier as used in this connector.\n *\n * @param uri The uri to look for\n *\n * @return\n */",
"public",
"static",
"String",
"getDestinationIdentifier",
"(",
"String",
"uri",
")",
"{",
"Destination",
"dest",
"=",
"Destination",
".",
"getDestination",
"(",
"uri",
")",
";",
"if",
"(",
"dest",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"dest",
".",
"getDestinationManager",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"",
".",
"\"",
"+",
"dest",
".",
"getName",
"(",
")",
";",
"}",
"/**\n * Returns the internal (JMS) queue/topic identifier for a given destination, without any\n * parameters.\n *\n * @param destination\n *\n * @return\n *\n * @throws JMSException\n */",
"public",
"static",
"String",
"getDestinationURI",
"(",
"javax",
".",
"jms",
".",
"Destination",
"destination",
")",
"throws",
"JMSException",
"{",
"String",
"destURI",
"=",
"\"",
"\"",
";",
"if",
"(",
"destination",
"instanceof",
"Queue",
")",
"{",
"destURI",
"=",
"(",
"(",
"Queue",
")",
"destination",
")",
".",
"getQueueName",
"(",
")",
";",
"}",
"else",
"if",
"(",
"destination",
"instanceof",
"Topic",
")",
"{",
"destURI",
"=",
"(",
"(",
"Topic",
")",
"destination",
")",
".",
"getTopicName",
"(",
")",
";",
"}",
"if",
"(",
"destURI",
".",
"indexOf",
"(",
"\"",
"?",
"\"",
")",
">",
"-",
"1",
")",
"{",
"destURI",
"=",
"destURI",
".",
"substring",
"(",
"0",
",",
"destURI",
".",
"indexOf",
"(",
"\"",
"?",
"\"",
")",
")",
";",
"}",
"return",
"destURI",
";",
"}",
"/**\n * Returns the JMSConnector name as well as the provider specific destination URL for the given\n * JMS destination. The JMSConnector destination is a destination that is related to the given\n * JMS destination (e.g. the receiving destination).\n *\n * @param dOrigConnectorDest Related JMSConnector destination.\n * @param dDest JMS destination.\n * @param bAddParameters If <code>true</code> dynamic destinations parameters are added\n * to the physical name (provider URL).\n *\n * @return String array where [0] = JMSConnector name, [1] = JMS provider URL (null if the\n * destination is known).\n *\n * @throws JMSException\n */",
"public",
"static",
"String",
"[",
"]",
"getJmsDestinationNames",
"(",
"Destination",
"dOrigConnectorDest",
",",
"javax",
".",
"jms",
".",
"Destination",
"dDest",
",",
"boolean",
"bAddParameters",
")",
"throws",
"JMSException",
"{",
"String",
"sProviderUrl",
"=",
"getDestinationURI",
"(",
"dDest",
")",
";",
"String",
"sConnectorName",
"=",
"getDestinationIdentifier",
"(",
"sProviderUrl",
")",
";",
"if",
"(",
"sConnectorName",
"!=",
"null",
")",
"{",
"return",
"new",
"String",
"[",
"]",
"{",
"sConnectorName",
",",
"null",
"}",
";",
"}",
"Destination",
"dUseDest",
"=",
"null",
";",
"if",
"(",
"(",
"sProviderUrl",
"!=",
"null",
")",
"&&",
"(",
"sProviderUrl",
".",
"length",
"(",
")",
">",
"0",
")",
")",
"{",
"dUseDest",
"=",
"dOrigConnectorDest",
".",
"getDestinationManager",
"(",
")",
".",
"getDynamicDestination",
"(",
")",
";",
"}",
"if",
"(",
"dUseDest",
"==",
"null",
")",
"{",
"dUseDest",
"=",
"dOrigConnectorDest",
";",
"}",
"sConnectorName",
"=",
"dUseDest",
".",
"getDestinationManager",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"",
".",
"\"",
"+",
"dUseDest",
".",
"getName",
"(",
")",
";",
"if",
"(",
"(",
"sProviderUrl",
"!=",
"null",
")",
"&&",
"(",
"sProviderUrl",
".",
"length",
"(",
")",
">",
"0",
")",
"&&",
"bAddParameters",
")",
"{",
"sProviderUrl",
"=",
"appendDynamicDestinationParameters",
"(",
"sProviderUrl",
",",
"dUseDest",
",",
"dUseDest",
".",
"getDynamicDestinationParameterString",
"(",
")",
")",
";",
"}",
"return",
"new",
"String",
"[",
"]",
"{",
"(",
"sConnectorName",
"!=",
"null",
")",
"?",
"sConnectorName",
":",
"\"",
"\"",
",",
"(",
"sProviderUrl",
"!=",
"null",
")",
"?",
"sProviderUrl",
":",
"\"",
"\"",
"}",
";",
"}",
"/**\n * DOCUMENTME.\n *\n * @param request DOCUMENTME\n * @param implementation DOCUMENTME\n * @param nodeName DOCUMENTME\n * @param requestIsAttribute DOCUMENTME\n * @param defaultValue DOCUMENTME\n *\n * @return DOCUMENTME\n */",
"public",
"static",
"Long",
"getLongParameter",
"(",
"int",
"request",
",",
"int",
"implementation",
",",
"String",
"nodeName",
",",
"boolean",
"requestIsAttribute",
",",
"Long",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"getParameter",
"(",
"request",
",",
"implementation",
",",
"nodeName",
",",
"requestIsAttribute",
",",
"nodeName",
",",
"null",
")",
";",
"if",
"(",
"(",
"value",
"==",
"null",
")",
"||",
"(",
"value",
".",
"length",
"(",
")",
"==",
"0",
")",
")",
"{",
"return",
"defaultValue",
";",
"}",
"try",
"{",
"return",
"Long",
".",
"parseLong",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Invalid value '",
"\"",
"+",
"value",
"+",
"\"",
"' for parameter: ",
"\"",
"+",
"nodeName",
")",
";",
"}",
"}",
"/**\n * DOCUMENTME.\n *\n * @param request DOCUMENTME\n * @param implementation DOCUMENTME\n * @param nodeName DOCUMENTME\n * @param defaultValue DOCUMENTME\n *\n * @return DOCUMENTME\n */",
"public",
"static",
"String",
"getParameter",
"(",
"int",
"request",
",",
"int",
"implementation",
",",
"String",
"nodeName",
",",
"String",
"defaultValue",
")",
"{",
"return",
"getParameter",
"(",
"request",
",",
"implementation",
",",
"nodeName",
",",
"false",
",",
"nodeName",
",",
"defaultValue",
")",
";",
"}",
"/**\n * DOCUMENTME.\n *\n * @param request DOCUMENTME\n * @param implementation DOCUMENTME\n * @param requestName DOCUMENTME\n * @param implementationName DOCUMENTME\n * @param defaultValue DOCUMENTME\n *\n * @return DOCUMENTME\n */",
"public",
"static",
"String",
"getParameter",
"(",
"int",
"request",
",",
"int",
"implementation",
",",
"String",
"requestName",
",",
"String",
"implementationName",
",",
"String",
"defaultValue",
")",
"{",
"return",
"getParameter",
"(",
"request",
",",
"implementation",
",",
"requestName",
",",
"false",
",",
"implementationName",
",",
"defaultValue",
")",
";",
"}",
"/**\n * DOCUMENTME.\n *\n * @param request DOCUMENTME\n * @param implementation DOCUMENTME\n * @param nodeName DOCUMENTME\n * @param requestIsAttribute DOCUMENTME\n * @param defaultValue DOCUMENTME\n *\n * @return DOCUMENTME\n */",
"public",
"static",
"String",
"getParameter",
"(",
"int",
"request",
",",
"int",
"implementation",
",",
"String",
"nodeName",
",",
"boolean",
"requestIsAttribute",
",",
"String",
"defaultValue",
")",
"{",
"return",
"getParameter",
"(",
"request",
",",
"implementation",
",",
"nodeName",
",",
"requestIsAttribute",
",",
"nodeName",
",",
"defaultValue",
")",
";",
"}",
"/**\n * Returns a parameter value from the implementation or the request itself, based on the\n * implementation settings.\n *\n * @param request The request xml\n * @param implementation The implementation xml\n * @param requestName The parameter name in the request\n * @param requestIsAttribute true if the parameter is specified in an attribute in the\n * request\n * @param implementationName The parameter name in the implementation\n * @param defaultValue A default value\n *\n * @return the value from the request if the implementation states that it was overridable,\n * else the value from the implementation and if that one is not found either, the\n * default value\n */",
"public",
"static",
"String",
"getParameter",
"(",
"int",
"request",
",",
"int",
"implementation",
",",
"String",
"requestName",
",",
"boolean",
"requestIsAttribute",
",",
"String",
"implementationName",
",",
"String",
"defaultValue",
")",
"{",
"int",
"impNode",
"=",
"Node",
".",
"getElement",
"(",
"implementation",
",",
"implementationName",
")",
";",
"if",
"(",
"(",
"impNode",
"==",
"0",
")",
"||",
"\"",
"true",
"\"",
".",
"equals",
"(",
"Node",
".",
"getAttribute",
"(",
"impNode",
",",
"\"",
"overridable",
"\"",
")",
")",
")",
"{",
"String",
"sRes",
";",
"if",
"(",
"requestIsAttribute",
")",
"{",
"sRes",
"=",
"Node",
".",
"getAttribute",
"(",
"request",
",",
"requestName",
",",
"null",
")",
";",
"}",
"else",
"{",
"sRes",
"=",
"Node",
".",
"getDataElement",
"(",
"request",
",",
"requestName",
",",
"null",
")",
";",
"}",
"if",
"(",
"sRes",
"!=",
"null",
")",
"{",
"return",
"sRes",
";",
"}",
"}",
"return",
"Node",
".",
"getDataWithDefault",
"(",
"impNode",
",",
"defaultValue",
")",
";",
"}",
"/**\n * Returns a better stacktrace especially for JMSExceptions (contain a linked exception with\n * more exception details).\n *\n * @param t the exception to get it from\n *\n * @return a string containing the stacktrace\n */",
"public",
"static",
"String",
"getStackTrace",
"(",
"Throwable",
"t",
")",
"{",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"return",
"\"",
"\"",
";",
"}",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"sb",
".",
"append",
"(",
"t",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"",
": ",
"\"",
")",
";",
"if",
"(",
"t",
".",
"getMessage",
"(",
")",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"t",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"if",
"(",
"t",
"instanceof",
"JMSException",
")",
"{",
"sb",
".",
"append",
"(",
"\"",
"Caused by: ",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getStackTrace",
"(",
"(",
"(",
"JMSException",
")",
"t",
")",
".",
"getLinkedException",
"(",
")",
")",
")",
";",
"}",
"else",
"if",
"(",
"t",
".",
"getCause",
"(",
")",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"\"",
"Caused by: ",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getStackTrace",
"(",
"t",
".",
"getCause",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"StringWriter",
"sw",
"=",
"new",
"StringWriter",
"(",
")",
";",
"PrintWriter",
"pw",
"=",
"new",
"PrintWriter",
"(",
"sw",
")",
";",
"t",
".",
"printStackTrace",
"(",
"pw",
")",
";",
"pw",
".",
"flush",
"(",
")",
";",
"sb",
".",
"append",
"(",
"sw",
".",
"getBuffer",
"(",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * Get the properties from the given xml.\n *\n * @param xml the xml to read the properties from\n * @param nodeName the node name containing the property list\n * @param properties the object to put the properties into\n * @param canChange true if existing properties can be changed\n *\n * @throws JMSConnectorException\n */",
"public",
"static",
"void",
"processProperties",
"(",
"int",
"xml",
",",
"String",
"nodeName",
",",
"Hashtable",
"<",
"String",
",",
"Object",
">",
"properties",
",",
"boolean",
"canChange",
")",
"throws",
"JMSConnectorException",
"{",
"int",
"propNode",
"=",
"Node",
".",
"getElement",
"(",
"xml",
",",
"nodeName",
")",
";",
"if",
"(",
"propNode",
"!=",
"0",
")",
"{",
"for",
"(",
"int",
"cnode",
"=",
"Node",
".",
"getFirstChild",
"(",
"propNode",
")",
";",
"cnode",
"!=",
"0",
";",
"cnode",
"=",
"Node",
".",
"getNextSibling",
"(",
"cnode",
")",
")",
"{",
"String",
"key",
"=",
"Node",
".",
"getAttribute",
"(",
"cnode",
",",
"\"",
"name",
"\"",
")",
";",
"if",
"(",
"!",
"canChange",
"&&",
"properties",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"(",
"key",
"==",
"null",
")",
"||",
"(",
"key",
".",
"length",
"(",
")",
"==",
"0",
")",
")",
"{",
"continue",
";",
"}",
"String",
"type",
"=",
"Node",
".",
"getAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"null",
")",
";",
"if",
"(",
"(",
"type",
"==",
"null",
")",
"||",
"(",
"type",
".",
"length",
"(",
")",
"==",
"0",
")",
")",
"{",
"throw",
"new",
"JMSConnectorException",
"(",
"\"",
"No type found for property '",
"\"",
"+",
"key",
"+",
"\"",
"'",
"\"",
")",
";",
"}",
"String",
"value",
"=",
"Node",
".",
"getData",
"(",
"cnode",
")",
";",
"Object",
"objValue",
";",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"String",
"\"",
")",
")",
"{",
"objValue",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"Short",
"\"",
")",
")",
"{",
"objValue",
"=",
"Short",
".",
"valueOf",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"Byte",
"\"",
")",
")",
"{",
"objValue",
"=",
"Byte",
".",
"valueOf",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"Boolean",
"\"",
")",
")",
"{",
"objValue",
"=",
"Boolean",
".",
"valueOf",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"Double",
"\"",
")",
")",
"{",
"objValue",
"=",
"Double",
".",
"valueOf",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"Float",
"\"",
")",
")",
"{",
"objValue",
"=",
"Float",
".",
"valueOf",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"Integer",
"\"",
")",
")",
"{",
"objValue",
"=",
"Integer",
".",
"valueOf",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"type",
".",
"equals",
"(",
"\"",
"Long",
"\"",
")",
")",
"{",
"objValue",
"=",
"Long",
".",
"valueOf",
"(",
"value",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"JMSConnectorException",
"(",
"\"",
"Unknown type '",
"\"",
"+",
"type",
"+",
"\"",
"' for property '",
"\"",
"+",
"key",
"+",
"\"",
"'",
"\"",
")",
";",
"}",
"properties",
".",
"put",
"(",
"key",
",",
"objValue",
")",
";",
"}",
"}",
"}",
"/**\n * Formats a a string so that it can be put into the log safely. Some characters seem to cause\n * problem.\n *\n * @param oMessage Object to be formatted. Uses toString().\n *\n * @return Formattes string.\n */",
"public",
"static",
"String",
"safeFormatLogMessage",
"(",
"Object",
"oMessage",
")",
"{",
"return",
"safeFormatLogMessage",
"(",
"oMessage",
".",
"toString",
"(",
")",
")",
";",
"}",
"/**\n * Formats a a string so that it can be put into the log safely. Some characters seem to cause\n * problem.\n *\n * @param sMessage Log message to be formatted.\n *\n * @return Formattes string.\n */",
"public",
"static",
"String",
"safeFormatLogMessage",
"(",
"String",
"sMessage",
")",
"{",
"StringBuilder",
"sbRes",
"=",
"new",
"StringBuilder",
"(",
"sMessage",
".",
"length",
"(",
")",
"+",
"20",
")",
";",
"int",
"iLen",
"=",
"sMessage",
".",
"length",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"iLen",
";",
"i",
"++",
")",
"{",
"char",
"ch",
"=",
"sMessage",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"(",
"ch",
"<",
"9",
")",
"||",
"(",
"ch",
"==",
"11",
")",
"||",
"(",
"ch",
"==",
"12",
")",
"||",
"(",
"ch",
">",
"127",
")",
")",
"{",
"sbRes",
".",
"append",
"(",
"\"",
"[",
"\"",
")",
";",
"sbRes",
".",
"append",
"(",
"(",
"int",
")",
"ch",
")",
";",
"sbRes",
".",
"append",
"(",
"\"",
"]",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"(",
"ch",
"==",
"']'",
")",
"&&",
"(",
"i",
"<",
"(",
"iLen",
"-",
"2",
")",
")",
"&&",
"(",
"sMessage",
".",
"charAt",
"(",
"i",
"+",
"1",
")",
"==",
"']'",
")",
"&&",
"(",
"sMessage",
".",
"charAt",
"(",
"i",
"+",
"2",
")",
"==",
"'>'",
")",
")",
"{",
"sbRes",
".",
"append",
"(",
"\"",
"]] >",
"\"",
")",
";",
"i",
"+=",
"2",
";",
"}",
"else",
"{",
"sbRes",
".",
"append",
"(",
"ch",
")",
";",
"}",
"}",
"return",
"sbRes",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * Creates a copy of the message, used to put a message into the error queue.\n *\n * @param inputMsg the message to copy\n * @param session the session to use for the new message\n *\n * @return the copied message\n *\n * @throws JMSException\n * @throws JMSConnectorException\n */",
"protected",
"static",
"Message",
"getCopyOfMessageForSession",
"(",
"Message",
"inputMsg",
",",
"Session",
"session",
")",
"throws",
"JMSException",
",",
"JMSConnectorException",
"{",
"Message",
"outputMsg",
";",
"if",
"(",
"inputMsg",
"instanceof",
"BytesMessage",
")",
"{",
"outputMsg",
"=",
"session",
".",
"createBytesMessage",
"(",
")",
";",
"int",
"len",
"=",
"(",
"int",
")",
"(",
"(",
"BytesMessage",
")",
"inputMsg",
")",
".",
"getBodyLength",
"(",
")",
";",
"byte",
"[",
"]",
"msg",
"=",
"new",
"byte",
"[",
"len",
"]",
";",
"(",
"(",
"BytesMessage",
")",
"inputMsg",
")",
".",
"readBytes",
"(",
"msg",
")",
";",
"(",
"(",
"BytesMessage",
")",
"outputMsg",
")",
".",
"writeBytes",
"(",
"msg",
")",
";",
"}",
"else",
"if",
"(",
"inputMsg",
"instanceof",
"TextMessage",
")",
"{",
"outputMsg",
"=",
"session",
".",
"createTextMessage",
"(",
")",
";",
"(",
"(",
"TextMessage",
")",
"outputMsg",
")",
".",
"setText",
"(",
"(",
"(",
"TextMessage",
")",
"inputMsg",
")",
".",
"getText",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"inputMsg",
"instanceof",
"MapMessage",
")",
"{",
"outputMsg",
"=",
"session",
".",
"createMapMessage",
"(",
")",
";",
"Enumeration",
"<",
"?",
">",
"mapNames",
"=",
"(",
"(",
"MapMessage",
")",
"inputMsg",
")",
".",
"getMapNames",
"(",
")",
";",
"while",
"(",
"mapNames",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"String",
"key",
"=",
"(",
"String",
")",
"mapNames",
".",
"nextElement",
"(",
")",
";",
"(",
"(",
"MapMessage",
")",
"outputMsg",
")",
".",
"setObject",
"(",
"key",
",",
"(",
"(",
"MapMessage",
")",
"inputMsg",
")",
".",
"getObject",
"(",
"key",
")",
")",
";",
"}",
"}",
"else",
"if",
"(",
"inputMsg",
"instanceof",
"ObjectMessage",
")",
"{",
"outputMsg",
"=",
"session",
".",
"createObjectMessage",
"(",
")",
";",
"(",
"(",
"ObjectMessage",
")",
"outputMsg",
")",
".",
"setObject",
"(",
"(",
"(",
"ObjectMessage",
")",
"inputMsg",
")",
".",
"getObject",
"(",
")",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"JMSConnectorException",
"(",
"\"",
"Unsupported message format: ",
"\"",
"+",
"inputMsg",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"if",
"(",
"inputMsg",
".",
"getJMSMessageID",
"(",
")",
"!=",
"null",
")",
"{",
"outputMsg",
".",
"setJMSMessageID",
"(",
"inputMsg",
".",
"getJMSMessageID",
"(",
")",
")",
";",
"}",
"if",
"(",
"inputMsg",
".",
"getJMSCorrelationID",
"(",
")",
"!=",
"null",
")",
"{",
"outputMsg",
".",
"setJMSCorrelationID",
"(",
"inputMsg",
".",
"getJMSCorrelationID",
"(",
")",
")",
";",
"}",
"if",
"(",
"inputMsg",
".",
"getJMSReplyTo",
"(",
")",
"!=",
"null",
")",
"{",
"outputMsg",
".",
"setJMSReplyTo",
"(",
"inputMsg",
".",
"getJMSReplyTo",
"(",
")",
")",
";",
"}",
"if",
"(",
"inputMsg",
".",
"getJMSType",
"(",
")",
"!=",
"null",
")",
"{",
"outputMsg",
".",
"setJMSType",
"(",
"inputMsg",
".",
"getJMSType",
"(",
")",
")",
";",
"}",
"outputMsg",
".",
"setJMSDeliveryMode",
"(",
"inputMsg",
".",
"getJMSDeliveryMode",
"(",
")",
")",
";",
"outputMsg",
".",
"setJMSExpiration",
"(",
"inputMsg",
".",
"getJMSExpiration",
"(",
")",
")",
";",
"outputMsg",
".",
"setJMSPriority",
"(",
"inputMsg",
".",
"getJMSPriority",
"(",
")",
")",
";",
"outputMsg",
".",
"setJMSRedelivered",
"(",
"inputMsg",
".",
"getJMSRedelivered",
"(",
")",
")",
";",
"outputMsg",
".",
"setJMSTimestamp",
"(",
"inputMsg",
".",
"getJMSTimestamp",
"(",
")",
")",
";",
"Enumeration",
"<",
"?",
">",
"properties",
"=",
"inputMsg",
".",
"getPropertyNames",
"(",
")",
";",
"while",
"(",
"properties",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"String",
"key",
"=",
"(",
"String",
")",
"properties",
".",
"nextElement",
"(",
")",
";",
"if",
"(",
"key",
".",
"startsWith",
"(",
"\"",
"JMSX",
"\"",
")",
")",
"{",
"continue",
";",
"}",
"outputMsg",
".",
"setObjectProperty",
"(",
"key",
",",
"inputMsg",
".",
"getObjectProperty",
"(",
"key",
")",
")",
";",
"}",
"return",
"outputMsg",
";",
"}",
"/**\n * Convert a message to XML.\n *\n * @param dDest Destination the this message comes from.\n * @param msg The message\n * @param resultNode the xml node containing the xml representation\n *\n * @throws JMSException\n */",
"protected",
"static",
"void",
"getInformationFromMessage",
"(",
"Destination",
"dDest",
",",
"Message",
"msg",
",",
"int",
"resultNode",
")",
"throws",
"JMSException",
"{",
"Node",
".",
"createTextElement",
"(",
"\"",
"messageid",
"\"",
",",
"msg",
".",
"getJMSMessageID",
"(",
")",
",",
"resultNode",
")",
";",
"if",
"(",
"msg",
".",
"getJMSCorrelationID",
"(",
")",
"!=",
"null",
")",
"{",
"Node",
".",
"createTextElement",
"(",
"\"",
"correlationid",
"\"",
",",
"msg",
".",
"getJMSCorrelationID",
"(",
")",
",",
"resultNode",
")",
";",
"}",
"if",
"(",
"msg",
".",
"getJMSType",
"(",
")",
"!=",
"null",
")",
"{",
"Node",
".",
"createTextElement",
"(",
"\"",
"jmstype",
"\"",
",",
"msg",
".",
"getJMSType",
"(",
")",
",",
"resultNode",
")",
";",
"}",
"if",
"(",
"msg",
".",
"getJMSReplyTo",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"[",
"]",
"saNames",
"=",
"getJmsDestinationNames",
"(",
"dDest",
",",
"msg",
".",
"getJMSReplyTo",
"(",
")",
",",
"true",
")",
";",
"int",
"xTmpNode",
";",
"xTmpNode",
"=",
"Node",
".",
"createTextElement",
"(",
"\"",
"reply2destination",
"\"",
",",
"saNames",
"[",
"0",
"]",
",",
"resultNode",
")",
";",
"if",
"(",
"saNames",
"[",
"1",
"]",
"!=",
"null",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"xTmpNode",
",",
"Destination",
".",
"DESTINATION_PHYSICALNAME_ATTRIB",
",",
"saNames",
"[",
"1",
"]",
")",
";",
"}",
"}",
"{",
"String",
"[",
"]",
"saNames",
"=",
"getJmsDestinationNames",
"(",
"dDest",
",",
"msg",
".",
"getJMSDestination",
"(",
")",
",",
"true",
")",
";",
"int",
"xTmpNode",
";",
"xTmpNode",
"=",
"Node",
".",
"createTextElement",
"(",
"\"",
"fromdestination",
"\"",
",",
"saNames",
"[",
"0",
"]",
",",
"resultNode",
")",
";",
"if",
"(",
"saNames",
"[",
"1",
"]",
"!=",
"null",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"xTmpNode",
",",
"Destination",
".",
"DESTINATION_PHYSICALNAME_ATTRIB",
",",
"saNames",
"[",
"1",
"]",
")",
";",
"}",
"}",
"Enumeration",
"<",
"?",
">",
"properties",
"=",
"msg",
".",
"getPropertyNames",
"(",
")",
";",
"if",
"(",
"properties",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"int",
"propNode",
"=",
"Node",
".",
"createElement",
"(",
"\"",
"properties",
"\"",
",",
"resultNode",
")",
";",
"while",
"(",
"properties",
".",
"hasMoreElements",
"(",
")",
")",
"{",
"String",
"key",
"=",
"(",
"String",
")",
"properties",
".",
"nextElement",
"(",
")",
";",
"Object",
"value",
"=",
"msg",
".",
"getObjectProperty",
"(",
"key",
")",
";",
"int",
"cnode",
"=",
"Node",
".",
"createTextElement",
"(",
"\"",
"property",
"\"",
",",
"String",
".",
"valueOf",
"(",
"value",
")",
",",
"propNode",
")",
";",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"name",
"\"",
",",
"key",
")",
";",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"String",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Short",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Short",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Byte",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Byte",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Boolean",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Boolean",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Double",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Double",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Float",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Float",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Integer",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Integer",
"\"",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"Long",
")",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Long",
"\"",
")",
";",
"}",
"else",
"{",
"Node",
".",
"setAttribute",
"(",
"cnode",
",",
"\"",
"type",
"\"",
",",
"\"",
"Object",
"\"",
")",
";",
"}",
"}",
"}",
"}",
"}"
] | DOCUMENTME
. | [
"DOCUMENTME",
"."
] | [
"// Parse them in to a hash map, so later we can do parameter merging.",
"// Discard the possible query part from the physical name.",
"// remove all possible parameters...",
"// Unknown static destination. Just set it as a dynamic one.",
"// Destination physical name is known, so try to find a dynamic destination.",
"// No dynamic destination configured or the physical name was not known, so just",
"// use the default one. For triggers this is the destination to which the trigger is",
"// attached to.",
"// Escape CDATA end marker.",
"// StreamMessage is not implemented!!!",
"// Unknown as a static destination. Just set it as a dynamic one.",
"// Set the from destination too.",
"// Unknown as a static destination. Just set it as a dynamic one."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9a2b7ce693b278ce732b9a48e437e392a78184a | se-bastiaan/MarieDroid | app/src/main/java/eu/se_bastiaan/marietje/util/EventBus.java | [
"Apache-2.0"
] | Java | EventBus | /**
* A simple event bus built with RxJava
*/ | A simple event bus built with RxJava | [
"A",
"simple",
"event",
"bus",
"built",
"with",
"RxJava"
] | @Singleton
public class EventBus {
@Inject
public EventBus() {
// Public empty constructor
}
private final Subject<Object, Object> busSubject = new SerializedSubject<>(PublishSubject.create());
public <T> Subscription register(final Class<T> eventClass, Action1<T> onNext) {
return busSubject
.filter(event -> event.getClass().equals(eventClass))
.map(obj -> (T) obj)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> {
Timber.w(throwable, "Error in EventBus");
})
.onErrorResumeNext(throwable -> Observable.empty())
.subscribe(onNext);
}
public <T> Subscription register(final Class<T> eventClass, Subscriber<T> subscriber) {
return busSubject
.filter(event -> event.getClass().equals(eventClass))
.map(obj -> (T) obj)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> {
Timber.w(throwable, "Error in EventBus");
})
.onErrorResumeNext(throwable -> Observable.empty())
.subscribe(subscriber);
}
public <T> Observable<T> register(final Class<T> eventClass) {
return busSubject
.filter(event -> event.getClass().equals(eventClass))
.map(obj -> (T) obj)
.doOnError(throwable -> {
Timber.w(throwable, "Error in EventBus");
})
.onErrorResumeNext(throwable -> Observable.empty())
.observeOn(AndroidSchedulers.mainThread());
}
public void post(Object event) {
busSubject.onNext(event);
}
} | [
"@",
"Singleton",
"public",
"class",
"EventBus",
"{",
"@",
"Inject",
"public",
"EventBus",
"(",
")",
"{",
"}",
"private",
"final",
"Subject",
"<",
"Object",
",",
"Object",
">",
"busSubject",
"=",
"new",
"SerializedSubject",
"<",
">",
"(",
"PublishSubject",
".",
"create",
"(",
")",
")",
";",
"public",
"<",
"T",
">",
"Subscription",
"register",
"(",
"final",
"Class",
"<",
"T",
">",
"eventClass",
",",
"Action1",
"<",
"T",
">",
"onNext",
")",
"{",
"return",
"busSubject",
".",
"filter",
"(",
"event",
"->",
"event",
".",
"getClass",
"(",
")",
".",
"equals",
"(",
"eventClass",
")",
")",
".",
"map",
"(",
"obj",
"->",
"(",
"T",
")",
"obj",
")",
".",
"observeOn",
"(",
"AndroidSchedulers",
".",
"mainThread",
"(",
")",
")",
".",
"doOnError",
"(",
"throwable",
"->",
"{",
"Timber",
".",
"w",
"(",
"throwable",
",",
"\"",
"Error in EventBus",
"\"",
")",
";",
"}",
")",
".",
"onErrorResumeNext",
"(",
"throwable",
"->",
"Observable",
".",
"empty",
"(",
")",
")",
".",
"subscribe",
"(",
"onNext",
")",
";",
"}",
"public",
"<",
"T",
">",
"Subscription",
"register",
"(",
"final",
"Class",
"<",
"T",
">",
"eventClass",
",",
"Subscriber",
"<",
"T",
">",
"subscriber",
")",
"{",
"return",
"busSubject",
".",
"filter",
"(",
"event",
"->",
"event",
".",
"getClass",
"(",
")",
".",
"equals",
"(",
"eventClass",
")",
")",
".",
"map",
"(",
"obj",
"->",
"(",
"T",
")",
"obj",
")",
".",
"observeOn",
"(",
"AndroidSchedulers",
".",
"mainThread",
"(",
")",
")",
".",
"doOnError",
"(",
"throwable",
"->",
"{",
"Timber",
".",
"w",
"(",
"throwable",
",",
"\"",
"Error in EventBus",
"\"",
")",
";",
"}",
")",
".",
"onErrorResumeNext",
"(",
"throwable",
"->",
"Observable",
".",
"empty",
"(",
")",
")",
".",
"subscribe",
"(",
"subscriber",
")",
";",
"}",
"public",
"<",
"T",
">",
"Observable",
"<",
"T",
">",
"register",
"(",
"final",
"Class",
"<",
"T",
">",
"eventClass",
")",
"{",
"return",
"busSubject",
".",
"filter",
"(",
"event",
"->",
"event",
".",
"getClass",
"(",
")",
".",
"equals",
"(",
"eventClass",
")",
")",
".",
"map",
"(",
"obj",
"->",
"(",
"T",
")",
"obj",
")",
".",
"doOnError",
"(",
"throwable",
"->",
"{",
"Timber",
".",
"w",
"(",
"throwable",
",",
"\"",
"Error in EventBus",
"\"",
")",
";",
"}",
")",
".",
"onErrorResumeNext",
"(",
"throwable",
"->",
"Observable",
".",
"empty",
"(",
")",
")",
".",
"observeOn",
"(",
"AndroidSchedulers",
".",
"mainThread",
"(",
")",
")",
";",
"}",
"public",
"void",
"post",
"(",
"Object",
"event",
")",
"{",
"busSubject",
".",
"onNext",
"(",
"event",
")",
";",
"}",
"}"
] | A simple event bus built with RxJava | [
"A",
"simple",
"event",
"bus",
"built",
"with",
"RxJava"
] | [
"// Public empty constructor"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9a4f5fe23e0c6e1cbd5bc19ee850cf52c6105e8 | jbartok/hazelcast-jet-code-samples | enrichment/src/main/java/Enrichment.java | [
"Apache-2.0"
] | Java | Enrichment | /**
* Demonstrates the usage of the Pipeline API to enrich a data stream. We
* generate a stream of stock trade events and each event has an associated
* product ID and broker ID. The reference lists of products and brokers
* are stored in files. The goal is to enrich the trades with the actual
* name of the products and the brokers.
* <p>
* This example shows different ways of achieving this goal:
* <ol>
* <li>Using Hazelcast {@code IMap}</li>
* <li>Using Hazelcast {@code ReplicatedMap}</li>
* <li>Using an external service (gRPC in this sample)</li>
* <li>Using the pipeline {@code hashJoin} operation</li>
* </ol>
* <p>
* The details of each approach are documented with the associated method.
* <p>
* We generate the stream of trade events by updating a single key in the
* {@code trades} map which has the Event Journal enabled. The event
* journal emits a stream of update events.
*/ | Demonstrates the usage of the Pipeline API to enrich a data stream. We
generate a stream of stock trade events and each event has an associated
product ID and broker ID. The reference lists of products and brokers
are stored in files. The goal is to enrich the trades with the actual
name of the products and the brokers.
This example shows different ways of achieving this goal:
Using Hazelcast IMap
Using Hazelcast ReplicatedMap
Using an external service (gRPC in this sample)
Using the pipeline hashJoin operation
The details of each approach are documented with the associated method.
We generate the stream of trade events by updating a single key in the
trades map which has the Event Journal enabled. The event
journal emits a stream of update events. | [
"Demonstrates",
"the",
"usage",
"of",
"the",
"Pipeline",
"API",
"to",
"enrich",
"a",
"data",
"stream",
".",
"We",
"generate",
"a",
"stream",
"of",
"stock",
"trade",
"events",
"and",
"each",
"event",
"has",
"an",
"associated",
"product",
"ID",
"and",
"broker",
"ID",
".",
"The",
"reference",
"lists",
"of",
"products",
"and",
"brokers",
"are",
"stored",
"in",
"files",
".",
"The",
"goal",
"is",
"to",
"enrich",
"the",
"trades",
"with",
"the",
"actual",
"name",
"of",
"the",
"products",
"and",
"the",
"brokers",
".",
"This",
"example",
"shows",
"different",
"ways",
"of",
"achieving",
"this",
"goal",
":",
"Using",
"Hazelcast",
"IMap",
"Using",
"Hazelcast",
"ReplicatedMap",
"Using",
"an",
"external",
"service",
"(",
"gRPC",
"in",
"this",
"sample",
")",
"Using",
"the",
"pipeline",
"hashJoin",
"operation",
"The",
"details",
"of",
"each",
"approach",
"are",
"documented",
"with",
"the",
"associated",
"method",
".",
"We",
"generate",
"the",
"stream",
"of",
"trade",
"events",
"by",
"updating",
"a",
"single",
"key",
"in",
"the",
"trades",
"map",
"which",
"has",
"the",
"Event",
"Journal",
"enabled",
".",
"The",
"event",
"journal",
"emits",
"a",
"stream",
"of",
"update",
"events",
"."
] | public final class Enrichment {
private static final String TRADES = "trades";
private static final String PRODUCTS = "products";
private static final String BROKERS = "brokers";
private final JetInstance jet;
private Enrichment(JetInstance jet) {
this.jet = jet;
}
/**
* Builds a pipeline which enriches the stream using an {@link IMap}.
* <p>
* It loads two {@code IMap}s with the data from the files and then looks
* up from them for every incoming trade using the {@link
* StreamStage#mapUsingIMap mapUsingIMap} transform. Since the
* {@code IMap} is a distributed data structure, some of the lookups will
* have to go through the network to another cluster member.
* <p>
* With this approach you can modify the data in the {@code IMap} while the
* job is running and it will immediately see the changed data.
*/
private Pipeline enrichUsingIMap() {
IMapJet<Integer, Product> productMap = jet.getMap(PRODUCTS);
readLines("products.txt").forEach(e -> productMap.put(e.getKey(), new Product(e.getKey(), e.getValue())));
System.out.println("Loaded product map:");
printMap(productMap);
IMapJet<Integer, Broker> brokerMap = jet.getMap(BROKERS);
readLines("brokers.txt").forEach(e -> brokerMap.put(e.getKey(), new Broker(e.getKey(), e.getValue())));
System.out.println("Loaded brokers map:");
printMap(brokerMap);
Pipeline p = Pipeline.create();
// The stream to be enriched: trades
StreamStage<Trade> trades = p
.drawFrom(Sources.<Object, Trade>mapJournal(TRADES, START_FROM_CURRENT))
.withoutTimestamps()
.map(entryValue());
// first enrich the trade by looking up the product from the IMap
trades
.mapUsingIMap(
productMap, // target map to lookup
trade -> trade.productId(), // key to lookup in the map
(t, product) -> tuple2(t, product.name()) // merge the value in the map with the trade
)
// (trade, productName)
.mapUsingIMap(
brokerMap,
t -> t.f0().brokerId(),
(t, broker) -> tuple3(t.f0(), t.f1(), broker.name())
)
// (trade, productName, brokerName)
.drainTo(Sinks.logger());
return p;
}
/**
* Builds a pipeline which enriches the stream using a {@link ReplicatedMap}.
* <p>
* It loads two {@code ReplicatedMap}s with the data from the files and
* then looks up from them for every incoming trade using the {@link
* StreamStage#mapUsingReplicatedMap mapUsingReplicatedMap} transform.
* Since the {@code ReplicatedMap} replicates its complete contents on each
* member, all the lookups will be local. Compared to the {@code IMap} this
* means better performance, but also a higher memory cost.
* <p>
* With this approach you can modify the data in the {@code ReplicatedMap}
* while the job is running and it will immediately see the changed data.
*/
private Pipeline enrichUsingReplicatedMap() {
ReplicatedMap<Integer, Product> productMap = jet.getReplicatedMap(PRODUCTS);
readLines("products.txt").forEach(e -> productMap.put(e.getKey(), new Product(e.getKey(), e.getValue())));
System.out.println("Loaded product replicated map:");
printMap(productMap);
ReplicatedMap<Integer, Broker> brokerMap = jet.getReplicatedMap(BROKERS);
readLines("brokers.txt").forEach(e -> brokerMap.put(e.getKey(), new Broker(e.getKey(), e.getValue())));
System.out.println("Loaded brokers replicated map:");
printMap(brokerMap);
Pipeline p = Pipeline.create();
// The stream to be enriched: trades
StreamStage<Trade> trades = p
.drawFrom(Sources.<Object, Trade>mapJournal(TRADES, START_FROM_CURRENT))
.withoutTimestamps()
.map(entryValue());
// first enrich the trade by looking up the product from the replicated map
trades
.mapUsingReplicatedMap(
productMap, // target map to lookup
Trade::productId, // key to lookup in the map
(t, product) -> tuple2(t, product.name()) // merge the value in the map with the trade
)
// (trade, productName)
.mapUsingReplicatedMap(
brokerMap,
t -> t.f0().brokerId(),
(t, broker) -> tuple3(t.f0(), t.f1(), broker.name())
)
// (trade, productName, brokerName)
.drainTo(Sinks.logger());
return p;
}
/**
* Builds a pipeline which enriches the stream with the response from a
* remote service.
* <p>
* It starts a gRPC server that will provide product and broker names based
* on an ID. The job then enriches incoming trades using the service. This
* sample demonstrates a way to call external service with an async API
* using the {@link GeneralStage#mapUsingContextAsync mapUsingContextAsync}
* method.
*/
private static Pipeline enrichUsingAsyncService() throws Exception {
Map<Integer, Product> productMap = readLines("products.txt")
.collect(toMap(Entry::getKey, e -> new Product(e.getKey(), e.getValue())));
Map<Integer, Broker> brokerMap = readLines("brokers.txt")
.collect(toMap(Entry::getKey, e -> new Broker(e.getKey(), e.getValue())));
int port = 50051;
ServerBuilder.forPort(port)
.addService(new EnrichmentServiceImpl(productMap, brokerMap))
.build()
.start();
System.out.println("*** Server started, listening on " + port);
// The stream to be enriched: trades
Pipeline p = Pipeline.create();
StreamStage<Trade> trades = p
.drawFrom(Sources.<Object, Trade>mapJournal(TRADES, START_FROM_CURRENT))
.withoutTimestamps()
.map(entryValue());
// The context factory is the same for both enrichment steps
ContextFactory<EnrichmentServiceFutureStub> contextFactory = ContextFactory
.withCreateFn(x -> {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port)
.usePlaintext().build();
return EnrichmentServiceGrpc.newFutureStub(channel);
})
.withDestroyFn(stub -> {
ManagedChannel channel = (ManagedChannel) stub.getChannel();
channel.shutdown().awaitTermination(5, SECONDS);
});
// Enrich the trade by querying the product and broker name from the gRPC service
trades
.mapUsingContextAsync(contextFactory,
(stub, t) -> {
ProductInfoRequest request = ProductInfoRequest.newBuilder().setId(t.productId()).build();
return toCompletableFuture(stub.productInfo(request))
.thenApply(productReply -> tuple2(t, productReply.getProductName()));
})
.mapUsingContextAsync(contextFactory,
(stub, t) -> {
BrokerInfoRequest request = BrokerInfoRequest.newBuilder().setId(t.f0().brokerId()).build();
return toCompletableFuture(stub.brokerInfo(request))
.thenApply(brokerReply -> tuple3(t.f0(), t.f1(), brokerReply.getBrokerName()));
})
.drainTo(Sinks.logger());
return p;
}
/**
* Builds a pipeline which enriches the stream using the
* {@linkplain GeneralStage#hashJoin hash-join} transform.
* <p>
* When using the hash join, you don't have to pre-load any maps with the
* data. The Jet job will pull the data itself from files and store them
* in internal hashtables. The hashtables are read-only so you can't keep
* the data up-to-date while the job is running.
* <p>
* Like the {@code ReplicatedMap}, the hash-join transform stores all the
* enriching data at all cluster members. The data is read-only so there
* are no synchronization overheads, making this the fastest approach to
* data enrichment.
* <p>
* Since the enriching data is stored internally with the running job, once
* it completes the data is automatically released so there are no memory
* leak issues to deal with.
*/
private static Pipeline enrichUsingHashJoin() {
Pipeline p = Pipeline.create();
// The stream to be enriched: trades
StreamStage<Trade> trades = p.drawFrom(Sources.<Object, Trade>mapJournal(TRADES, START_FROM_CURRENT))
.withoutTimestamps()
.map(entryValue());
// The enriching streams: products and brokers
String resourcesPath = getClasspathDirectory(".").toString();
BatchSource<Map.Entry<Integer, Product>> products = Sources
.filesBuilder(resourcesPath)
.sharedFileSystem(true)
.glob("products.txt")
.build((file, line) -> {
Map.Entry<Integer, String> split = splitLine(line);
return entry(split.getKey(), new Product(split.getKey(), split.getValue()));
});
BatchSource<Map.Entry<Integer, Broker>> brokers = Sources
.filesBuilder(resourcesPath)
.sharedFileSystem(true)
.glob("brokers.txt")
.build((file, line) -> {
Map.Entry<Integer, String> split = splitLine(line);
return entry(split.getKey(), new Broker(split.getKey(), split.getValue()));
});
BatchStage<Map.Entry<Integer, Product>> prodEntries = p.drawFrom(products);
BatchStage<Map.Entry<Integer, Broker>> brokEntries = p.drawFrom(brokers);
// Join the trade stream with the product and broker streams
trades.hashJoin2(
prodEntries, joinMapEntries(Trade::productId),
brokEntries, joinMapEntries(Trade::brokerId),
Tuple3::tuple3
).drainTo(Sinks.logger());
return p;
}
public static void main(String[] args) throws Exception {
System.setProperty("hazelcast.logging.type", "log4j");
JetConfig cfg = new JetConfig();
cfg.getHazelcastConfig().getMapEventJournalConfig(TRADES).setEnabled(true);
JetInstance jet = Jet.newJetInstance(cfg);
Jet.newJetInstance(cfg);
new Enrichment(jet).go();
}
private void go() throws Exception {
EventGenerator eventGenerator = new EventGenerator(jet.getMap(TRADES));
eventGenerator.start();
try {
// comment out the code to try the appropriate enrichment method
Pipeline p = enrichUsingIMap();
// Pipeline p = enrichUsingReplicatedMap();
// Pipeline p = enrichUsingAsyncService();
// Pipeline p = enrichUsingHashJoin();
Job job = jet.newJob(p);
eventGenerator.generateEventsForFiveSeconds();
job.cancel();
try {
job.join();
} catch (CancellationException ignored) {
}
} finally {
eventGenerator.shutdown();
Jet.shutdownAll();
}
}
private static Stream<Map.Entry<Integer, String>> readLines(String file) {
try {
return Files.lines(Paths.get(Enrichment.class.getResource(file).toURI()))
.map(Enrichment::splitLine);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static Map.Entry<Integer, String> splitLine(String e) {
int commaPos = e.indexOf(',');
return entry(Integer.valueOf(e.substring(0, commaPos)), e.substring(commaPos + 1));
}
private static <K, V> void printMap(Map<K, V> imap) {
StringBuilder sb = new StringBuilder();
imap.forEach((k, v) -> sb.append(k).append("->").append(v).append('\n'));
System.out.println(sb);
}
private static Path getClasspathDirectory(String name) {
try {
return Paths.get(Enrichment.class.getResource(name).toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
/**
* Adapt a {@link ListenableFuture} to java standard {@link
* CompletableFuture}, which is used by Jet.
*/
private static <T> CompletableFuture<T> toCompletableFuture(ListenableFuture<T> lf) {
CompletableFuture<T> f = new CompletableFuture<>();
// note that we don't handle CompletableFuture.cancel()
Futures.addCallback(lf, new FutureCallback<T>() {
@Override
public void onSuccess(@NullableDecl T result) {
f.complete(result);
}
@Override
public void onFailure(Throwable t) {
f.completeExceptionally(t);
}
});
return f;
}
} | [
"public",
"final",
"class",
"Enrichment",
"{",
"private",
"static",
"final",
"String",
"TRADES",
"=",
"\"",
"trades",
"\"",
";",
"private",
"static",
"final",
"String",
"PRODUCTS",
"=",
"\"",
"products",
"\"",
";",
"private",
"static",
"final",
"String",
"BROKERS",
"=",
"\"",
"brokers",
"\"",
";",
"private",
"final",
"JetInstance",
"jet",
";",
"private",
"Enrichment",
"(",
"JetInstance",
"jet",
")",
"{",
"this",
".",
"jet",
"=",
"jet",
";",
"}",
"/**\n * Builds a pipeline which enriches the stream using an {@link IMap}.\n * <p>\n * It loads two {@code IMap}s with the data from the files and then looks\n * up from them for every incoming trade using the {@link\n * StreamStage#mapUsingIMap mapUsingIMap} transform. Since the\n * {@code IMap} is a distributed data structure, some of the lookups will\n * have to go through the network to another cluster member.\n * <p>\n * With this approach you can modify the data in the {@code IMap} while the\n * job is running and it will immediately see the changed data.\n */",
"private",
"Pipeline",
"enrichUsingIMap",
"(",
")",
"{",
"IMapJet",
"<",
"Integer",
",",
"Product",
">",
"productMap",
"=",
"jet",
".",
"getMap",
"(",
"PRODUCTS",
")",
";",
"readLines",
"(",
"\"",
"products.txt",
"\"",
")",
".",
"forEach",
"(",
"e",
"->",
"productMap",
".",
"put",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"new",
"Product",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"e",
".",
"getValue",
"(",
")",
")",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Loaded product map:",
"\"",
")",
";",
"printMap",
"(",
"productMap",
")",
";",
"IMapJet",
"<",
"Integer",
",",
"Broker",
">",
"brokerMap",
"=",
"jet",
".",
"getMap",
"(",
"BROKERS",
")",
";",
"readLines",
"(",
"\"",
"brokers.txt",
"\"",
")",
".",
"forEach",
"(",
"e",
"->",
"brokerMap",
".",
"put",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"new",
"Broker",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"e",
".",
"getValue",
"(",
")",
")",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Loaded brokers map:",
"\"",
")",
";",
"printMap",
"(",
"brokerMap",
")",
";",
"Pipeline",
"p",
"=",
"Pipeline",
".",
"create",
"(",
")",
";",
"StreamStage",
"<",
"Trade",
">",
"trades",
"=",
"p",
".",
"drawFrom",
"(",
"Sources",
".",
"<",
"Object",
",",
"Trade",
">",
"mapJournal",
"(",
"TRADES",
",",
"START_FROM_CURRENT",
")",
")",
".",
"withoutTimestamps",
"(",
")",
".",
"map",
"(",
"entryValue",
"(",
")",
")",
";",
"trades",
".",
"mapUsingIMap",
"(",
"productMap",
",",
"trade",
"->",
"trade",
".",
"productId",
"(",
")",
",",
"(",
"t",
",",
"product",
")",
"->",
"tuple2",
"(",
"t",
",",
"product",
".",
"name",
"(",
")",
")",
")",
".",
"mapUsingIMap",
"(",
"brokerMap",
",",
"t",
"->",
"t",
".",
"f0",
"(",
")",
".",
"brokerId",
"(",
")",
",",
"(",
"t",
",",
"broker",
")",
"->",
"tuple3",
"(",
"t",
".",
"f0",
"(",
")",
",",
"t",
".",
"f1",
"(",
")",
",",
"broker",
".",
"name",
"(",
")",
")",
")",
".",
"drainTo",
"(",
"Sinks",
".",
"logger",
"(",
")",
")",
";",
"return",
"p",
";",
"}",
"/**\n * Builds a pipeline which enriches the stream using a {@link ReplicatedMap}.\n * <p>\n * It loads two {@code ReplicatedMap}s with the data from the files and\n * then looks up from them for every incoming trade using the {@link\n * StreamStage#mapUsingReplicatedMap mapUsingReplicatedMap} transform.\n * Since the {@code ReplicatedMap} replicates its complete contents on each\n * member, all the lookups will be local. Compared to the {@code IMap} this\n * means better performance, but also a higher memory cost.\n * <p>\n * With this approach you can modify the data in the {@code ReplicatedMap}\n * while the job is running and it will immediately see the changed data.\n */",
"private",
"Pipeline",
"enrichUsingReplicatedMap",
"(",
")",
"{",
"ReplicatedMap",
"<",
"Integer",
",",
"Product",
">",
"productMap",
"=",
"jet",
".",
"getReplicatedMap",
"(",
"PRODUCTS",
")",
";",
"readLines",
"(",
"\"",
"products.txt",
"\"",
")",
".",
"forEach",
"(",
"e",
"->",
"productMap",
".",
"put",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"new",
"Product",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"e",
".",
"getValue",
"(",
")",
")",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Loaded product replicated map:",
"\"",
")",
";",
"printMap",
"(",
"productMap",
")",
";",
"ReplicatedMap",
"<",
"Integer",
",",
"Broker",
">",
"brokerMap",
"=",
"jet",
".",
"getReplicatedMap",
"(",
"BROKERS",
")",
";",
"readLines",
"(",
"\"",
"brokers.txt",
"\"",
")",
".",
"forEach",
"(",
"e",
"->",
"brokerMap",
".",
"put",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"new",
"Broker",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"e",
".",
"getValue",
"(",
")",
")",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Loaded brokers replicated map:",
"\"",
")",
";",
"printMap",
"(",
"brokerMap",
")",
";",
"Pipeline",
"p",
"=",
"Pipeline",
".",
"create",
"(",
")",
";",
"StreamStage",
"<",
"Trade",
">",
"trades",
"=",
"p",
".",
"drawFrom",
"(",
"Sources",
".",
"<",
"Object",
",",
"Trade",
">",
"mapJournal",
"(",
"TRADES",
",",
"START_FROM_CURRENT",
")",
")",
".",
"withoutTimestamps",
"(",
")",
".",
"map",
"(",
"entryValue",
"(",
")",
")",
";",
"trades",
".",
"mapUsingReplicatedMap",
"(",
"productMap",
",",
"Trade",
"::",
"productId",
",",
"(",
"t",
",",
"product",
")",
"->",
"tuple2",
"(",
"t",
",",
"product",
".",
"name",
"(",
")",
")",
")",
".",
"mapUsingReplicatedMap",
"(",
"brokerMap",
",",
"t",
"->",
"t",
".",
"f0",
"(",
")",
".",
"brokerId",
"(",
")",
",",
"(",
"t",
",",
"broker",
")",
"->",
"tuple3",
"(",
"t",
".",
"f0",
"(",
")",
",",
"t",
".",
"f1",
"(",
")",
",",
"broker",
".",
"name",
"(",
")",
")",
")",
".",
"drainTo",
"(",
"Sinks",
".",
"logger",
"(",
")",
")",
";",
"return",
"p",
";",
"}",
"/**\n * Builds a pipeline which enriches the stream with the response from a\n * remote service.\n * <p>\n * It starts a gRPC server that will provide product and broker names based\n * on an ID. The job then enriches incoming trades using the service. This\n * sample demonstrates a way to call external service with an async API\n * using the {@link GeneralStage#mapUsingContextAsync mapUsingContextAsync}\n * method.\n */",
"private",
"static",
"Pipeline",
"enrichUsingAsyncService",
"(",
")",
"throws",
"Exception",
"{",
"Map",
"<",
"Integer",
",",
"Product",
">",
"productMap",
"=",
"readLines",
"(",
"\"",
"products.txt",
"\"",
")",
".",
"collect",
"(",
"toMap",
"(",
"Entry",
"::",
"getKey",
",",
"e",
"->",
"new",
"Product",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"e",
".",
"getValue",
"(",
")",
")",
")",
")",
";",
"Map",
"<",
"Integer",
",",
"Broker",
">",
"brokerMap",
"=",
"readLines",
"(",
"\"",
"brokers.txt",
"\"",
")",
".",
"collect",
"(",
"toMap",
"(",
"Entry",
"::",
"getKey",
",",
"e",
"->",
"new",
"Broker",
"(",
"e",
".",
"getKey",
"(",
")",
",",
"e",
".",
"getValue",
"(",
")",
")",
")",
")",
";",
"int",
"port",
"=",
"50051",
";",
"ServerBuilder",
".",
"forPort",
"(",
"port",
")",
".",
"addService",
"(",
"new",
"EnrichmentServiceImpl",
"(",
"productMap",
",",
"brokerMap",
")",
")",
".",
"build",
"(",
")",
".",
"start",
"(",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"*** Server started, listening on ",
"\"",
"+",
"port",
")",
";",
"Pipeline",
"p",
"=",
"Pipeline",
".",
"create",
"(",
")",
";",
"StreamStage",
"<",
"Trade",
">",
"trades",
"=",
"p",
".",
"drawFrom",
"(",
"Sources",
".",
"<",
"Object",
",",
"Trade",
">",
"mapJournal",
"(",
"TRADES",
",",
"START_FROM_CURRENT",
")",
")",
".",
"withoutTimestamps",
"(",
")",
".",
"map",
"(",
"entryValue",
"(",
")",
")",
";",
"ContextFactory",
"<",
"EnrichmentServiceFutureStub",
">",
"contextFactory",
"=",
"ContextFactory",
".",
"withCreateFn",
"(",
"x",
"->",
"{",
"ManagedChannel",
"channel",
"=",
"ManagedChannelBuilder",
".",
"forAddress",
"(",
"\"",
"localhost",
"\"",
",",
"port",
")",
".",
"usePlaintext",
"(",
")",
".",
"build",
"(",
")",
";",
"return",
"EnrichmentServiceGrpc",
".",
"newFutureStub",
"(",
"channel",
")",
";",
"}",
")",
".",
"withDestroyFn",
"(",
"stub",
"->",
"{",
"ManagedChannel",
"channel",
"=",
"(",
"ManagedChannel",
")",
"stub",
".",
"getChannel",
"(",
")",
";",
"channel",
".",
"shutdown",
"(",
")",
".",
"awaitTermination",
"(",
"5",
",",
"SECONDS",
")",
";",
"}",
")",
";",
"trades",
".",
"mapUsingContextAsync",
"(",
"contextFactory",
",",
"(",
"stub",
",",
"t",
")",
"->",
"{",
"ProductInfoRequest",
"request",
"=",
"ProductInfoRequest",
".",
"newBuilder",
"(",
")",
".",
"setId",
"(",
"t",
".",
"productId",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"return",
"toCompletableFuture",
"(",
"stub",
".",
"productInfo",
"(",
"request",
")",
")",
".",
"thenApply",
"(",
"productReply",
"->",
"tuple2",
"(",
"t",
",",
"productReply",
".",
"getProductName",
"(",
")",
")",
")",
";",
"}",
")",
".",
"mapUsingContextAsync",
"(",
"contextFactory",
",",
"(",
"stub",
",",
"t",
")",
"->",
"{",
"BrokerInfoRequest",
"request",
"=",
"BrokerInfoRequest",
".",
"newBuilder",
"(",
")",
".",
"setId",
"(",
"t",
".",
"f0",
"(",
")",
".",
"brokerId",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"return",
"toCompletableFuture",
"(",
"stub",
".",
"brokerInfo",
"(",
"request",
")",
")",
".",
"thenApply",
"(",
"brokerReply",
"->",
"tuple3",
"(",
"t",
".",
"f0",
"(",
")",
",",
"t",
".",
"f1",
"(",
")",
",",
"brokerReply",
".",
"getBrokerName",
"(",
")",
")",
")",
";",
"}",
")",
".",
"drainTo",
"(",
"Sinks",
".",
"logger",
"(",
")",
")",
";",
"return",
"p",
";",
"}",
"/**\n * Builds a pipeline which enriches the stream using the\n * {@linkplain GeneralStage#hashJoin hash-join} transform.\n * <p>\n * When using the hash join, you don't have to pre-load any maps with the\n * data. The Jet job will pull the data itself from files and store them\n * in internal hashtables. The hashtables are read-only so you can't keep\n * the data up-to-date while the job is running.\n * <p>\n * Like the {@code ReplicatedMap}, the hash-join transform stores all the\n * enriching data at all cluster members. The data is read-only so there\n * are no synchronization overheads, making this the fastest approach to\n * data enrichment.\n * <p>\n * Since the enriching data is stored internally with the running job, once\n * it completes the data is automatically released so there are no memory\n * leak issues to deal with.\n */",
"private",
"static",
"Pipeline",
"enrichUsingHashJoin",
"(",
")",
"{",
"Pipeline",
"p",
"=",
"Pipeline",
".",
"create",
"(",
")",
";",
"StreamStage",
"<",
"Trade",
">",
"trades",
"=",
"p",
".",
"drawFrom",
"(",
"Sources",
".",
"<",
"Object",
",",
"Trade",
">",
"mapJournal",
"(",
"TRADES",
",",
"START_FROM_CURRENT",
")",
")",
".",
"withoutTimestamps",
"(",
")",
".",
"map",
"(",
"entryValue",
"(",
")",
")",
";",
"String",
"resourcesPath",
"=",
"getClasspathDirectory",
"(",
"\"",
".",
"\"",
")",
".",
"toString",
"(",
")",
";",
"BatchSource",
"<",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"Product",
">",
">",
"products",
"=",
"Sources",
".",
"filesBuilder",
"(",
"resourcesPath",
")",
".",
"sharedFileSystem",
"(",
"true",
")",
".",
"glob",
"(",
"\"",
"products.txt",
"\"",
")",
".",
"build",
"(",
"(",
"file",
",",
"line",
")",
"->",
"{",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"String",
">",
"split",
"=",
"splitLine",
"(",
"line",
")",
";",
"return",
"entry",
"(",
"split",
".",
"getKey",
"(",
")",
",",
"new",
"Product",
"(",
"split",
".",
"getKey",
"(",
")",
",",
"split",
".",
"getValue",
"(",
")",
")",
")",
";",
"}",
")",
";",
"BatchSource",
"<",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"Broker",
">",
">",
"brokers",
"=",
"Sources",
".",
"filesBuilder",
"(",
"resourcesPath",
")",
".",
"sharedFileSystem",
"(",
"true",
")",
".",
"glob",
"(",
"\"",
"brokers.txt",
"\"",
")",
".",
"build",
"(",
"(",
"file",
",",
"line",
")",
"->",
"{",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"String",
">",
"split",
"=",
"splitLine",
"(",
"line",
")",
";",
"return",
"entry",
"(",
"split",
".",
"getKey",
"(",
")",
",",
"new",
"Broker",
"(",
"split",
".",
"getKey",
"(",
")",
",",
"split",
".",
"getValue",
"(",
")",
")",
")",
";",
"}",
")",
";",
"BatchStage",
"<",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"Product",
">",
">",
"prodEntries",
"=",
"p",
".",
"drawFrom",
"(",
"products",
")",
";",
"BatchStage",
"<",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"Broker",
">",
">",
"brokEntries",
"=",
"p",
".",
"drawFrom",
"(",
"brokers",
")",
";",
"trades",
".",
"hashJoin2",
"(",
"prodEntries",
",",
"joinMapEntries",
"(",
"Trade",
"::",
"productId",
")",
",",
"brokEntries",
",",
"joinMapEntries",
"(",
"Trade",
"::",
"brokerId",
")",
",",
"Tuple3",
"::",
"tuple3",
")",
".",
"drainTo",
"(",
"Sinks",
".",
"logger",
"(",
")",
")",
";",
"return",
"p",
";",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"System",
".",
"setProperty",
"(",
"\"",
"hazelcast.logging.type",
"\"",
",",
"\"",
"log4j",
"\"",
")",
";",
"JetConfig",
"cfg",
"=",
"new",
"JetConfig",
"(",
")",
";",
"cfg",
".",
"getHazelcastConfig",
"(",
")",
".",
"getMapEventJournalConfig",
"(",
"TRADES",
")",
".",
"setEnabled",
"(",
"true",
")",
";",
"JetInstance",
"jet",
"=",
"Jet",
".",
"newJetInstance",
"(",
"cfg",
")",
";",
"Jet",
".",
"newJetInstance",
"(",
"cfg",
")",
";",
"new",
"Enrichment",
"(",
"jet",
")",
".",
"go",
"(",
")",
";",
"}",
"private",
"void",
"go",
"(",
")",
"throws",
"Exception",
"{",
"EventGenerator",
"eventGenerator",
"=",
"new",
"EventGenerator",
"(",
"jet",
".",
"getMap",
"(",
"TRADES",
")",
")",
";",
"eventGenerator",
".",
"start",
"(",
")",
";",
"try",
"{",
"Pipeline",
"p",
"=",
"enrichUsingIMap",
"(",
")",
";",
"Job",
"job",
"=",
"jet",
".",
"newJob",
"(",
"p",
")",
";",
"eventGenerator",
".",
"generateEventsForFiveSeconds",
"(",
")",
";",
"job",
".",
"cancel",
"(",
")",
";",
"try",
"{",
"job",
".",
"join",
"(",
")",
";",
"}",
"catch",
"(",
"CancellationException",
"ignored",
")",
"{",
"}",
"}",
"finally",
"{",
"eventGenerator",
".",
"shutdown",
"(",
")",
";",
"Jet",
".",
"shutdownAll",
"(",
")",
";",
"}",
"}",
"private",
"static",
"Stream",
"<",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"String",
">",
">",
"readLines",
"(",
"String",
"file",
")",
"{",
"try",
"{",
"return",
"Files",
".",
"lines",
"(",
"Paths",
".",
"get",
"(",
"Enrichment",
".",
"class",
".",
"getResource",
"(",
"file",
")",
".",
"toURI",
"(",
")",
")",
")",
".",
"map",
"(",
"Enrichment",
"::",
"splitLine",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"private",
"static",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"String",
">",
"splitLine",
"(",
"String",
"e",
")",
"{",
"int",
"commaPos",
"=",
"e",
".",
"indexOf",
"(",
"','",
")",
";",
"return",
"entry",
"(",
"Integer",
".",
"valueOf",
"(",
"e",
".",
"substring",
"(",
"0",
",",
"commaPos",
")",
")",
",",
"e",
".",
"substring",
"(",
"commaPos",
"+",
"1",
")",
")",
";",
"}",
"private",
"static",
"<",
"K",
",",
"V",
">",
"void",
"printMap",
"(",
"Map",
"<",
"K",
",",
"V",
">",
"imap",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"imap",
".",
"forEach",
"(",
"(",
"k",
",",
"v",
")",
"->",
"sb",
".",
"append",
"(",
"k",
")",
".",
"append",
"(",
"\"",
"->",
"\"",
")",
".",
"append",
"(",
"v",
")",
".",
"append",
"(",
"'\\n'",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"sb",
")",
";",
"}",
"private",
"static",
"Path",
"getClasspathDirectory",
"(",
"String",
"name",
")",
"{",
"try",
"{",
"return",
"Paths",
".",
"get",
"(",
"Enrichment",
".",
"class",
".",
"getResource",
"(",
"name",
")",
".",
"toURI",
"(",
")",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"/**\n * Adapt a {@link ListenableFuture} to java standard {@link\n * CompletableFuture}, which is used by Jet.\n */",
"private",
"static",
"<",
"T",
">",
"CompletableFuture",
"<",
"T",
">",
"toCompletableFuture",
"(",
"ListenableFuture",
"<",
"T",
">",
"lf",
")",
"{",
"CompletableFuture",
"<",
"T",
">",
"f",
"=",
"new",
"CompletableFuture",
"<",
">",
"(",
")",
";",
"Futures",
".",
"addCallback",
"(",
"lf",
",",
"new",
"FutureCallback",
"<",
"T",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onSuccess",
"(",
"@",
"NullableDecl",
"T",
"result",
")",
"{",
"f",
".",
"complete",
"(",
"result",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"onFailure",
"(",
"Throwable",
"t",
")",
"{",
"f",
".",
"completeExceptionally",
"(",
"t",
")",
";",
"}",
"}",
")",
";",
"return",
"f",
";",
"}",
"}"
] | Demonstrates the usage of the Pipeline API to enrich a data stream. | [
"Demonstrates",
"the",
"usage",
"of",
"the",
"Pipeline",
"API",
"to",
"enrich",
"a",
"data",
"stream",
"."
] | [
"// The stream to be enriched: trades",
"// first enrich the trade by looking up the product from the IMap",
"// target map to lookup",
"// key to lookup in the map",
"// merge the value in the map with the trade",
"// (trade, productName)",
"// (trade, productName, brokerName)",
"// The stream to be enriched: trades",
"// first enrich the trade by looking up the product from the replicated map",
"// target map to lookup",
"// key to lookup in the map",
"// merge the value in the map with the trade",
"// (trade, productName)",
"// (trade, productName, brokerName)",
"// The stream to be enriched: trades",
"// The context factory is the same for both enrichment steps",
"// Enrich the trade by querying the product and broker name from the gRPC service",
"// The stream to be enriched: trades",
"// The enriching streams: products and brokers",
"// Join the trade stream with the product and broker streams",
"// comment out the code to try the appropriate enrichment method",
"// Pipeline p = enrichUsingReplicatedMap();",
"// Pipeline p = enrichUsingAsyncService();",
"// Pipeline p = enrichUsingHashJoin();",
"// note that we don't handle CompletableFuture.cancel()"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9a55194adf7c0c6103c26c74661ad194f1e6625 | Nalhin/Leetcode | src/main/java/com/leetcode/dp/medium/MinimumCostForTickets_983.java | [
"MIT"
] | Java | MinimumCostForTickets_983 | /*
O(n) Runtime: 1 ms, faster than 73.57% of Java online submissions for Minimum Cost For Tickets.
O(n) Memory Usage: 36.7 MB, less than 74.14% of Java online submissions for Minimum Cost For Tickets.
*/ | O(n) Runtime: 1 ms, faster than 73.57% of Java online submissions for Minimum Cost For Tickets.
O(n) Memory Usage: 36.7 MB, less than 74.14% of Java online submissions for Minimum Cost For Tickets. | [
"O",
"(",
"n",
")",
"Runtime",
":",
"1",
"ms",
"faster",
"than",
"73",
".",
"57%",
"of",
"Java",
"online",
"submissions",
"for",
"Minimum",
"Cost",
"For",
"Tickets",
".",
"O",
"(",
"n",
")",
"Memory",
"Usage",
":",
"36",
".",
"7",
"MB",
"less",
"than",
"74",
".",
"14%",
"of",
"Java",
"online",
"submissions",
"for",
"Minimum",
"Cost",
"For",
"Tickets",
"."
] | public class MinimumCostForTickets_983 {
private final int OFFSET = 30;
public int mincostTickets(int[] days, int[] costs) {
int lastDay = days[days.length - 1];
int[] dp = new int[OFFSET + lastDay + 1];
int[] costDays = new int[] {1, 7, 30};
Arrays.fill(dp, Integer.MAX_VALUE);
for (int i = 0; i <= OFFSET; i++) {
dp[i] = 0;
}
int dayCount = 0;
for (int i = OFFSET; i < dp.length; i++) {
if (i == days[dayCount] + OFFSET) {
for (int j = 0; j < costDays.length; j++) {
int prev = i - costDays[j];
dp[i] = Math.min(dp[i], dp[prev] + costs[j]);
}
dayCount++;
} else {
dp[i] = dp[i - 1];
}
}
return dp[OFFSET + lastDay];
}
} | [
"public",
"class",
"MinimumCostForTickets_983",
"{",
"private",
"final",
"int",
"OFFSET",
"=",
"30",
";",
"public",
"int",
"mincostTickets",
"(",
"int",
"[",
"]",
"days",
",",
"int",
"[",
"]",
"costs",
")",
"{",
"int",
"lastDay",
"=",
"days",
"[",
"days",
".",
"length",
"-",
"1",
"]",
";",
"int",
"[",
"]",
"dp",
"=",
"new",
"int",
"[",
"OFFSET",
"+",
"lastDay",
"+",
"1",
"]",
";",
"int",
"[",
"]",
"costDays",
"=",
"new",
"int",
"[",
"]",
"{",
"1",
",",
"7",
",",
"30",
"}",
";",
"Arrays",
".",
"fill",
"(",
"dp",
",",
"Integer",
".",
"MAX_VALUE",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<=",
"OFFSET",
";",
"i",
"++",
")",
"{",
"dp",
"[",
"i",
"]",
"=",
"0",
";",
"}",
"int",
"dayCount",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"OFFSET",
";",
"i",
"<",
"dp",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"==",
"days",
"[",
"dayCount",
"]",
"+",
"OFFSET",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"costDays",
".",
"length",
";",
"j",
"++",
")",
"{",
"int",
"prev",
"=",
"i",
"-",
"costDays",
"[",
"j",
"]",
";",
"dp",
"[",
"i",
"]",
"=",
"Math",
".",
"min",
"(",
"dp",
"[",
"i",
"]",
",",
"dp",
"[",
"prev",
"]",
"+",
"costs",
"[",
"j",
"]",
")",
";",
"}",
"dayCount",
"++",
";",
"}",
"else",
"{",
"dp",
"[",
"i",
"]",
"=",
"dp",
"[",
"i",
"-",
"1",
"]",
";",
"}",
"}",
"return",
"dp",
"[",
"OFFSET",
"+",
"lastDay",
"]",
";",
"}",
"}"
] | O(n) Runtime: 1 ms, faster than 73.57% of Java online submissions for Minimum Cost For Tickets. | [
"O",
"(",
"n",
")",
"Runtime",
":",
"1",
"ms",
"faster",
"than",
"73",
".",
"57%",
"of",
"Java",
"online",
"submissions",
"for",
"Minimum",
"Cost",
"For",
"Tickets",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9a96df56fbc31d3fdafdf92201b731c2e38a738 | aldebaro/easy-speech-recognition | src/edu/ucsd/asr/TIDigitsPathOrganizer.java | [
"MIT"
] | Java | TIDigitsPathOrganizer | /**Helps to interpret a TIDigits path.
* @author Aldebaro Klautau
* @version 1.4 - 02/17/00
*/ | Helps to interpret a TIDigits path.
@author Aldebaro Klautau
@version 1.4 - 02/17/00 | [
"Helps",
"to",
"interpret",
"a",
"TIDigits",
"path",
".",
"@author",
"Aldebaro",
"Klautau",
"@version",
"1",
".",
"4",
"-",
"02",
"/",
"17",
"/",
"00"
] | public class TIDigitsPathOrganizer extends PathOrganizer {
private String m_corpus;
private String m_usage;
private String m_speakerType;
private String m_speakerID;
private String[] m_digits;
private String m_production;
private String m_fileType;
//this needs to be in sync with TableOfLabels
private static final String[][] m_table = {{"z"},{"1"},{"2"},{"3"},
{"4"},{"5"},{"6"},{"7"},{"8"},{"9"},{"o"}};
private static final TableOfLabels m_tableOfLabels = new TableOfLabels(m_table);
private static final TableOfLabels m_tableOfLabelsForTIDIGITS = new TableOfLabels(TableOfLabels.Type.TIDIGITS);
public TIDigitsPathOrganizer(String tidigitsPathOrUniqueFile) {
if (!parseUniqueFileWithCompleteTIDIGITSPath(tidigitsPathOrUniqueFile)) {
parsePath(tidigitsPathOrUniqueFile);
}
}
//should modify but now it's aborting if path is not ok,
//so I can return true always
public boolean isPathOk() {
return true;
}
private void parsePath(String segmentInfo) {
segmentInfo = segmentInfo.toLowerCase();
segmentInfo = FileNamesAndDirectories.replaceBackSlashByForward(segmentInfo);
//System.out.println(segmentInfo);
int nfirstBlankSpaceIndex = segmentInfo.indexOf(" ");
String temporaryPath;
if (nfirstBlankSpaceIndex != -1) {
temporaryPath = segmentInfo.substring(0,nfirstBlankSpaceIndex);
} else {
temporaryPath = segmentInfo;
}
temporaryPath = temporaryPath.toLowerCase();
//System.out.println(temporaryPath);
//i'm not assuming the user is reading from the TIDIGIT CD.
//the user can have created a tree like c:/tidigits/tidigits/tidigits/test/...
//so, find the last occurence of "tidigits" and strip off its prefix:
int nlastTimitIndex = temporaryPath.lastIndexOf("tidigits");
if (nlastTimitIndex == -1) {
System.out.println("Error: couldn't find directory TIDIGIT in the path " + temporaryPath);
System.exit(1);
}
String path = temporaryPath.substring(nlastTimitIndex);
//StringTokenizer stringTokenizer = new StringTokenizer(path,System.getProperties().getProperty("file.separator"));
StringTokenizer stringTokenizer = new StringTokenizer(path,"/");
m_corpus = stringTokenizer.nextToken();
if (!m_corpus.equals("tidigits")) {
generateErrorMessage(m_corpus);
}
m_usage = stringTokenizer.nextToken();
if (! (m_usage.equals("train") | m_usage.equals("test") ) ) {
generateErrorMessage(m_usage);
}
m_speakerType = stringTokenizer.nextToken();
if (! (m_speakerType.equals("man") |
m_speakerType.equals("woman") |
m_speakerType.equals("boy") |
m_speakerType.equals("girl") ) ) {
generateErrorMessage(m_speakerType);
}
m_speakerID = stringTokenizer.nextToken();
if (m_speakerID.length() != 2) {
generateErrorMessage(m_speakerID);
}
String sentenceTemporary = stringTokenizer.nextToken();
m_fileType = sentenceTemporary.substring(sentenceTemporary.length() - 3);
if (! m_fileType.equals("wav") ) {
generateErrorMessage(m_fileType);
}
//take out the file extension
String sentence = sentenceTemporary.substring(0, sentenceTemporary.length() - 4);
//ak - gambiarra visto que nao tenho o TIDIGITS!!!! XXX
m_digits = new String[1];
m_digits[0] = sentence.substring(sentence.length()-1, sentence.length());
if (true) {
return;
}
//fim da gambiarra
m_production = sentence.substring(sentence.length() - 1);
if (! ( m_production.equals("a") |
m_production.equals("b") ) ) {
generateErrorMessage(m_production);
}
String digitString = sentence.substring(0, sentence.length() - 1);
int nnumberOfDigits = digitString.length();
if (( nnumberOfDigits < 1 ) | (nnumberOfDigits > 7) ) {
System.out.println("Invalid (outside [1, 7]) number of digits in " +
segmentInfo + ".");
System.exit(1);
}
m_digits = new String[nnumberOfDigits];
for (int i=0; i<nnumberOfDigits; i++) {
m_digits[i] = (new Character(digitString.charAt(i))).toString();
if (! (m_digits[i].equals("o") |
m_digits[i].equals("z") |
m_digits[i].equals("1") |
m_digits[i].equals("2") |
m_digits[i].equals("3") |
m_digits[i].equals("4") |
m_digits[i].equals("5") |
m_digits[i].equals("6") |
m_digits[i].equals("7") |
m_digits[i].equals("8") |
m_digits[i].equals("9") ) ) {
generateErrorMessage(m_digits[i]);
}
}
m_production = sentence.substring(sentence.length() - 1);
if (! ( m_production.equals("a") |
m_production.equals("b") ) ) {
generateErrorMessage(m_production);
}
}
public String toString() {
//not using m_corpus
String result = m_usage + "/" + m_speakerType + "/" +
m_speakerID + "/";
for (int i=0; i<m_digits.length; i++) {
result += m_digits[i];
}
result += m_production + "." + m_fileType;
return result;
}
public String getUniqueName() {
String result = m_usage + m_speakerType + m_speakerID;
for (int i=0; i<m_digits.length; i++) {
result += m_digits[i];
}
result += m_production + "." + m_fileType;
return result;
}
void generateErrorMessage(String wrongToken) {
System.out.println("Invalid token when parsing TIDigits path:\n Original string: " + wrongToken);
System.out.print(".\n It was parsed as:\n");
System.out.print(m_corpus + " " + m_usage + " " + m_speakerType + " " +
m_speakerID + " ");
if (m_digits != null) {
for (int i=0; i<m_digits.length; i++) {
System.out.print(m_digits[i] + " ");
}
}
System.out.println(m_production + " " + m_fileType);
End.throwError("Error parsing " + wrongToken);
}
public String getCorpus() {
return m_corpus;
}
public String getUsage() {
return m_usage;
}
public String getSpeakerType() {
return m_speakerType;
}
public String getSpeakerID() {
return m_speakerID;
}
public int getNumberOfDigits() {
return m_digits.length;
}
public String[] getDigits() {
return m_digits;
}
/**
* Changes z to "zero", 1 to "one" and so on.
*/
public String[] getDigitsAsInTableOfLabels() {
String[] out = new String[m_digits.length];
for (int i = 0; i < out.length; i++) {
int n = m_tableOfLabels.getEntry(m_digits[i]);
out[i] = m_tableOfLabelsForTIDIGITS.getFirstLabel(n);
}
return out;
}
public String getFirstDigit() {
if (m_digits != null) {
return m_digits[0];
} else {
return null;
}
}
public String getProduction() {
return m_production;
}
public String getFileType() {
return m_fileType;
}
private boolean parseUniqueFileWithCompleteTIDIGITSPath(String originalFileName) {
m_fileType = FileNamesAndDirectories.getExtension(originalFileName);
//want to decode FEA files, so disable below
//if (!m_fileType.equalsIgnoreCase("wav")) {
// return false;
//}
originalFileName = FileNamesAndDirectories.deleteExtension(originalFileName);
//do not want to alter letter's case so keep original name
originalFileName = FileNamesAndDirectories.getFileNameFromPath(originalFileName);
//but convert to lower case a temporary variable to make comparisons easier
String fileName = originalFileName.toLowerCase();
if (fileName.startsWith("test")) {
//m_usage = "test";
m_usage = originalFileName.substring(0,4);
fileName = fileName.substring(4);
originalFileName = originalFileName.substring(4);
} else if (fileName.startsWith("train")) {
//m_usage = "train";
m_usage = originalFileName.substring(0,5);
fileName = fileName.substring(5);
originalFileName = originalFileName.substring(5);
} else {
return false;
}
if (fileName.startsWith("man") || fileName.startsWith("boy")) {
m_speakerType = originalFileName.substring(0,3);
fileName = fileName.substring(3);
originalFileName = originalFileName.substring(3);
} else if (fileName.startsWith("woman")) {
m_speakerType = originalFileName.substring(0,5);
fileName = fileName.substring(5);
originalFileName = originalFileName.substring(5);
} else if (fileName.startsWith("girl")) {
m_speakerType = originalFileName.substring(0,4);
fileName = fileName.substring(4);
originalFileName = originalFileName.substring(4);
} else {
return false;
}
m_speakerID = originalFileName.substring(0,2);
fileName = fileName.substring(2);
originalFileName = originalFileName.substring(2);
//take out last character
m_production = originalFileName.substring(originalFileName.length()-1,originalFileName.length());
fileName = fileName.substring(0, fileName.length()-1);
originalFileName = originalFileName.substring(0, originalFileName.length()-1);
if (fileName.length() < 1) {
return false;
}
m_digits = new String[fileName.length()];
for (int i = 0; i < m_digits.length; i++) {
m_digits[i] = fileName.substring(i,i+1);
if (!m_tableOfLabels.isLabelInTable(m_digits[i])) {
return false;
}
}
m_corpus = "tidigits";
return true;
}
} | [
"public",
"class",
"TIDigitsPathOrganizer",
"extends",
"PathOrganizer",
"{",
"private",
"String",
"m_corpus",
";",
"private",
"String",
"m_usage",
";",
"private",
"String",
"m_speakerType",
";",
"private",
"String",
"m_speakerID",
";",
"private",
"String",
"[",
"]",
"m_digits",
";",
"private",
"String",
"m_production",
";",
"private",
"String",
"m_fileType",
";",
"private",
"static",
"final",
"String",
"[",
"]",
"[",
"]",
"m_table",
"=",
"{",
"{",
"\"",
"z",
"\"",
"}",
",",
"{",
"\"",
"1",
"\"",
"}",
",",
"{",
"\"",
"2",
"\"",
"}",
",",
"{",
"\"",
"3",
"\"",
"}",
",",
"{",
"\"",
"4",
"\"",
"}",
",",
"{",
"\"",
"5",
"\"",
"}",
",",
"{",
"\"",
"6",
"\"",
"}",
",",
"{",
"\"",
"7",
"\"",
"}",
",",
"{",
"\"",
"8",
"\"",
"}",
",",
"{",
"\"",
"9",
"\"",
"}",
",",
"{",
"\"",
"o",
"\"",
"}",
"}",
";",
"private",
"static",
"final",
"TableOfLabels",
"m_tableOfLabels",
"=",
"new",
"TableOfLabels",
"(",
"m_table",
")",
";",
"private",
"static",
"final",
"TableOfLabels",
"m_tableOfLabelsForTIDIGITS",
"=",
"new",
"TableOfLabels",
"(",
"TableOfLabels",
".",
"Type",
".",
"TIDIGITS",
")",
";",
"public",
"TIDigitsPathOrganizer",
"(",
"String",
"tidigitsPathOrUniqueFile",
")",
"{",
"if",
"(",
"!",
"parseUniqueFileWithCompleteTIDIGITSPath",
"(",
"tidigitsPathOrUniqueFile",
")",
")",
"{",
"parsePath",
"(",
"tidigitsPathOrUniqueFile",
")",
";",
"}",
"}",
"public",
"boolean",
"isPathOk",
"(",
")",
"{",
"return",
"true",
";",
"}",
"private",
"void",
"parsePath",
"(",
"String",
"segmentInfo",
")",
"{",
"segmentInfo",
"=",
"segmentInfo",
".",
"toLowerCase",
"(",
")",
";",
"segmentInfo",
"=",
"FileNamesAndDirectories",
".",
"replaceBackSlashByForward",
"(",
"segmentInfo",
")",
";",
"int",
"nfirstBlankSpaceIndex",
"=",
"segmentInfo",
".",
"indexOf",
"(",
"\"",
" ",
"\"",
")",
";",
"String",
"temporaryPath",
";",
"if",
"(",
"nfirstBlankSpaceIndex",
"!=",
"-",
"1",
")",
"{",
"temporaryPath",
"=",
"segmentInfo",
".",
"substring",
"(",
"0",
",",
"nfirstBlankSpaceIndex",
")",
";",
"}",
"else",
"{",
"temporaryPath",
"=",
"segmentInfo",
";",
"}",
"temporaryPath",
"=",
"temporaryPath",
".",
"toLowerCase",
"(",
")",
";",
"int",
"nlastTimitIndex",
"=",
"temporaryPath",
".",
"lastIndexOf",
"(",
"\"",
"tidigits",
"\"",
")",
";",
"if",
"(",
"nlastTimitIndex",
"==",
"-",
"1",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Error: couldn't find directory TIDIGIT in the path ",
"\"",
"+",
"temporaryPath",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"String",
"path",
"=",
"temporaryPath",
".",
"substring",
"(",
"nlastTimitIndex",
")",
";",
"StringTokenizer",
"stringTokenizer",
"=",
"new",
"StringTokenizer",
"(",
"path",
",",
"\"",
"/",
"\"",
")",
";",
"m_corpus",
"=",
"stringTokenizer",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"!",
"m_corpus",
".",
"equals",
"(",
"\"",
"tidigits",
"\"",
")",
")",
"{",
"generateErrorMessage",
"(",
"m_corpus",
")",
";",
"}",
"m_usage",
"=",
"stringTokenizer",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"!",
"(",
"m_usage",
".",
"equals",
"(",
"\"",
"train",
"\"",
")",
"|",
"m_usage",
".",
"equals",
"(",
"\"",
"test",
"\"",
")",
")",
")",
"{",
"generateErrorMessage",
"(",
"m_usage",
")",
";",
"}",
"m_speakerType",
"=",
"stringTokenizer",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"!",
"(",
"m_speakerType",
".",
"equals",
"(",
"\"",
"man",
"\"",
")",
"|",
"m_speakerType",
".",
"equals",
"(",
"\"",
"woman",
"\"",
")",
"|",
"m_speakerType",
".",
"equals",
"(",
"\"",
"boy",
"\"",
")",
"|",
"m_speakerType",
".",
"equals",
"(",
"\"",
"girl",
"\"",
")",
")",
")",
"{",
"generateErrorMessage",
"(",
"m_speakerType",
")",
";",
"}",
"m_speakerID",
"=",
"stringTokenizer",
".",
"nextToken",
"(",
")",
";",
"if",
"(",
"m_speakerID",
".",
"length",
"(",
")",
"!=",
"2",
")",
"{",
"generateErrorMessage",
"(",
"m_speakerID",
")",
";",
"}",
"String",
"sentenceTemporary",
"=",
"stringTokenizer",
".",
"nextToken",
"(",
")",
";",
"m_fileType",
"=",
"sentenceTemporary",
".",
"substring",
"(",
"sentenceTemporary",
".",
"length",
"(",
")",
"-",
"3",
")",
";",
"if",
"(",
"!",
"m_fileType",
".",
"equals",
"(",
"\"",
"wav",
"\"",
")",
")",
"{",
"generateErrorMessage",
"(",
"m_fileType",
")",
";",
"}",
"String",
"sentence",
"=",
"sentenceTemporary",
".",
"substring",
"(",
"0",
",",
"sentenceTemporary",
".",
"length",
"(",
")",
"-",
"4",
")",
";",
"m_digits",
"=",
"new",
"String",
"[",
"1",
"]",
";",
"m_digits",
"[",
"0",
"]",
"=",
"sentence",
".",
"substring",
"(",
"sentence",
".",
"length",
"(",
")",
"-",
"1",
",",
"sentence",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"true",
")",
"{",
"return",
";",
"}",
"m_production",
"=",
"sentence",
".",
"substring",
"(",
"sentence",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"if",
"(",
"!",
"(",
"m_production",
".",
"equals",
"(",
"\"",
"a",
"\"",
")",
"|",
"m_production",
".",
"equals",
"(",
"\"",
"b",
"\"",
")",
")",
")",
"{",
"generateErrorMessage",
"(",
"m_production",
")",
";",
"}",
"String",
"digitString",
"=",
"sentence",
".",
"substring",
"(",
"0",
",",
"sentence",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"int",
"nnumberOfDigits",
"=",
"digitString",
".",
"length",
"(",
")",
";",
"if",
"(",
"(",
"nnumberOfDigits",
"<",
"1",
")",
"|",
"(",
"nnumberOfDigits",
">",
"7",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Invalid (outside [1, 7]) number of digits in ",
"\"",
"+",
"segmentInfo",
"+",
"\"",
".",
"\"",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"m_digits",
"=",
"new",
"String",
"[",
"nnumberOfDigits",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nnumberOfDigits",
";",
"i",
"++",
")",
"{",
"m_digits",
"[",
"i",
"]",
"=",
"(",
"new",
"Character",
"(",
"digitString",
".",
"charAt",
"(",
"i",
")",
")",
")",
".",
"toString",
"(",
")",
";",
"if",
"(",
"!",
"(",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"o",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"z",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"1",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"2",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"3",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"4",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"5",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"6",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"7",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"8",
"\"",
")",
"|",
"m_digits",
"[",
"i",
"]",
".",
"equals",
"(",
"\"",
"9",
"\"",
")",
")",
")",
"{",
"generateErrorMessage",
"(",
"m_digits",
"[",
"i",
"]",
")",
";",
"}",
"}",
"m_production",
"=",
"sentence",
".",
"substring",
"(",
"sentence",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"if",
"(",
"!",
"(",
"m_production",
".",
"equals",
"(",
"\"",
"a",
"\"",
")",
"|",
"m_production",
".",
"equals",
"(",
"\"",
"b",
"\"",
")",
")",
")",
"{",
"generateErrorMessage",
"(",
"m_production",
")",
";",
"}",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"String",
"result",
"=",
"m_usage",
"+",
"\"",
"/",
"\"",
"+",
"m_speakerType",
"+",
"\"",
"/",
"\"",
"+",
"m_speakerID",
"+",
"\"",
"/",
"\"",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m_digits",
".",
"length",
";",
"i",
"++",
")",
"{",
"result",
"+=",
"m_digits",
"[",
"i",
"]",
";",
"}",
"result",
"+=",
"m_production",
"+",
"\"",
".",
"\"",
"+",
"m_fileType",
";",
"return",
"result",
";",
"}",
"public",
"String",
"getUniqueName",
"(",
")",
"{",
"String",
"result",
"=",
"m_usage",
"+",
"m_speakerType",
"+",
"m_speakerID",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m_digits",
".",
"length",
";",
"i",
"++",
")",
"{",
"result",
"+=",
"m_digits",
"[",
"i",
"]",
";",
"}",
"result",
"+=",
"m_production",
"+",
"\"",
".",
"\"",
"+",
"m_fileType",
";",
"return",
"result",
";",
"}",
"void",
"generateErrorMessage",
"(",
"String",
"wrongToken",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Invalid token when parsing TIDigits path:",
"\\n",
" Original string: ",
"\"",
"+",
"wrongToken",
")",
";",
"System",
".",
"out",
".",
"print",
"(",
"\"",
".",
"\\n",
" It was parsed as:",
"\\n",
"\"",
")",
";",
"System",
".",
"out",
".",
"print",
"(",
"m_corpus",
"+",
"\"",
" ",
"\"",
"+",
"m_usage",
"+",
"\"",
" ",
"\"",
"+",
"m_speakerType",
"+",
"\"",
" ",
"\"",
"+",
"m_speakerID",
"+",
"\"",
" ",
"\"",
")",
";",
"if",
"(",
"m_digits",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m_digits",
".",
"length",
";",
"i",
"++",
")",
"{",
"System",
".",
"out",
".",
"print",
"(",
"m_digits",
"[",
"i",
"]",
"+",
"\"",
" ",
"\"",
")",
";",
"}",
"}",
"System",
".",
"out",
".",
"println",
"(",
"m_production",
"+",
"\"",
" ",
"\"",
"+",
"m_fileType",
")",
";",
"End",
".",
"throwError",
"(",
"\"",
"Error parsing ",
"\"",
"+",
"wrongToken",
")",
";",
"}",
"public",
"String",
"getCorpus",
"(",
")",
"{",
"return",
"m_corpus",
";",
"}",
"public",
"String",
"getUsage",
"(",
")",
"{",
"return",
"m_usage",
";",
"}",
"public",
"String",
"getSpeakerType",
"(",
")",
"{",
"return",
"m_speakerType",
";",
"}",
"public",
"String",
"getSpeakerID",
"(",
")",
"{",
"return",
"m_speakerID",
";",
"}",
"public",
"int",
"getNumberOfDigits",
"(",
")",
"{",
"return",
"m_digits",
".",
"length",
";",
"}",
"public",
"String",
"[",
"]",
"getDigits",
"(",
")",
"{",
"return",
"m_digits",
";",
"}",
"/**\n * Changes z to \"zero\", 1 to \"one\" and so on.\n */",
"public",
"String",
"[",
"]",
"getDigitsAsInTableOfLabels",
"(",
")",
"{",
"String",
"[",
"]",
"out",
"=",
"new",
"String",
"[",
"m_digits",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"out",
".",
"length",
";",
"i",
"++",
")",
"{",
"int",
"n",
"=",
"m_tableOfLabels",
".",
"getEntry",
"(",
"m_digits",
"[",
"i",
"]",
")",
";",
"out",
"[",
"i",
"]",
"=",
"m_tableOfLabelsForTIDIGITS",
".",
"getFirstLabel",
"(",
"n",
")",
";",
"}",
"return",
"out",
";",
"}",
"public",
"String",
"getFirstDigit",
"(",
")",
"{",
"if",
"(",
"m_digits",
"!=",
"null",
")",
"{",
"return",
"m_digits",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"public",
"String",
"getProduction",
"(",
")",
"{",
"return",
"m_production",
";",
"}",
"public",
"String",
"getFileType",
"(",
")",
"{",
"return",
"m_fileType",
";",
"}",
"private",
"boolean",
"parseUniqueFileWithCompleteTIDIGITSPath",
"(",
"String",
"originalFileName",
")",
"{",
"m_fileType",
"=",
"FileNamesAndDirectories",
".",
"getExtension",
"(",
"originalFileName",
")",
";",
"originalFileName",
"=",
"FileNamesAndDirectories",
".",
"deleteExtension",
"(",
"originalFileName",
")",
";",
"originalFileName",
"=",
"FileNamesAndDirectories",
".",
"getFileNameFromPath",
"(",
"originalFileName",
")",
";",
"String",
"fileName",
"=",
"originalFileName",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"fileName",
".",
"startsWith",
"(",
"\"",
"test",
"\"",
")",
")",
"{",
"m_usage",
"=",
"originalFileName",
".",
"substring",
"(",
"0",
",",
"4",
")",
";",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"4",
")",
";",
"originalFileName",
"=",
"originalFileName",
".",
"substring",
"(",
"4",
")",
";",
"}",
"else",
"if",
"(",
"fileName",
".",
"startsWith",
"(",
"\"",
"train",
"\"",
")",
")",
"{",
"m_usage",
"=",
"originalFileName",
".",
"substring",
"(",
"0",
",",
"5",
")",
";",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"5",
")",
";",
"originalFileName",
"=",
"originalFileName",
".",
"substring",
"(",
"5",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"fileName",
".",
"startsWith",
"(",
"\"",
"man",
"\"",
")",
"||",
"fileName",
".",
"startsWith",
"(",
"\"",
"boy",
"\"",
")",
")",
"{",
"m_speakerType",
"=",
"originalFileName",
".",
"substring",
"(",
"0",
",",
"3",
")",
";",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"3",
")",
";",
"originalFileName",
"=",
"originalFileName",
".",
"substring",
"(",
"3",
")",
";",
"}",
"else",
"if",
"(",
"fileName",
".",
"startsWith",
"(",
"\"",
"woman",
"\"",
")",
")",
"{",
"m_speakerType",
"=",
"originalFileName",
".",
"substring",
"(",
"0",
",",
"5",
")",
";",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"5",
")",
";",
"originalFileName",
"=",
"originalFileName",
".",
"substring",
"(",
"5",
")",
";",
"}",
"else",
"if",
"(",
"fileName",
".",
"startsWith",
"(",
"\"",
"girl",
"\"",
")",
")",
"{",
"m_speakerType",
"=",
"originalFileName",
".",
"substring",
"(",
"0",
",",
"4",
")",
";",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"4",
")",
";",
"originalFileName",
"=",
"originalFileName",
".",
"substring",
"(",
"4",
")",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"m_speakerID",
"=",
"originalFileName",
".",
"substring",
"(",
"0",
",",
"2",
")",
";",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"2",
")",
";",
"originalFileName",
"=",
"originalFileName",
".",
"substring",
"(",
"2",
")",
";",
"m_production",
"=",
"originalFileName",
".",
"substring",
"(",
"originalFileName",
".",
"length",
"(",
")",
"-",
"1",
",",
"originalFileName",
".",
"length",
"(",
")",
")",
";",
"fileName",
"=",
"fileName",
".",
"substring",
"(",
"0",
",",
"fileName",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"originalFileName",
"=",
"originalFileName",
".",
"substring",
"(",
"0",
",",
"originalFileName",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"if",
"(",
"fileName",
".",
"length",
"(",
")",
"<",
"1",
")",
"{",
"return",
"false",
";",
"}",
"m_digits",
"=",
"new",
"String",
"[",
"fileName",
".",
"length",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"m_digits",
".",
"length",
";",
"i",
"++",
")",
"{",
"m_digits",
"[",
"i",
"]",
"=",
"fileName",
".",
"substring",
"(",
"i",
",",
"i",
"+",
"1",
")",
";",
"if",
"(",
"!",
"m_tableOfLabels",
".",
"isLabelInTable",
"(",
"m_digits",
"[",
"i",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"m_corpus",
"=",
"\"",
"tidigits",
"\"",
";",
"return",
"true",
";",
"}",
"}"
] | Helps to interpret a TIDigits path. | [
"Helps",
"to",
"interpret",
"a",
"TIDigits",
"path",
"."
] | [
"//this needs to be in sync with TableOfLabels",
"//should modify but now it's aborting if path is not ok,",
"//so I can return true always",
"//System.out.println(segmentInfo);",
"//System.out.println(temporaryPath);",
"//i'm not assuming the user is reading from the TIDIGIT CD.",
"//the user can have created a tree like c:/tidigits/tidigits/tidigits/test/...",
"//so, find the last occurence of \"tidigits\" and strip off its prefix:",
"//StringTokenizer stringTokenizer = new StringTokenizer(path,System.getProperties().getProperty(\"file.separator\"));",
"//take out the file extension",
"//ak - gambiarra visto que nao tenho o TIDIGITS!!!! XXX",
"//fim da gambiarra",
"//not using m_corpus",
"//want to decode FEA files, so disable below",
"//if (!m_fileType.equalsIgnoreCase(\"wav\")) {",
"//\treturn false;",
"//}",
"//do not want to alter letter's case so keep original name",
"//but convert to lower case a temporary variable to make comparisons easier",
"//m_usage = \"test\";",
"//m_usage = \"train\";",
"//take out last character"
] | [
{
"param": "PathOrganizer",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "PathOrganizer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9acdfe1318772111cd24289f157ec30c05f80de | ernsyn/yes-cart | payment-modules/payment-module-base/src/test/java/org/yes/cart/payment/impl/PaymentProcessorSurrogate.java | [
"Apache-2.0"
] | Java | PaymentProcessorSurrogate | /**
* This is surrogate for real processor, need to keep common processing logic during different pg tests.
* <p/>
* User: Igor Azarny [email protected]
* Date: 09-May-2011
* Time: 14:12:54
*/ | This is surrogate for real processor, need to keep common processing logic during different pg tests. | [
"This",
"is",
"surrogate",
"for",
"real",
"processor",
"need",
"to",
"keep",
"common",
"processing",
"logic",
"during",
"different",
"pg",
"tests",
"."
] | public class PaymentProcessorSurrogate extends PaymentProcessorImpl {
private static final Logger LOG = LoggerFactory.getLogger(PaymentProcessorSurrogate.class);
private final CustomerOrderPaymentService customerOrderPaymentService;
/**
* Construct payment processor.
*
* @param customerOrderPaymentService generic service to use.
*/
public PaymentProcessorSurrogate(final CustomerOrderPaymentService customerOrderPaymentService) {
super(customerOrderPaymentService);
this.customerOrderPaymentService = customerOrderPaymentService;
}
/**
* Construct payment processor.
*
* @param customerOrderPaymentService generic service to use.
*/
public PaymentProcessorSurrogate(CustomerOrderPaymentService customerOrderPaymentService,
PaymentGatewayInternalForm paymentGateway) {
super(customerOrderPaymentService);
setPaymentGateway(paymentGateway);
this.customerOrderPaymentService = customerOrderPaymentService;
}
/**
* AuthCapture or immediate sale operation will be be used if payment gateway does not support normal flow authorize - delivery - capture.
*
* @param order to authorize payments.
* @param forceSinglePayment flag is true for authCapture operation, when payment gateway not supports
* several payments per order
* @param forceProcessing force processing
* @param params for payment gateway to create template from.
*
* @return status of operation.
*/
@Override
public String authorizeCapture(final CustomerOrder order,
boolean forceSinglePayment,
boolean forceProcessing,
final Map params) {
return super.authorizeCapture(order, forceSinglePayment, forceProcessing, params);
}
/**
* Reverse authorized payments. This can be when one of the payments from whole set is failed.
* Reverse authorization will be applied to authorized payments only
*
* @param orderNum order with some authorized payments
* @param forceProcessing
*/
@Override
public void reverseAuthorizations(final String orderNum, final boolean forceProcessing) {
super.reverseAuthorizations(orderNum, forceProcessing);
}
/**
* {@inheritDoc}
*/
public String shipmentComplete(final CustomerOrder order,
final String orderShipmentNumber,
boolean forceProcessing) {
return shipmentComplete(order, orderShipmentNumber, forceProcessing, BigDecimal.ZERO);
}
/**
* Particular shipment is complete. Funds can be captured.
* In case of multiple delivery and single payment, capture on last delivery.
*
* @param order order
* @param orderShipmentNumber internal shipment number.
* Each order has at least one delivery.
* @param addToPayment amount to add for each payment if it not null
* @return status of operation.
*/
public String shipmentComplete(final CustomerOrder order,
final String orderShipmentNumber,
boolean forceProcessing,
final BigDecimal addToPayment) {
return shipmentComplete(order, orderShipmentNumber, forceProcessing, new HashMap() {{
put("forceManualProcessing", false);
put("forceManualProcessingMessage", null);
put("forceAddToEveryPaymentAmount", addToPayment);
}});
}
/**
* {@inheritDoc}
*/
public String cancelOrder(final CustomerOrder order,
final boolean forceProcessing,
final boolean useRefund) {
return cancelOrder(order, forceProcessing, new HashMap() {{
put("forceManualProcessing", false);
put("forceManualProcessingMessage", null);
put("forceAutoProcessingOperation", useRefund ? PaymentGateway.REFUND : PaymentGateway.VOID_CAPTURE);
}});
}
} | [
"public",
"class",
"PaymentProcessorSurrogate",
"extends",
"PaymentProcessorImpl",
"{",
"private",
"static",
"final",
"Logger",
"LOG",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"PaymentProcessorSurrogate",
".",
"class",
")",
";",
"private",
"final",
"CustomerOrderPaymentService",
"customerOrderPaymentService",
";",
"/**\n * Construct payment processor.\n *\n * @param customerOrderPaymentService generic service to use.\n */",
"public",
"PaymentProcessorSurrogate",
"(",
"final",
"CustomerOrderPaymentService",
"customerOrderPaymentService",
")",
"{",
"super",
"(",
"customerOrderPaymentService",
")",
";",
"this",
".",
"customerOrderPaymentService",
"=",
"customerOrderPaymentService",
";",
"}",
"/**\n * Construct payment processor.\n *\n * @param customerOrderPaymentService generic service to use.\n */",
"public",
"PaymentProcessorSurrogate",
"(",
"CustomerOrderPaymentService",
"customerOrderPaymentService",
",",
"PaymentGatewayInternalForm",
"paymentGateway",
")",
"{",
"super",
"(",
"customerOrderPaymentService",
")",
";",
"setPaymentGateway",
"(",
"paymentGateway",
")",
";",
"this",
".",
"customerOrderPaymentService",
"=",
"customerOrderPaymentService",
";",
"}",
"/**\n * AuthCapture or immediate sale operation will be be used if payment gateway does not support normal flow authorize - delivery - capture.\n *\n * @param order to authorize payments.\n * @param forceSinglePayment flag is true for authCapture operation, when payment gateway not supports\n * several payments per order\n * @param forceProcessing force processing\n * @param params for payment gateway to create template from.\n *\n * @return status of operation.\n */",
"@",
"Override",
"public",
"String",
"authorizeCapture",
"(",
"final",
"CustomerOrder",
"order",
",",
"boolean",
"forceSinglePayment",
",",
"boolean",
"forceProcessing",
",",
"final",
"Map",
"params",
")",
"{",
"return",
"super",
".",
"authorizeCapture",
"(",
"order",
",",
"forceSinglePayment",
",",
"forceProcessing",
",",
"params",
")",
";",
"}",
"/**\n * Reverse authorized payments. This can be when one of the payments from whole set is failed.\n * Reverse authorization will be applied to authorized payments only\n *\n * @param orderNum order with some authorized payments\n * @param forceProcessing\n */",
"@",
"Override",
"public",
"void",
"reverseAuthorizations",
"(",
"final",
"String",
"orderNum",
",",
"final",
"boolean",
"forceProcessing",
")",
"{",
"super",
".",
"reverseAuthorizations",
"(",
"orderNum",
",",
"forceProcessing",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"public",
"String",
"shipmentComplete",
"(",
"final",
"CustomerOrder",
"order",
",",
"final",
"String",
"orderShipmentNumber",
",",
"boolean",
"forceProcessing",
")",
"{",
"return",
"shipmentComplete",
"(",
"order",
",",
"orderShipmentNumber",
",",
"forceProcessing",
",",
"BigDecimal",
".",
"ZERO",
")",
";",
"}",
"/**\n * Particular shipment is complete. Funds can be captured.\n * In case of multiple delivery and single payment, capture on last delivery.\n *\n * @param order order\n * @param orderShipmentNumber internal shipment number.\n * Each order has at least one delivery.\n * @param addToPayment amount to add for each payment if it not null\n * @return status of operation.\n */",
"public",
"String",
"shipmentComplete",
"(",
"final",
"CustomerOrder",
"order",
",",
"final",
"String",
"orderShipmentNumber",
",",
"boolean",
"forceProcessing",
",",
"final",
"BigDecimal",
"addToPayment",
")",
"{",
"return",
"shipmentComplete",
"(",
"order",
",",
"orderShipmentNumber",
",",
"forceProcessing",
",",
"new",
"HashMap",
"(",
")",
"{",
"{",
"put",
"(",
"\"",
"forceManualProcessing",
"\"",
",",
"false",
")",
";",
"put",
"(",
"\"",
"forceManualProcessingMessage",
"\"",
",",
"null",
")",
";",
"put",
"(",
"\"",
"forceAddToEveryPaymentAmount",
"\"",
",",
"addToPayment",
")",
";",
"}",
"}",
")",
";",
"}",
"/**\n * {@inheritDoc}\n */",
"public",
"String",
"cancelOrder",
"(",
"final",
"CustomerOrder",
"order",
",",
"final",
"boolean",
"forceProcessing",
",",
"final",
"boolean",
"useRefund",
")",
"{",
"return",
"cancelOrder",
"(",
"order",
",",
"forceProcessing",
",",
"new",
"HashMap",
"(",
")",
"{",
"{",
"put",
"(",
"\"",
"forceManualProcessing",
"\"",
",",
"false",
")",
";",
"put",
"(",
"\"",
"forceManualProcessingMessage",
"\"",
",",
"null",
")",
";",
"put",
"(",
"\"",
"forceAutoProcessingOperation",
"\"",
",",
"useRefund",
"?",
"PaymentGateway",
".",
"REFUND",
":",
"PaymentGateway",
".",
"VOID_CAPTURE",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] | This is surrogate for real processor, need to keep common processing logic during different pg tests. | [
"This",
"is",
"surrogate",
"for",
"real",
"processor",
"need",
"to",
"keep",
"common",
"processing",
"logic",
"during",
"different",
"pg",
"tests",
"."
] | [] | [
{
"param": "PaymentProcessorImpl",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "PaymentProcessorImpl",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9ad2f800ad50221e77a4ce723b1fb7d2561e938 | emilva/crawl_j | versioneye_maven_crawler/src/main/java/versioneye/mojo/Group1Mojo.java | [
"MIT",
"Unlicense"
] | Java | Group1Mojo | /**
* Crawles all repositories in group1.
*/ | Crawles all repositories in group1. | [
"Crawles",
"all",
"repositories",
"in",
"group1",
"."
] | @Mojo( name = "group1", defaultPhase = LifecyclePhase.PROCESS_SOURCES )
public class Group1Mojo extends AetherMojo {
static final Logger logger = LogManager.getLogger(Group1Mojo.class.getName());
@Parameter( defaultValue = "lamina", property = "groupIdC")
protected String groupIdC;
@Parameter( defaultValue = "lamina", property = "artifactIdC")
protected String artifactIdC;
@Parameter( defaultValue = "0.5.0", property = "versionC")
protected String versionC;
protected ProductService productService;
public void execute() throws MojoExecutionException, MojoFailureException {
try{
super.execute();
productService = (ProductService) context.getBean("productService");
super.execute();
setRepository("CloJars", "http://clojars.org/repo");
logger.info("run for " + groupIdC + ":" + artifactIdC + ":pom:" + versionC);
Artifact artifactInfo = getArtifact( groupIdC + ":" + artifactIdC + ":pom:" + versionC);
ArtifactResult artifactResult = resolveArtifact(artifactInfo);
resolveDependencies(artifactInfo);
parseArtifact(artifactResult.getArtifact(), null);
} catch( Exception exception ){
logger.error(exception);
throw new MojoExecutionException("Oh no! Something went wrong. Get in touch with the VersionEye guys and give them feedback.", exception);
}
}
private void setRepository(String name, String url){
Repository repo = new Repository();
repo.setName(name);
repo.setRepoType("Maven2");
repo.setSrc(url);
mavenPomProcessor.setRepository(repo);
mavenProjectProcessor.setRepository(repo);
}
} | [
"@",
"Mojo",
"(",
"name",
"=",
"\"",
"group1",
"\"",
",",
"defaultPhase",
"=",
"LifecyclePhase",
".",
"PROCESS_SOURCES",
")",
"public",
"class",
"Group1Mojo",
"extends",
"AetherMojo",
"{",
"static",
"final",
"Logger",
"logger",
"=",
"LogManager",
".",
"getLogger",
"(",
"Group1Mojo",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"@",
"Parameter",
"(",
"defaultValue",
"=",
"\"",
"lamina",
"\"",
",",
"property",
"=",
"\"",
"groupIdC",
"\"",
")",
"protected",
"String",
"groupIdC",
";",
"@",
"Parameter",
"(",
"defaultValue",
"=",
"\"",
"lamina",
"\"",
",",
"property",
"=",
"\"",
"artifactIdC",
"\"",
")",
"protected",
"String",
"artifactIdC",
";",
"@",
"Parameter",
"(",
"defaultValue",
"=",
"\"",
"0.5.0",
"\"",
",",
"property",
"=",
"\"",
"versionC",
"\"",
")",
"protected",
"String",
"versionC",
";",
"protected",
"ProductService",
"productService",
";",
"public",
"void",
"execute",
"(",
")",
"throws",
"MojoExecutionException",
",",
"MojoFailureException",
"{",
"try",
"{",
"super",
".",
"execute",
"(",
")",
";",
"productService",
"=",
"(",
"ProductService",
")",
"context",
".",
"getBean",
"(",
"\"",
"productService",
"\"",
")",
";",
"super",
".",
"execute",
"(",
")",
";",
"setRepository",
"(",
"\"",
"CloJars",
"\"",
",",
"\"",
"http://clojars.org/repo",
"\"",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"run for ",
"\"",
"+",
"groupIdC",
"+",
"\"",
":",
"\"",
"+",
"artifactIdC",
"+",
"\"",
":pom:",
"\"",
"+",
"versionC",
")",
";",
"Artifact",
"artifactInfo",
"=",
"getArtifact",
"(",
"groupIdC",
"+",
"\"",
":",
"\"",
"+",
"artifactIdC",
"+",
"\"",
":pom:",
"\"",
"+",
"versionC",
")",
";",
"ArtifactResult",
"artifactResult",
"=",
"resolveArtifact",
"(",
"artifactInfo",
")",
";",
"resolveDependencies",
"(",
"artifactInfo",
")",
";",
"parseArtifact",
"(",
"artifactResult",
".",
"getArtifact",
"(",
")",
",",
"null",
")",
";",
"}",
"catch",
"(",
"Exception",
"exception",
")",
"{",
"logger",
".",
"error",
"(",
"exception",
")",
";",
"throw",
"new",
"MojoExecutionException",
"(",
"\"",
"Oh no! Something went wrong. Get in touch with the VersionEye guys and give them feedback.",
"\"",
",",
"exception",
")",
";",
"}",
"}",
"private",
"void",
"setRepository",
"(",
"String",
"name",
",",
"String",
"url",
")",
"{",
"Repository",
"repo",
"=",
"new",
"Repository",
"(",
")",
";",
"repo",
".",
"setName",
"(",
"name",
")",
";",
"repo",
".",
"setRepoType",
"(",
"\"",
"Maven2",
"\"",
")",
";",
"repo",
".",
"setSrc",
"(",
"url",
")",
";",
"mavenPomProcessor",
".",
"setRepository",
"(",
"repo",
")",
";",
"mavenProjectProcessor",
".",
"setRepository",
"(",
"repo",
")",
";",
"}",
"}"
] | Crawles all repositories in group1. | [
"Crawles",
"all",
"repositories",
"in",
"group1",
"."
] | [] | [
{
"param": "AetherMojo",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AetherMojo",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9afb606758781ce9be75d81979f7b31e5811505 | Orange-OpenSource/matos-profiles | matos-android/src/main/java/android/drm/DrmInfoEvent.java | [
"Apache-2.0"
] | Java | DrmInfoEvent | /*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/ |
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#L% | [
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
".",
"#L%"
] | public class DrmInfoEvent
extends DrmEvent{
// Fields
public static final int TYPE_ALREADY_REGISTERED_BY_ANOTHER_ACCOUNT = 1;
public static final int TYPE_REMOVE_RIGHTS = 2;
public static final int TYPE_RIGHTS_INSTALLED = 3;
public static final int TYPE_WAIT_FOR_RIGHTS = 4;
public static final int TYPE_ACCOUNT_ALREADY_REGISTERED = 5;
public static final int TYPE_RIGHTS_REMOVED = 6;
// Constructors
public DrmInfoEvent(int arg1, int arg2, java.lang.String arg3){
super(0, 0, (java.lang.String) null, (java.util.HashMap) null);
}
public DrmInfoEvent(int arg1, int arg2, java.lang.String arg3, java.util.HashMap<java.lang.String, java.lang.Object> arg4){
super(0, 0, (java.lang.String) null, (java.util.HashMap) null);
}
} | [
"public",
"class",
"DrmInfoEvent",
"extends",
"DrmEvent",
"{",
"public",
"static",
"final",
"int",
"TYPE_ALREADY_REGISTERED_BY_ANOTHER_ACCOUNT",
"=",
"1",
";",
"public",
"static",
"final",
"int",
"TYPE_REMOVE_RIGHTS",
"=",
"2",
";",
"public",
"static",
"final",
"int",
"TYPE_RIGHTS_INSTALLED",
"=",
"3",
";",
"public",
"static",
"final",
"int",
"TYPE_WAIT_FOR_RIGHTS",
"=",
"4",
";",
"public",
"static",
"final",
"int",
"TYPE_ACCOUNT_ALREADY_REGISTERED",
"=",
"5",
";",
"public",
"static",
"final",
"int",
"TYPE_RIGHTS_REMOVED",
"=",
"6",
";",
"public",
"DrmInfoEvent",
"(",
"int",
"arg1",
",",
"int",
"arg2",
",",
"java",
".",
"lang",
".",
"String",
"arg3",
")",
"{",
"super",
"(",
"0",
",",
"0",
",",
"(",
"java",
".",
"lang",
".",
"String",
")",
"null",
",",
"(",
"java",
".",
"util",
".",
"HashMap",
")",
"null",
")",
";",
"}",
"public",
"DrmInfoEvent",
"(",
"int",
"arg1",
",",
"int",
"arg2",
",",
"java",
".",
"lang",
".",
"String",
"arg3",
",",
"java",
".",
"util",
".",
"HashMap",
"<",
"java",
".",
"lang",
".",
"String",
",",
"java",
".",
"lang",
".",
"Object",
">",
"arg4",
")",
"{",
"super",
"(",
"0",
",",
"0",
",",
"(",
"java",
".",
"lang",
".",
"String",
")",
"null",
",",
"(",
"java",
".",
"util",
".",
"HashMap",
")",
"null",
")",
";",
"}",
"}"
] | #%L
Matos
$Id:$
$HeadURL:$
%%
Copyright (C) 2010 - 2014 Orange SA
%%
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. | [
"#%L",
"Matos",
"$Id",
":",
"$",
"$HeadURL",
":",
"$",
"%%",
"Copyright",
"(",
"C",
")",
"2010",
"-",
"2014",
"Orange",
"SA",
"%%",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
"."
] | [
"// Fields",
"// Constructors"
] | [
{
"param": "DrmEvent",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "DrmEvent",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9afde51fa948f7ca00ecb3f22ef7cf6a4690e04 | charques/renthell | event-store-srv/src/main/java/io/renthell/eventstoresrv/web/dto/EventDto.java | [
"MIT"
] | Java | EventDto | /**
* Created by cfhernandez on 17/9/17.
*/ | Created by cfhernandez on 17/9/17. | [
"Created",
"by",
"cfhernandez",
"on",
"17",
"/",
"9",
"/",
"17",
"."
] | @Getter
@Setter
@ToString
public class EventDto {
private String uuid;
private Date creationDate;
private String correlationId;
private String type;
private BaseEvent event;
} | [
"@",
"Getter",
"@",
"Setter",
"@",
"ToString",
"public",
"class",
"EventDto",
"{",
"private",
"String",
"uuid",
";",
"private",
"Date",
"creationDate",
";",
"private",
"String",
"correlationId",
";",
"private",
"String",
"type",
";",
"private",
"BaseEvent",
"event",
";",
"}"
] | Created by cfhernandez on 17/9/17. | [
"Created",
"by",
"cfhernandez",
"on",
"17",
"/",
"9",
"/",
"17",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9b212906c4a5f1367d41e2291aeb18041de1e88 | SolidStateGroup/patientview | root/data/src/main/java/org/patientview/builder/ProcedureBuilder.java | [
"MIT"
] | Java | ProcedureBuilder | /**
* Build Procedure object, suitable for insertion/update into FHIR. Handles update and create, with assumption that
* empty strings means clear existing data, null strings means leave alone and do not update. For Date, clear if null.
*
* Created by [email protected]
* Created on 21/03/2016
*/ | Build Procedure object, suitable for insertion/update into FHIR. Handles update and create, with assumption that
empty strings means clear existing data, null strings means leave alone and do not update. For Date, clear if null.
Created by [email protected]
Created on 21/03/2016 | [
"Build",
"Procedure",
"object",
"suitable",
"for",
"insertion",
"/",
"update",
"into",
"FHIR",
".",
"Handles",
"update",
"and",
"create",
"with",
"assumption",
"that",
"empty",
"strings",
"means",
"clear",
"existing",
"data",
"null",
"strings",
"means",
"leave",
"alone",
"and",
"do",
"not",
"update",
".",
"For",
"Date",
"clear",
"if",
"null",
".",
"Created",
"by",
"jamesr@solidstategroup",
".",
"com",
"Created",
"on",
"21",
"/",
"03",
"/",
"2016"
] | public class ProcedureBuilder {
private Procedure procedure;
private FhirProcedure fhirProcedure;
private ResourceReference patientReference;
private ResourceReference encounterReference;
public ProcedureBuilder(Procedure procedure, FhirProcedure fhirProcedure,
ResourceReference patientReference, ResourceReference encounterReference) {
this.procedure = procedure;
this.fhirProcedure = fhirProcedure;
this.patientReference = patientReference;
this.encounterReference = encounterReference;
}
public Procedure build() {
if (procedure == null) {
procedure = new Procedure();
}
procedure.setSubject(patientReference);
procedure.setEncounter(encounterReference);
// body site
if (fhirProcedure.getBodySite() != null) {
procedure.getBodySite().clear();
if (StringUtils.isNotEmpty(fhirProcedure.getBodySite())) {
CodeableConcept bodySite = new CodeableConcept();
bodySite.setTextSimple(CommonUtils.cleanSql(fhirProcedure.getBodySite()));
procedure.getBodySite().add(bodySite);
}
}
// type
if (fhirProcedure.getType() != null) {
if (StringUtils.isNotEmpty(fhirProcedure.getType())) {
CodeableConcept type = new CodeableConcept();
type.setTextSimple(CommonUtils.cleanSql(fhirProcedure.getType()));
procedure.setType(type);
} else {
procedure.setType(null);
}
}
return procedure;
}
} | [
"public",
"class",
"ProcedureBuilder",
"{",
"private",
"Procedure",
"procedure",
";",
"private",
"FhirProcedure",
"fhirProcedure",
";",
"private",
"ResourceReference",
"patientReference",
";",
"private",
"ResourceReference",
"encounterReference",
";",
"public",
"ProcedureBuilder",
"(",
"Procedure",
"procedure",
",",
"FhirProcedure",
"fhirProcedure",
",",
"ResourceReference",
"patientReference",
",",
"ResourceReference",
"encounterReference",
")",
"{",
"this",
".",
"procedure",
"=",
"procedure",
";",
"this",
".",
"fhirProcedure",
"=",
"fhirProcedure",
";",
"this",
".",
"patientReference",
"=",
"patientReference",
";",
"this",
".",
"encounterReference",
"=",
"encounterReference",
";",
"}",
"public",
"Procedure",
"build",
"(",
")",
"{",
"if",
"(",
"procedure",
"==",
"null",
")",
"{",
"procedure",
"=",
"new",
"Procedure",
"(",
")",
";",
"}",
"procedure",
".",
"setSubject",
"(",
"patientReference",
")",
";",
"procedure",
".",
"setEncounter",
"(",
"encounterReference",
")",
";",
"if",
"(",
"fhirProcedure",
".",
"getBodySite",
"(",
")",
"!=",
"null",
")",
"{",
"procedure",
".",
"getBodySite",
"(",
")",
".",
"clear",
"(",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNotEmpty",
"(",
"fhirProcedure",
".",
"getBodySite",
"(",
")",
")",
")",
"{",
"CodeableConcept",
"bodySite",
"=",
"new",
"CodeableConcept",
"(",
")",
";",
"bodySite",
".",
"setTextSimple",
"(",
"CommonUtils",
".",
"cleanSql",
"(",
"fhirProcedure",
".",
"getBodySite",
"(",
")",
")",
")",
";",
"procedure",
".",
"getBodySite",
"(",
")",
".",
"add",
"(",
"bodySite",
")",
";",
"}",
"}",
"if",
"(",
"fhirProcedure",
".",
"getType",
"(",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isNotEmpty",
"(",
"fhirProcedure",
".",
"getType",
"(",
")",
")",
")",
"{",
"CodeableConcept",
"type",
"=",
"new",
"CodeableConcept",
"(",
")",
";",
"type",
".",
"setTextSimple",
"(",
"CommonUtils",
".",
"cleanSql",
"(",
"fhirProcedure",
".",
"getType",
"(",
")",
")",
")",
";",
"procedure",
".",
"setType",
"(",
"type",
")",
";",
"}",
"else",
"{",
"procedure",
".",
"setType",
"(",
"null",
")",
";",
"}",
"}",
"return",
"procedure",
";",
"}",
"}"
] | Build Procedure object, suitable for insertion/update into FHIR. | [
"Build",
"Procedure",
"object",
"suitable",
"for",
"insertion",
"/",
"update",
"into",
"FHIR",
"."
] | [
"// body site",
"// type"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9b2703eee2b7a2277f879e87d2a2a48c1760267 | soberm/distributed-systems-engineering | VEHICLEdata/src/main/java/at/dse/g14/web/VehicleManufacturerController.java | [
"MIT"
] | Java | VehicleManufacturerController | /**
* @author Lukas Baronyai
* @version ${buildVersion}
* @since 1.0.0
*/ | @author Lukas Baronyai
@version ${buildVersion}
@since 1.0.0 | [
"@author",
"Lukas",
"Baronyai",
"@version",
"$",
"{",
"buildVersion",
"}",
"@since",
"1",
".",
"0",
".",
"0"
] | @RestController
@RequestMapping("/manufacturer")
public class VehicleManufacturerController {
private final VehicleManufacturerService manufacturerService;
@Autowired
public VehicleManufacturerController(final VehicleManufacturerService manufacturerService) {
this.manufacturerService = manufacturerService;
}
@PostMapping
public VehicleManufacturer createVehicleManufacturer(
@RequestBody final VehicleManufacturer manufacturer) throws ServiceException {
return manufacturerService.save(manufacturer);
}
@GetMapping("/{id}")
public VehicleManufacturer getVehicleManufacturer(@PathVariable("id") final String id)
throws ServiceException {
return manufacturerService.findOne(id);
}
@GetMapping
public VehicleManufacturer getVehicleManufacturerByVin(@RequestParam("vin") final String vin)
throws ServiceException {
return manufacturerService.findByVin(vin);
}
@GetMapping("getAll")
public List<VehicleManufacturer> getAllVehicleManufacturers() throws ServiceException {
return manufacturerService.findAll();
}
@PutMapping
public VehicleManufacturer updateVehicleManufacturer(
@RequestBody final VehicleManufacturer manufacturer) throws ServiceException {
return manufacturerService.update(manufacturer);
}
} | [
"@",
"RestController",
"@",
"RequestMapping",
"(",
"\"",
"/manufacturer",
"\"",
")",
"public",
"class",
"VehicleManufacturerController",
"{",
"private",
"final",
"VehicleManufacturerService",
"manufacturerService",
";",
"@",
"Autowired",
"public",
"VehicleManufacturerController",
"(",
"final",
"VehicleManufacturerService",
"manufacturerService",
")",
"{",
"this",
".",
"manufacturerService",
"=",
"manufacturerService",
";",
"}",
"@",
"PostMapping",
"public",
"VehicleManufacturer",
"createVehicleManufacturer",
"(",
"@",
"RequestBody",
"final",
"VehicleManufacturer",
"manufacturer",
")",
"throws",
"ServiceException",
"{",
"return",
"manufacturerService",
".",
"save",
"(",
"manufacturer",
")",
";",
"}",
"@",
"GetMapping",
"(",
"\"",
"/{id}",
"\"",
")",
"public",
"VehicleManufacturer",
"getVehicleManufacturer",
"(",
"@",
"PathVariable",
"(",
"\"",
"id",
"\"",
")",
"final",
"String",
"id",
")",
"throws",
"ServiceException",
"{",
"return",
"manufacturerService",
".",
"findOne",
"(",
"id",
")",
";",
"}",
"@",
"GetMapping",
"public",
"VehicleManufacturer",
"getVehicleManufacturerByVin",
"(",
"@",
"RequestParam",
"(",
"\"",
"vin",
"\"",
")",
"final",
"String",
"vin",
")",
"throws",
"ServiceException",
"{",
"return",
"manufacturerService",
".",
"findByVin",
"(",
"vin",
")",
";",
"}",
"@",
"GetMapping",
"(",
"\"",
"getAll",
"\"",
")",
"public",
"List",
"<",
"VehicleManufacturer",
">",
"getAllVehicleManufacturers",
"(",
")",
"throws",
"ServiceException",
"{",
"return",
"manufacturerService",
".",
"findAll",
"(",
")",
";",
"}",
"@",
"PutMapping",
"public",
"VehicleManufacturer",
"updateVehicleManufacturer",
"(",
"@",
"RequestBody",
"final",
"VehicleManufacturer",
"manufacturer",
")",
"throws",
"ServiceException",
"{",
"return",
"manufacturerService",
".",
"update",
"(",
"manufacturer",
")",
";",
"}",
"}"
] | @author Lukas Baronyai
@version ${buildVersion}
@since 1.0.0 | [
"@author",
"Lukas",
"Baronyai",
"@version",
"$",
"{",
"buildVersion",
"}",
"@since",
"1",
".",
"0",
".",
"0"
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9b283939d62d5399c4c0c4d3aff0888fe5dd258 | hmcts/pip-account-management | src/main/java/uk/gov/hmcts/reform/pip/account/management/errorhandling/GlobalExceptionHandler.java | [
"MIT"
] | Java | GlobalExceptionHandler | /**
* Global exception handler, that captures exceptions thrown by the controllers, and encapsulates
* the logic to handle them and return a standardised response to the user.
*/ | Global exception handler, that captures exceptions thrown by the controllers, and encapsulates
the logic to handle them and return a standardised response to the user. | [
"Global",
"exception",
"handler",
"that",
"captures",
"exceptions",
"thrown",
"by",
"the",
"controllers",
"and",
"encapsulates",
"the",
"logic",
"to",
"handle",
"them",
"and",
"return",
"a",
"standardised",
"response",
"to",
"the",
"user",
"."
] | @ControllerAdvice
public class GlobalExceptionHandler {
/**
* Exception handler that handles Invalid Json exceptions
* and returns a 400 bad request error code.
* @param ex The exception that has been thrown.
* @return The error response, modelled using the ExceptionResponse object.
*/
@ExceptionHandler(JsonMappingException.class)
public ResponseEntity<ExceptionResponse> handle(
JsonMappingException ex) {
ExceptionResponse exceptionResponse = new ExceptionResponse();
exceptionResponse.setMessage(ex.getOriginalMessage());
exceptionResponse.setTimestamp(LocalDateTime.now());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(exceptionResponse);
}
} | [
"@",
"ControllerAdvice",
"public",
"class",
"GlobalExceptionHandler",
"{",
"/**\n * Exception handler that handles Invalid Json exceptions\n * and returns a 400 bad request error code.\n * @param ex The exception that has been thrown.\n * @return The error response, modelled using the ExceptionResponse object.\n */",
"@",
"ExceptionHandler",
"(",
"JsonMappingException",
".",
"class",
")",
"public",
"ResponseEntity",
"<",
"ExceptionResponse",
">",
"handle",
"(",
"JsonMappingException",
"ex",
")",
"{",
"ExceptionResponse",
"exceptionResponse",
"=",
"new",
"ExceptionResponse",
"(",
")",
";",
"exceptionResponse",
".",
"setMessage",
"(",
"ex",
".",
"getOriginalMessage",
"(",
")",
")",
";",
"exceptionResponse",
".",
"setTimestamp",
"(",
"LocalDateTime",
".",
"now",
"(",
")",
")",
";",
"return",
"ResponseEntity",
".",
"status",
"(",
"HttpStatus",
".",
"BAD_REQUEST",
")",
".",
"body",
"(",
"exceptionResponse",
")",
";",
"}",
"}"
] | Global exception handler, that captures exceptions thrown by the controllers, and encapsulates
the logic to handle them and return a standardised response to the user. | [
"Global",
"exception",
"handler",
"that",
"captures",
"exceptions",
"thrown",
"by",
"the",
"controllers",
"and",
"encapsulates",
"the",
"logic",
"to",
"handle",
"them",
"and",
"return",
"a",
"standardised",
"response",
"to",
"the",
"user",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9b6baa27ef535108eb354db5c5f909eebd95dcd | alizinha/MyVerbosityCalculatorAndPrettyTitle | src/nyc/c4q/ac21/APrettyTitle.java | [
"Unlicense"
] | Java | APrettyTitle | /**
* Created by c4q-Allison on 3/20/15.
*/ | Created by c4q-Allison on 3/20/15. | [
"Created",
"by",
"c4q",
"-",
"Allison",
"on",
"3",
"/",
"20",
"/",
"15",
"."
] | public class APrettyTitle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your favorite book title here to be prettified:");
String title = input.nextLine();
System.out.println(Capitalize(title));
System.out.println(PrettyTitle(title));
}
public static String PrettyTitle(String title) {
String prettify = "";
for (int i = 0; i < title.length(); i++) {
if (title.charAt(i) != ' ') {
prettify += "*"; }
else
prettify += " ";
}
return prettify;
}
public static String Capitalize(String title) {
String newTitle ="";
for (int i = 0; i < title.length(); i++) {
if (i == 0)
newTitle = title.substring(i, i+1).toUpperCase();
else if (title.charAt(i - 1) == ' ')
newTitle += title.substring(i, i+1).toUpperCase();
else
newTitle += title.charAt(i);
}
return newTitle;
}
} | [
"public",
"class",
"APrettyTitle",
"{",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"Scanner",
"input",
"=",
"new",
"Scanner",
"(",
"System",
".",
"in",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Enter your favorite book title here to be prettified:",
"\"",
")",
";",
"String",
"title",
"=",
"input",
".",
"nextLine",
"(",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"Capitalize",
"(",
"title",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"PrettyTitle",
"(",
"title",
")",
")",
";",
"}",
"public",
"static",
"String",
"PrettyTitle",
"(",
"String",
"title",
")",
"{",
"String",
"prettify",
"=",
"\"",
"\"",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"title",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"title",
".",
"charAt",
"(",
"i",
")",
"!=",
"' '",
")",
"{",
"prettify",
"+=",
"\"",
"*",
"\"",
";",
"}",
"else",
"prettify",
"+=",
"\"",
" ",
"\"",
";",
"}",
"return",
"prettify",
";",
"}",
"public",
"static",
"String",
"Capitalize",
"(",
"String",
"title",
")",
"{",
"String",
"newTitle",
"=",
"\"",
"\"",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"title",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"==",
"0",
")",
"newTitle",
"=",
"title",
".",
"substring",
"(",
"i",
",",
"i",
"+",
"1",
")",
".",
"toUpperCase",
"(",
")",
";",
"else",
"if",
"(",
"title",
".",
"charAt",
"(",
"i",
"-",
"1",
")",
"==",
"' '",
")",
"newTitle",
"+=",
"title",
".",
"substring",
"(",
"i",
",",
"i",
"+",
"1",
")",
".",
"toUpperCase",
"(",
")",
";",
"else",
"newTitle",
"+=",
"title",
".",
"charAt",
"(",
"i",
")",
";",
"}",
"return",
"newTitle",
";",
"}",
"}"
] | Created by c4q-Allison on 3/20/15. | [
"Created",
"by",
"c4q",
"-",
"Allison",
"on",
"3",
"/",
"20",
"/",
"15",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9b6fa1fa41911f40413a0310fbcc6a9e90ab73b | mporcheron/Co-Curator | app/src/main/java/uk/porcheron/co_curator/util/Image.java | [
"MIT"
] | Java | Image | /**
* Utilities for handling images within the application.
*/ | Utilities for handling images within the application. | [
"Utilities",
"for",
"handling",
"images",
"within",
"the",
"application",
"."
] | public class Image {
private static final String TAG = "CC:Image";
public interface OnCompleteRunner {
void run(String filename);
}
public static void url2File(final String url, final String destination, final int thumbWidth, final int thumbHeight, final Runnable onCompleteRunner, final Runnable onFailedRunner) {
Log.v(TAG, "Download " + url + " and save as " + destination);
// new Thread(new Runnable() {
//
// @Override
// public void run() {
TimelineActivity activity = TimelineActivity.getInstance();
try {
// Download and save the bitmap
ValuePair[] pairs = {new ValuePair("url", url)};
Bitmap bitmap = Image.getBitmapFromURL(url);
if(bitmap == null) {
// bitmap = Image.getBitmapFromURL(Web.GET_URL_SCREENSHOT_STORE + url + ".png", null);
// if(bitmap == null) {
// Log.e(TAG, "Could not get bitmap from " + url);
if(onFailedRunner != null) {
onFailedRunner.run();
}
return;
//}
}
Image.save(activity, bitmap, destination);
// Thumbnail
Image.save(activity, bitmap, destination + "-thumb", thumbWidth, thumbHeight, true);
// On Complete…
if(onCompleteRunner != null) {
activity.runOnUiThread(onCompleteRunner);
}
} catch (IOException e) {
e.printStackTrace();
}
// }
//}).start();
}
public static void file2file(final String source, final String destination, final int thumbWidth, final int thumbHeight, final Runnable onCompleteRunner) {
new Thread(new Runnable() {
@Override
public void run() {
TimelineActivity activity = TimelineActivity.getInstance();
try {
// Import the photo for this phone
Bitmap bitmap = decodeSampledBitmapFromResource(source, Phone.screenWidth, Phone.screenHeight);
Image.save(activity, bitmap, destination);
// Thumbnail
Image.save(activity, bitmap, destination + "-thumb", thumbWidth, thumbHeight, true);
// On Complete…
if(onCompleteRunner != null) {
activity.runOnUiThread(onCompleteRunner);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
/////////////////////////////////////////////////////////////////
// Below here are helper methods; they do NOT handle threading //
/////////////////////////////////////////////////////////////////
public static class ValuePair {
public final String key;
public final String value;
public ValuePair(String key, String value) {
this.key = key;
this.value = value;
}
}
private static Bitmap getBitmapFromURL(String src) {
try {
Log.v(TAG, "Download image from " + src);
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn =
(HttpURLConnection) (new URL(src)).openConnection();
conn.setInstanceFollowRedirects(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
conn.setAllowUserInteraction(false);
conn.connect();
InputStream input = conn.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
Log.e(TAG, "Failed to get image from URL: " + e.getMessage());
e.printStackTrace();
return null;
}
}
private static Bitmap save(Context context, Bitmap bitmap, String filename) throws IOException, IllegalArgumentException {
final FileOutputStream fos = context.openFileOutput(filename + ".png", Context.MODE_PRIVATE);
if (bitmap == null || fos == null || !bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
Log.e(TAG, "Could not save bitmap locally");
}
fos.close();
return bitmap;
}
private static Bitmap save(Context context, Bitmap bitmap, String filename, int finalWidth, int finalHeight, boolean crop) throws IOException, IllegalArgumentException {
if(bitmap == null) {
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Log.v(TAG, "Image is (" + width + "," + height + ")");
float thumbScale = finalWidth / (float) width;
if(height * thumbScale < finalHeight) {
thumbScale = finalHeight / (float) height;
}
int scaleWidth = (int) (width * thumbScale);
int scaleHeight = (int) (height * thumbScale);
Log.v(TAG, "Scaled Image is is (" + scaleWidth + "," + scaleHeight + ")");
bitmap = Bitmap.createScaledBitmap(bitmap, scaleWidth, scaleHeight, true);
if(crop) {
int x = (int) ((scaleWidth / 2f) - (finalWidth / 2f));
int y = (int) ((scaleHeight / 2f) - (finalHeight / 2f));
Log.v(TAG, "Thumbnail Image is is (" + finalWidth + "," + finalHeight + ")");
bitmap = Bitmap.createBitmap(bitmap, x, y, finalWidth, finalHeight);
}
final FileOutputStream fos = context.openFileOutput(filename + ".png", Context.MODE_PRIVATE);
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)) {
Log.e(TAG, "Could not save bitmap locally");
}
fos.close();
return bitmap;
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private static Bitmap decodeSampledBitmapFromResource(String file, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}
} | [
"public",
"class",
"Image",
"{",
"private",
"static",
"final",
"String",
"TAG",
"=",
"\"",
"CC:Image",
"\"",
";",
"public",
"interface",
"OnCompleteRunner",
"{",
"void",
"run",
"(",
"String",
"filename",
")",
";",
"}",
"public",
"static",
"void",
"url2File",
"(",
"final",
"String",
"url",
",",
"final",
"String",
"destination",
",",
"final",
"int",
"thumbWidth",
",",
"final",
"int",
"thumbHeight",
",",
"final",
"Runnable",
"onCompleteRunner",
",",
"final",
"Runnable",
"onFailedRunner",
")",
"{",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"",
"Download ",
"\"",
"+",
"url",
"+",
"\"",
" and save as ",
"\"",
"+",
"destination",
")",
";",
"TimelineActivity",
"activity",
"=",
"TimelineActivity",
".",
"getInstance",
"(",
")",
";",
"try",
"{",
"ValuePair",
"[",
"]",
"pairs",
"=",
"{",
"new",
"ValuePair",
"(",
"\"",
"url",
"\"",
",",
"url",
")",
"}",
";",
"Bitmap",
"bitmap",
"=",
"Image",
".",
"getBitmapFromURL",
"(",
"url",
")",
";",
"if",
"(",
"bitmap",
"==",
"null",
")",
"{",
"if",
"(",
"onFailedRunner",
"!=",
"null",
")",
"{",
"onFailedRunner",
".",
"run",
"(",
")",
";",
"}",
"return",
";",
"}",
"Image",
".",
"save",
"(",
"activity",
",",
"bitmap",
",",
"destination",
")",
";",
"Image",
".",
"save",
"(",
"activity",
",",
"bitmap",
",",
"destination",
"+",
"\"",
"-thumb",
"\"",
",",
"thumbWidth",
",",
"thumbHeight",
",",
"true",
")",
";",
"if",
"(",
"onCompleteRunner",
"!=",
"null",
")",
"{",
"activity",
".",
"runOnUiThread",
"(",
"onCompleteRunner",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"public",
"static",
"void",
"file2file",
"(",
"final",
"String",
"source",
",",
"final",
"String",
"destination",
",",
"final",
"int",
"thumbWidth",
",",
"final",
"int",
"thumbHeight",
",",
"final",
"Runnable",
"onCompleteRunner",
")",
"{",
"new",
"Thread",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"TimelineActivity",
"activity",
"=",
"TimelineActivity",
".",
"getInstance",
"(",
")",
";",
"try",
"{",
"Bitmap",
"bitmap",
"=",
"decodeSampledBitmapFromResource",
"(",
"source",
",",
"Phone",
".",
"screenWidth",
",",
"Phone",
".",
"screenHeight",
")",
";",
"Image",
".",
"save",
"(",
"activity",
",",
"bitmap",
",",
"destination",
")",
";",
"Image",
".",
"save",
"(",
"activity",
",",
"bitmap",
",",
"destination",
"+",
"\"",
"-thumb",
"\"",
",",
"thumbWidth",
",",
"thumbHeight",
",",
"true",
")",
";",
"if",
"(",
"onCompleteRunner",
"!=",
"null",
")",
"{",
"activity",
".",
"runOnUiThread",
"(",
"onCompleteRunner",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}",
")",
".",
"start",
"(",
")",
";",
"}",
"public",
"static",
"class",
"ValuePair",
"{",
"public",
"final",
"String",
"key",
";",
"public",
"final",
"String",
"value",
";",
"public",
"ValuePair",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"this",
".",
"key",
"=",
"key",
";",
"this",
".",
"value",
"=",
"value",
";",
"}",
"}",
"private",
"static",
"Bitmap",
"getBitmapFromURL",
"(",
"String",
"src",
")",
"{",
"try",
"{",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"",
"Download image from ",
"\"",
"+",
"src",
")",
";",
"System",
".",
"setProperty",
"(",
"\"",
"http.keepAlive",
"\"",
",",
"\"",
"false",
"\"",
")",
";",
"HttpURLConnection",
"conn",
"=",
"(",
"HttpURLConnection",
")",
"(",
"new",
"URL",
"(",
"src",
")",
")",
".",
"openConnection",
"(",
")",
";",
"conn",
".",
"setInstanceFollowRedirects",
"(",
"true",
")",
";",
"conn",
".",
"setDoInput",
"(",
"true",
")",
";",
"conn",
".",
"setUseCaches",
"(",
"false",
")",
";",
"conn",
".",
"setUseCaches",
"(",
"false",
")",
";",
"conn",
".",
"setDefaultUseCaches",
"(",
"false",
")",
";",
"conn",
".",
"setAllowUserInteraction",
"(",
"false",
")",
";",
"conn",
".",
"connect",
"(",
")",
";",
"InputStream",
"input",
"=",
"conn",
".",
"getInputStream",
"(",
")",
";",
"return",
"BitmapFactory",
".",
"decodeStream",
"(",
"input",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"Failed to get image from URL: ",
"\"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
";",
"return",
"null",
";",
"}",
"}",
"private",
"static",
"Bitmap",
"save",
"(",
"Context",
"context",
",",
"Bitmap",
"bitmap",
",",
"String",
"filename",
")",
"throws",
"IOException",
",",
"IllegalArgumentException",
"{",
"final",
"FileOutputStream",
"fos",
"=",
"context",
".",
"openFileOutput",
"(",
"filename",
"+",
"\"",
".png",
"\"",
",",
"Context",
".",
"MODE_PRIVATE",
")",
";",
"if",
"(",
"bitmap",
"==",
"null",
"||",
"fos",
"==",
"null",
"||",
"!",
"bitmap",
".",
"compress",
"(",
"Bitmap",
".",
"CompressFormat",
".",
"PNG",
",",
"100",
",",
"fos",
")",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"Could not save bitmap locally",
"\"",
")",
";",
"}",
"fos",
".",
"close",
"(",
")",
";",
"return",
"bitmap",
";",
"}",
"private",
"static",
"Bitmap",
"save",
"(",
"Context",
"context",
",",
"Bitmap",
"bitmap",
",",
"String",
"filename",
",",
"int",
"finalWidth",
",",
"int",
"finalHeight",
",",
"boolean",
"crop",
")",
"throws",
"IOException",
",",
"IllegalArgumentException",
"{",
"if",
"(",
"bitmap",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"int",
"width",
"=",
"bitmap",
".",
"getWidth",
"(",
")",
";",
"int",
"height",
"=",
"bitmap",
".",
"getHeight",
"(",
")",
";",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"",
"Image is (",
"\"",
"+",
"width",
"+",
"\"",
",",
"\"",
"+",
"height",
"+",
"\"",
")",
"\"",
")",
";",
"float",
"thumbScale",
"=",
"finalWidth",
"/",
"(",
"float",
")",
"width",
";",
"if",
"(",
"height",
"*",
"thumbScale",
"<",
"finalHeight",
")",
"{",
"thumbScale",
"=",
"finalHeight",
"/",
"(",
"float",
")",
"height",
";",
"}",
"int",
"scaleWidth",
"=",
"(",
"int",
")",
"(",
"width",
"*",
"thumbScale",
")",
";",
"int",
"scaleHeight",
"=",
"(",
"int",
")",
"(",
"height",
"*",
"thumbScale",
")",
";",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"",
"Scaled Image is is (",
"\"",
"+",
"scaleWidth",
"+",
"\"",
",",
"\"",
"+",
"scaleHeight",
"+",
"\"",
")",
"\"",
")",
";",
"bitmap",
"=",
"Bitmap",
".",
"createScaledBitmap",
"(",
"bitmap",
",",
"scaleWidth",
",",
"scaleHeight",
",",
"true",
")",
";",
"if",
"(",
"crop",
")",
"{",
"int",
"x",
"=",
"(",
"int",
")",
"(",
"(",
"scaleWidth",
"/",
"2f",
")",
"-",
"(",
"finalWidth",
"/",
"2f",
")",
")",
";",
"int",
"y",
"=",
"(",
"int",
")",
"(",
"(",
"scaleHeight",
"/",
"2f",
")",
"-",
"(",
"finalHeight",
"/",
"2f",
")",
")",
";",
"Log",
".",
"v",
"(",
"TAG",
",",
"\"",
"Thumbnail Image is is (",
"\"",
"+",
"finalWidth",
"+",
"\"",
",",
"\"",
"+",
"finalHeight",
"+",
"\"",
")",
"\"",
")",
";",
"bitmap",
"=",
"Bitmap",
".",
"createBitmap",
"(",
"bitmap",
",",
"x",
",",
"y",
",",
"finalWidth",
",",
"finalHeight",
")",
";",
"}",
"final",
"FileOutputStream",
"fos",
"=",
"context",
".",
"openFileOutput",
"(",
"filename",
"+",
"\"",
".png",
"\"",
",",
"Context",
".",
"MODE_PRIVATE",
")",
";",
"if",
"(",
"!",
"bitmap",
".",
"compress",
"(",
"Bitmap",
".",
"CompressFormat",
".",
"PNG",
",",
"100",
",",
"fos",
")",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"Could not save bitmap locally",
"\"",
")",
";",
"}",
"fos",
".",
"close",
"(",
")",
";",
"return",
"bitmap",
";",
"}",
"private",
"static",
"int",
"calculateInSampleSize",
"(",
"BitmapFactory",
".",
"Options",
"options",
",",
"int",
"reqWidth",
",",
"int",
"reqHeight",
")",
"{",
"final",
"int",
"height",
"=",
"options",
".",
"outHeight",
";",
"final",
"int",
"width",
"=",
"options",
".",
"outWidth",
";",
"int",
"inSampleSize",
"=",
"1",
";",
"if",
"(",
"height",
">",
"reqHeight",
"||",
"width",
">",
"reqWidth",
")",
"{",
"final",
"int",
"halfHeight",
"=",
"height",
"/",
"2",
";",
"final",
"int",
"halfWidth",
"=",
"width",
"/",
"2",
";",
"while",
"(",
"(",
"halfHeight",
"/",
"inSampleSize",
")",
">",
"reqHeight",
"&&",
"(",
"halfWidth",
"/",
"inSampleSize",
")",
">",
"reqWidth",
")",
"{",
"inSampleSize",
"*=",
"2",
";",
"}",
"}",
"return",
"inSampleSize",
";",
"}",
"private",
"static",
"Bitmap",
"decodeSampledBitmapFromResource",
"(",
"String",
"file",
",",
"int",
"reqWidth",
",",
"int",
"reqHeight",
")",
"{",
"final",
"BitmapFactory",
".",
"Options",
"options",
"=",
"new",
"BitmapFactory",
".",
"Options",
"(",
")",
";",
"options",
".",
"inJustDecodeBounds",
"=",
"true",
";",
"BitmapFactory",
".",
"decodeFile",
"(",
"file",
",",
"options",
")",
";",
"options",
".",
"inSampleSize",
"=",
"calculateInSampleSize",
"(",
"options",
",",
"reqWidth",
",",
"reqHeight",
")",
";",
"options",
".",
"inJustDecodeBounds",
"=",
"false",
";",
"return",
"BitmapFactory",
".",
"decodeFile",
"(",
"file",
",",
"options",
")",
";",
"}",
"}"
] | Utilities for handling images within the application. | [
"Utilities",
"for",
"handling",
"images",
"within",
"the",
"application",
"."
] | [
"// new Thread(new Runnable() {",
"//",
"// @Override",
"// public void run() {",
"// Download and save the bitmap",
"// bitmap = Image.getBitmapFromURL(Web.GET_URL_SCREENSHOT_STORE + url + \".png\", null);",
"// if(bitmap == null) {",
"// Log.e(TAG, \"Could not get bitmap from \" + url);",
"//}",
"// Thumbnail",
"// On Complete…",
"// }",
"//}).start();",
"// Import the photo for this phone",
"// Thumbnail",
"// On Complete…",
"/////////////////////////////////////////////////////////////////",
"// Below here are helper methods; they do NOT handle threading //",
"/////////////////////////////////////////////////////////////////",
"// Raw height and width of image",
"// Calculate the largest inSampleSize value that is a power of 2 and keeps both",
"// height and width larger than the requested height and width.",
"// First decode with inJustDecodeBounds=true to check dimensions",
"// Calculate inSampleSize",
"// Decode bitmap with inSampleSize set"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9b707be8f01e9339ec8e13693982cd72c7423bf | jankeromnes/Terasology | engine/src/main/java/org/terasology/rendering/nui/editor/layers/NUIEditorSettingsScreen.java | [
"Apache-2.0"
] | Java | NUIEditorSettingsScreen | /**
* The screen to modify NUI screen/skin editor settings.
*/ | The screen to modify NUI screen/skin editor settings. | [
"The",
"screen",
"to",
"modify",
"NUI",
"screen",
"/",
"skin",
"editor",
"settings",
"."
] | @SuppressWarnings("unchecked")
public class NUIEditorSettingsScreen extends CoreScreenLayer {
public static final ResourceUrn ASSET_URI = new ResourceUrn("engine:nuiEditorSettingsScreen");
@In
private Config config;
@In
private TranslationSystem translationSystem;
private UIDropdownScrollable<Locale> alternativeLocale;
@Override
public void initialise() {
WidgetUtil.tryBindCheckbox(this, "disableAutosave", BindHelper.bindBeanProperty("disableAutosave", config.getNuiEditor(), Boolean.TYPE));
WidgetUtil.tryBindCheckbox(this, "disableIcons", BindHelper.bindBeanProperty("disableIcons", config.getNuiEditor(), Boolean.TYPE));
WidgetUtil.trySubscribe(this, "close", button -> getManager().closeScreen(ASSET_URI));
alternativeLocale = find("alternativeLocale", UIDropdownScrollable.class);
if (alternativeLocale != null) {
// Build the list of available locales and set the dropdown's options to them.
TranslationProject menuProject = translationSystem.getProject(new SimpleUri("engine:menu"));
List<Locale> locales = new ArrayList<>(menuProject.getAvailableLocales());
Collections.sort(locales, ((Object o1, Object o2) -> (o1.toString().compareTo(o2.toString()))));
alternativeLocale.setOptions(Lists.newArrayList(locales));
alternativeLocale.setVisibleOptions(5);
alternativeLocale.setOptionRenderer(new LocaleRenderer(translationSystem));
// If an alternative locale has been previously selected, select it; otherwise select the system locale.
if (config.getNuiEditor().getAlternativeLocale() != null) {
alternativeLocale.setSelection(config.getNuiEditor().getAlternativeLocale());
} else {
alternativeLocale.setSelection(config.getSystem().getLocale());
}
}
}
@Override
public void onClosed() {
if (!alternativeLocale.getSelection().equals(config.getNuiEditor().getAlternativeLocale())) {
config.getNuiEditor().setAlternativeLocale(alternativeLocale.getSelection());
}
if (getManager().isOpen(NUIEditorScreen.ASSET_URI)) {
((NUIEditorScreen) getManager().getScreen(NUIEditorScreen.ASSET_URI)).updateConfig();
}
if (getManager().isOpen(NUISkinEditorScreen.ASSET_URI)) {
((NUISkinEditorScreen) getManager().getScreen(NUISkinEditorScreen.ASSET_URI)).updateConfig();
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"",
"unchecked",
"\"",
")",
"public",
"class",
"NUIEditorSettingsScreen",
"extends",
"CoreScreenLayer",
"{",
"public",
"static",
"final",
"ResourceUrn",
"ASSET_URI",
"=",
"new",
"ResourceUrn",
"(",
"\"",
"engine:nuiEditorSettingsScreen",
"\"",
")",
";",
"@",
"In",
"private",
"Config",
"config",
";",
"@",
"In",
"private",
"TranslationSystem",
"translationSystem",
";",
"private",
"UIDropdownScrollable",
"<",
"Locale",
">",
"alternativeLocale",
";",
"@",
"Override",
"public",
"void",
"initialise",
"(",
")",
"{",
"WidgetUtil",
".",
"tryBindCheckbox",
"(",
"this",
",",
"\"",
"disableAutosave",
"\"",
",",
"BindHelper",
".",
"bindBeanProperty",
"(",
"\"",
"disableAutosave",
"\"",
",",
"config",
".",
"getNuiEditor",
"(",
")",
",",
"Boolean",
".",
"TYPE",
")",
")",
";",
"WidgetUtil",
".",
"tryBindCheckbox",
"(",
"this",
",",
"\"",
"disableIcons",
"\"",
",",
"BindHelper",
".",
"bindBeanProperty",
"(",
"\"",
"disableIcons",
"\"",
",",
"config",
".",
"getNuiEditor",
"(",
")",
",",
"Boolean",
".",
"TYPE",
")",
")",
";",
"WidgetUtil",
".",
"trySubscribe",
"(",
"this",
",",
"\"",
"close",
"\"",
",",
"button",
"->",
"getManager",
"(",
")",
".",
"closeScreen",
"(",
"ASSET_URI",
")",
")",
";",
"alternativeLocale",
"=",
"find",
"(",
"\"",
"alternativeLocale",
"\"",
",",
"UIDropdownScrollable",
".",
"class",
")",
";",
"if",
"(",
"alternativeLocale",
"!=",
"null",
")",
"{",
"TranslationProject",
"menuProject",
"=",
"translationSystem",
".",
"getProject",
"(",
"new",
"SimpleUri",
"(",
"\"",
"engine:menu",
"\"",
")",
")",
";",
"List",
"<",
"Locale",
">",
"locales",
"=",
"new",
"ArrayList",
"<",
">",
"(",
"menuProject",
".",
"getAvailableLocales",
"(",
")",
")",
";",
"Collections",
".",
"sort",
"(",
"locales",
",",
"(",
"(",
"Object",
"o1",
",",
"Object",
"o2",
")",
"->",
"(",
"o1",
".",
"toString",
"(",
")",
".",
"compareTo",
"(",
"o2",
".",
"toString",
"(",
")",
")",
")",
")",
")",
";",
"alternativeLocale",
".",
"setOptions",
"(",
"Lists",
".",
"newArrayList",
"(",
"locales",
")",
")",
";",
"alternativeLocale",
".",
"setVisibleOptions",
"(",
"5",
")",
";",
"alternativeLocale",
".",
"setOptionRenderer",
"(",
"new",
"LocaleRenderer",
"(",
"translationSystem",
")",
")",
";",
"if",
"(",
"config",
".",
"getNuiEditor",
"(",
")",
".",
"getAlternativeLocale",
"(",
")",
"!=",
"null",
")",
"{",
"alternativeLocale",
".",
"setSelection",
"(",
"config",
".",
"getNuiEditor",
"(",
")",
".",
"getAlternativeLocale",
"(",
")",
")",
";",
"}",
"else",
"{",
"alternativeLocale",
".",
"setSelection",
"(",
"config",
".",
"getSystem",
"(",
")",
".",
"getLocale",
"(",
")",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"void",
"onClosed",
"(",
")",
"{",
"if",
"(",
"!",
"alternativeLocale",
".",
"getSelection",
"(",
")",
".",
"equals",
"(",
"config",
".",
"getNuiEditor",
"(",
")",
".",
"getAlternativeLocale",
"(",
")",
")",
")",
"{",
"config",
".",
"getNuiEditor",
"(",
")",
".",
"setAlternativeLocale",
"(",
"alternativeLocale",
".",
"getSelection",
"(",
")",
")",
";",
"}",
"if",
"(",
"getManager",
"(",
")",
".",
"isOpen",
"(",
"NUIEditorScreen",
".",
"ASSET_URI",
")",
")",
"{",
"(",
"(",
"NUIEditorScreen",
")",
"getManager",
"(",
")",
".",
"getScreen",
"(",
"NUIEditorScreen",
".",
"ASSET_URI",
")",
")",
".",
"updateConfig",
"(",
")",
";",
"}",
"if",
"(",
"getManager",
"(",
")",
".",
"isOpen",
"(",
"NUISkinEditorScreen",
".",
"ASSET_URI",
")",
")",
"{",
"(",
"(",
"NUISkinEditorScreen",
")",
"getManager",
"(",
")",
".",
"getScreen",
"(",
"NUISkinEditorScreen",
".",
"ASSET_URI",
")",
")",
".",
"updateConfig",
"(",
")",
";",
"}",
"}",
"}"
] | The screen to modify NUI screen/skin editor settings. | [
"The",
"screen",
"to",
"modify",
"NUI",
"screen",
"/",
"skin",
"editor",
"settings",
"."
] | [
"// Build the list of available locales and set the dropdown's options to them.",
"// If an alternative locale has been previously selected, select it; otherwise select the system locale."
] | [
{
"param": "CoreScreenLayer",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "CoreScreenLayer",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9b76a21b628b1507ba8742bd56e71d17f550ae8 | chtyim/weave | core/src/main/java/com/continuuity/weave/internal/json/WeaveSpecificationAdapter.java | [
"Apache-2.0"
] | Java | WeaveSpecificationTypeAdapterFactory | // This is to get around gson ignoring of inner class | This is to get around gson ignoring of inner class | [
"This",
"is",
"to",
"get",
"around",
"gson",
"ignoring",
"of",
"inner",
"class"
] | private static final class WeaveSpecificationTypeAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<?> rawType = type.getRawType();
if (!Map.class.isAssignableFrom(rawType)) {
return null;
}
Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
TypeToken<?> keyType = TypeToken.get(typeArgs[0]);
TypeToken<?> valueType = TypeToken.get(typeArgs[1]);
if (keyType.getRawType() != String.class) {
return null;
}
return (TypeAdapter<T>) mapAdapter(gson, valueType);
}
private <V> TypeAdapter<Map<String, V>> mapAdapter(Gson gson, TypeToken<V> valueType) {
final TypeAdapter<V> valueAdapter = gson.getAdapter(valueType);
return new TypeAdapter<Map<String, V>>() {
@Override
public void write(JsonWriter writer, Map<String, V> map) throws IOException {
if (map == null) {
writer.nullValue();
return;
}
writer.beginObject();
for (Map.Entry<String, V> entry : map.entrySet()) {
writer.name(entry.getKey());
valueAdapter.write(writer, entry.getValue());
}
writer.endObject();
}
@Override
public Map<String, V> read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
if (reader.peek() != JsonToken.BEGIN_OBJECT) {
return null;
}
Map<String, V> map = Maps.newHashMap();
reader.beginObject();
while (reader.peek() != JsonToken.END_OBJECT) {
map.put(reader.nextName(), valueAdapter.read(reader));
}
reader.endObject();
return map;
}
};
}
} | [
"private",
"static",
"final",
"class",
"WeaveSpecificationTypeAdapterFactory",
"implements",
"TypeAdapterFactory",
"{",
"@",
"Override",
"public",
"<",
"T",
">",
"TypeAdapter",
"<",
"T",
">",
"create",
"(",
"Gson",
"gson",
",",
"TypeToken",
"<",
"T",
">",
"type",
")",
"{",
"Class",
"<",
"?",
">",
"rawType",
"=",
"type",
".",
"getRawType",
"(",
")",
";",
"if",
"(",
"!",
"Map",
".",
"class",
".",
"isAssignableFrom",
"(",
"rawType",
")",
")",
"{",
"return",
"null",
";",
"}",
"Type",
"[",
"]",
"typeArgs",
"=",
"(",
"(",
"ParameterizedType",
")",
"type",
".",
"getType",
"(",
")",
")",
".",
"getActualTypeArguments",
"(",
")",
";",
"TypeToken",
"<",
"?",
">",
"keyType",
"=",
"TypeToken",
".",
"get",
"(",
"typeArgs",
"[",
"0",
"]",
")",
";",
"TypeToken",
"<",
"?",
">",
"valueType",
"=",
"TypeToken",
".",
"get",
"(",
"typeArgs",
"[",
"1",
"]",
")",
";",
"if",
"(",
"keyType",
".",
"getRawType",
"(",
")",
"!=",
"String",
".",
"class",
")",
"{",
"return",
"null",
";",
"}",
"return",
"(",
"TypeAdapter",
"<",
"T",
">",
")",
"mapAdapter",
"(",
"gson",
",",
"valueType",
")",
";",
"}",
"private",
"<",
"V",
">",
"TypeAdapter",
"<",
"Map",
"<",
"String",
",",
"V",
">",
">",
"mapAdapter",
"(",
"Gson",
"gson",
",",
"TypeToken",
"<",
"V",
">",
"valueType",
")",
"{",
"final",
"TypeAdapter",
"<",
"V",
">",
"valueAdapter",
"=",
"gson",
".",
"getAdapter",
"(",
"valueType",
")",
";",
"return",
"new",
"TypeAdapter",
"<",
"Map",
"<",
"String",
",",
"V",
">",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"write",
"(",
"JsonWriter",
"writer",
",",
"Map",
"<",
"String",
",",
"V",
">",
"map",
")",
"throws",
"IOException",
"{",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"writer",
".",
"nullValue",
"(",
")",
";",
"return",
";",
"}",
"writer",
".",
"beginObject",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"V",
">",
"entry",
":",
"map",
".",
"entrySet",
"(",
")",
")",
"{",
"writer",
".",
"name",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"valueAdapter",
".",
"write",
"(",
"writer",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"writer",
".",
"endObject",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Map",
"<",
"String",
",",
"V",
">",
"read",
"(",
"JsonReader",
"reader",
")",
"throws",
"IOException",
"{",
"if",
"(",
"reader",
".",
"peek",
"(",
")",
"==",
"JsonToken",
".",
"NULL",
")",
"{",
"reader",
".",
"nextNull",
"(",
")",
";",
"return",
"null",
";",
"}",
"if",
"(",
"reader",
".",
"peek",
"(",
")",
"!=",
"JsonToken",
".",
"BEGIN_OBJECT",
")",
"{",
"return",
"null",
";",
"}",
"Map",
"<",
"String",
",",
"V",
">",
"map",
"=",
"Maps",
".",
"newHashMap",
"(",
")",
";",
"reader",
".",
"beginObject",
"(",
")",
";",
"while",
"(",
"reader",
".",
"peek",
"(",
")",
"!=",
"JsonToken",
".",
"END_OBJECT",
")",
"{",
"map",
".",
"put",
"(",
"reader",
".",
"nextName",
"(",
")",
",",
"valueAdapter",
".",
"read",
"(",
"reader",
")",
")",
";",
"}",
"reader",
".",
"endObject",
"(",
")",
";",
"return",
"map",
";",
"}",
"}",
";",
"}",
"}"
] | This is to get around gson ignoring of inner class | [
"This",
"is",
"to",
"get",
"around",
"gson",
"ignoring",
"of",
"inner",
"class"
] | [] | [
{
"param": "TypeAdapterFactory",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "TypeAdapterFactory",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9c40f137b8eb82f5546536ed582c6488f1d08ab | lukairui/seata | core/src/test/java/io/seata/core/message/GlobalBeginRequestTest.java | [
"Apache-2.0"
] | Java | GlobalBeginRequestTest | /**
* The type Global begin request test.
*
* @author xiajun.0706 @163.com
* @since 2019 /1/24
*/ | The type Global begin request test. | [
"The",
"type",
"Global",
"begin",
"request",
"test",
"."
] | public class GlobalBeginRequestTest {
/**
* Test to string.
*
* @throws Exception the exception
*/
@Test
public void testToString() throws Exception {
GlobalBeginRequest globalBeginRequest = new GlobalBeginRequest();
globalBeginRequest.setTransactionName("tran 1");
System.out.println(globalBeginRequest.toString());
Assertions.assertEquals("timeout=60000,transactionName=tran 1", globalBeginRequest.toString());
}
} | [
"public",
"class",
"GlobalBeginRequestTest",
"{",
"/**\n * Test to string.\n *\n * @throws Exception the exception\n */",
"@",
"Test",
"public",
"void",
"testToString",
"(",
")",
"throws",
"Exception",
"{",
"GlobalBeginRequest",
"globalBeginRequest",
"=",
"new",
"GlobalBeginRequest",
"(",
")",
";",
"globalBeginRequest",
".",
"setTransactionName",
"(",
"\"",
"tran 1",
"\"",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"globalBeginRequest",
".",
"toString",
"(",
")",
")",
";",
"Assertions",
".",
"assertEquals",
"(",
"\"",
"timeout=60000,transactionName=tran 1",
"\"",
",",
"globalBeginRequest",
".",
"toString",
"(",
")",
")",
";",
"}",
"}"
] | The type Global begin request test. | [
"The",
"type",
"Global",
"begin",
"request",
"test",
"."
] | [] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9c4a2ac36038c23ac802cb31ad5ea51c30f0270 | janaGit/Sensor_SmartEditor | smartsensoreditor-api/src/main/java/org/n52/smartsensoreditor/cswclient/facades/TransactionResponseSOS.java | [
"Apache-2.0"
] | Java | TransactionResponseSOS | /**
* Response facade for a Transaction response
*
*/ | Response facade for a Transaction response | [
"Response",
"facade",
"for",
"a",
"Transaction",
"response"
] | public class TransactionResponseSOS extends TransactionResponse {
private static Logger LOG = Logger.getLogger(TransactionResponseSOS.class);
protected final static CSWContextSOS cswContextSOS = new CSWContextSOS();
private String insertedProcedure;
private String updatedProcedure;
private String deletedProcedure;
private String error="";
public TransactionResponseSOS() {
super(null);
}
/**
* Class contructor with parameters
*
* @param pDoc original server response
*/
public TransactionResponseSOS(Document pDoc) {
super(pDoc);
//initialize the procedure ids
insertedProcedure=evaluateAsString("//swes:assignedProcedure");
updatedProcedure=evaluateAsString("//swes:updatedProcedure");
deletedProcedure=evaluateAsString("//swes:deletedProcedure");
}
/**
* Return a list of strings
*
* @return list of identifier or null
*/
@Override
public List getIdentifiers() {
List<String> lResult = new ArrayList<String>();
if(getDocument()!=null){
if (!insertedProcedure.equals("")){
//assigned Procedure
lResult.add(insertedProcedure);
//assigned Offering
Element o = (Element)evaluateXPath("//swes:assignedOffering", XPathConstants.NODE);
if(o!=null){
NodeList list=o.getChildNodes();
int length=list.getLength();
Node node;
for(int i=0; i<length;i++){
node=list.item(i);
String insertedOffering=node.getNodeValue();
lResult.add(insertedOffering);
}
}
}else if(!updatedProcedure.equals("")){
lResult.add(updatedProcedure);
}else if(!deletedProcedure.equals("")){
lResult.add(deletedProcedure);
}
}
return lResult;
}
public String getRequestId() {
if (!insertedProcedure.equals("")){
return insertedProcedure;
}
if(!updatedProcedure.equals("")){
return updatedProcedure;
}
if(!deletedProcedure.equals("")){
return deletedProcedure;
}
return "";
}
@Override
public int getTotalInserted() {
if(getDocument()==null){
return 0;
}
if (insertedProcedure.equals("")) {
LOG.debug("'//swes:assignedProcedure' results to NULL. Returning 0 thus.");
return 0;
}
return 1;
}
@Override
public int getTotalUpdated() {
if(getDocument()==null){
return 0;
}
if (updatedProcedure.equals("")) {
LOG.debug("'//swes:updatedProcedure' results to NULL. Returning 0 thus.");
return 0;
}
return 1;
}
@Override
public int getTotalDeleted() {
if(getDocument()==null){
return 0;
}
if (deletedProcedure.equals("")) {
LOG.debug("'//swes:deletedProcedure' results to NULL. Returning 0 thus.");
return 0;
}
return 1;
}
public String getError() {
if(getDocument()==null){
return error;
}
error=evaluateAsString("//ows:ExceptionText");
if (error.equals("")) {
LOG.debug("'//ows:ExceptionText' results to NULL. Returning 0 thus.");
error="";
}
return error;
}
public void setError(String error){
this.error=error;
}
@Override
protected NamespaceContext getNamespaceContext() {
return cswContextSOS;
}
} | [
"public",
"class",
"TransactionResponseSOS",
"extends",
"TransactionResponse",
"{",
"private",
"static",
"Logger",
"LOG",
"=",
"Logger",
".",
"getLogger",
"(",
"TransactionResponseSOS",
".",
"class",
")",
";",
"protected",
"final",
"static",
"CSWContextSOS",
"cswContextSOS",
"=",
"new",
"CSWContextSOS",
"(",
")",
";",
"private",
"String",
"insertedProcedure",
";",
"private",
"String",
"updatedProcedure",
";",
"private",
"String",
"deletedProcedure",
";",
"private",
"String",
"error",
"=",
"\"",
"\"",
";",
"public",
"TransactionResponseSOS",
"(",
")",
"{",
"super",
"(",
"null",
")",
";",
"}",
"/**\n\t * Class contructor with parameters\n\t *\n\t * @param pDoc original server response\n\t */",
"public",
"TransactionResponseSOS",
"(",
"Document",
"pDoc",
")",
"{",
"super",
"(",
"pDoc",
")",
";",
"insertedProcedure",
"=",
"evaluateAsString",
"(",
"\"",
"//swes:assignedProcedure",
"\"",
")",
";",
"updatedProcedure",
"=",
"evaluateAsString",
"(",
"\"",
"//swes:updatedProcedure",
"\"",
")",
";",
"deletedProcedure",
"=",
"evaluateAsString",
"(",
"\"",
"//swes:deletedProcedure",
"\"",
")",
";",
"}",
"/**\n\t * Return a list of strings\n\t *\n\t * @return list of identifier or null\n\t */",
"@",
"Override",
"public",
"List",
"getIdentifiers",
"(",
")",
"{",
"List",
"<",
"String",
">",
"lResult",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
"getDocument",
"(",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"insertedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"lResult",
".",
"add",
"(",
"insertedProcedure",
")",
";",
"Element",
"o",
"=",
"(",
"Element",
")",
"evaluateXPath",
"(",
"\"",
"//swes:assignedOffering",
"\"",
",",
"XPathConstants",
".",
"NODE",
")",
";",
"if",
"(",
"o",
"!=",
"null",
")",
"{",
"NodeList",
"list",
"=",
"o",
".",
"getChildNodes",
"(",
")",
";",
"int",
"length",
"=",
"list",
".",
"getLength",
"(",
")",
";",
"Node",
"node",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"node",
"=",
"list",
".",
"item",
"(",
"i",
")",
";",
"String",
"insertedOffering",
"=",
"node",
".",
"getNodeValue",
"(",
")",
";",
"lResult",
".",
"add",
"(",
"insertedOffering",
")",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"!",
"updatedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"lResult",
".",
"add",
"(",
"updatedProcedure",
")",
";",
"}",
"else",
"if",
"(",
"!",
"deletedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"lResult",
".",
"add",
"(",
"deletedProcedure",
")",
";",
"}",
"}",
"return",
"lResult",
";",
"}",
"public",
"String",
"getRequestId",
"(",
")",
"{",
"if",
"(",
"!",
"insertedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"return",
"insertedProcedure",
";",
"}",
"if",
"(",
"!",
"updatedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"return",
"updatedProcedure",
";",
"}",
"if",
"(",
"!",
"deletedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"return",
"deletedProcedure",
";",
"}",
"return",
"\"",
"\"",
";",
"}",
"@",
"Override",
"public",
"int",
"getTotalInserted",
"(",
")",
"{",
"if",
"(",
"getDocument",
"(",
")",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"insertedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"'//swes:assignedProcedure' results to NULL. Returning 0 thus.",
"\"",
")",
";",
"return",
"0",
";",
"}",
"return",
"1",
";",
"}",
"@",
"Override",
"public",
"int",
"getTotalUpdated",
"(",
")",
"{",
"if",
"(",
"getDocument",
"(",
")",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"updatedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"'//swes:updatedProcedure' results to NULL. Returning 0 thus.",
"\"",
")",
";",
"return",
"0",
";",
"}",
"return",
"1",
";",
"}",
"@",
"Override",
"public",
"int",
"getTotalDeleted",
"(",
")",
"{",
"if",
"(",
"getDocument",
"(",
")",
"==",
"null",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"deletedProcedure",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"'//swes:deletedProcedure' results to NULL. Returning 0 thus.",
"\"",
")",
";",
"return",
"0",
";",
"}",
"return",
"1",
";",
"}",
"public",
"String",
"getError",
"(",
")",
"{",
"if",
"(",
"getDocument",
"(",
")",
"==",
"null",
")",
"{",
"return",
"error",
";",
"}",
"error",
"=",
"evaluateAsString",
"(",
"\"",
"//ows:ExceptionText",
"\"",
")",
";",
"if",
"(",
"error",
".",
"equals",
"(",
"\"",
"\"",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"",
"'//ows:ExceptionText' results to NULL. Returning 0 thus.",
"\"",
")",
";",
"error",
"=",
"\"",
"\"",
";",
"}",
"return",
"error",
";",
"}",
"public",
"void",
"setError",
"(",
"String",
"error",
")",
"{",
"this",
".",
"error",
"=",
"error",
";",
"}",
"@",
"Override",
"protected",
"NamespaceContext",
"getNamespaceContext",
"(",
")",
"{",
"return",
"cswContextSOS",
";",
"}",
"}"
] | Response facade for a Transaction response | [
"Response",
"facade",
"for",
"a",
"Transaction",
"response"
] | [
"//initialize the procedure ids",
"//assigned Procedure",
"//assigned Offering"
] | [
{
"param": "TransactionResponse",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "TransactionResponse",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9c7fc5cb02f50ede2a44a7e5323d4742339ab93 | jasongzcity/MyAlgorithm | leetcode/src/ContainsDuplicateII_219/Solution.java | [
"Apache-2.0"
] | Java | Solution | /**
* Given an array of integers and an integer k,
* find out whether there are two distinct indices i and j in the array
* such that nums[i] = nums[j] and the absolute difference
* between i and j is at most k.
*/ | Given an array of integers and an integer k,
find out whether there are two distinct indices i and j in the array
such that nums[i] = nums[j] and the absolute difference
between i and j is at most k. | [
"Given",
"an",
"array",
"of",
"integers",
"and",
"an",
"integer",
"k",
"find",
"out",
"whether",
"there",
"are",
"two",
"distinct",
"indices",
"i",
"and",
"j",
"in",
"the",
"array",
"such",
"that",
"nums",
"[",
"i",
"]",
"=",
"nums",
"[",
"j",
"]",
"and",
"the",
"absolute",
"difference",
"between",
"i",
"and",
"j",
"is",
"at",
"most",
"k",
"."
] | public class Solution {
// We could also use a set to "maintain" a window.
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<>(nums.length<<1);
for(int i=0;i<nums.length;i++){
Integer prev = map.put(nums[i],i);
if(prev!=null&&i-prev<=k) return true;
}
return false;
}
} | [
"public",
"class",
"Solution",
"{",
"public",
"boolean",
"containsNearbyDuplicate",
"(",
"int",
"[",
"]",
"nums",
",",
"int",
"k",
")",
"{",
"Map",
"<",
"Integer",
",",
"Integer",
">",
"map",
"=",
"new",
"HashMap",
"<",
">",
"(",
"nums",
".",
"length",
"<<",
"1",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nums",
".",
"length",
";",
"i",
"++",
")",
"{",
"Integer",
"prev",
"=",
"map",
".",
"put",
"(",
"nums",
"[",
"i",
"]",
",",
"i",
")",
";",
"if",
"(",
"prev",
"!=",
"null",
"&&",
"i",
"-",
"prev",
"<=",
"k",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
"}"
] | Given an array of integers and an integer k,
find out whether there are two distinct indices i and j in the array
such that nums[i] = nums[j] and the absolute difference
between i and j is at most k. | [
"Given",
"an",
"array",
"of",
"integers",
"and",
"an",
"integer",
"k",
"find",
"out",
"whether",
"there",
"are",
"two",
"distinct",
"indices",
"i",
"and",
"j",
"in",
"the",
"array",
"such",
"that",
"nums",
"[",
"i",
"]",
"=",
"nums",
"[",
"j",
"]",
"and",
"the",
"absolute",
"difference",
"between",
"i",
"and",
"j",
"is",
"at",
"most",
"k",
"."
] | [
"// We could also use a set to \"maintain\" a window."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9ca12bf3d5b293a13eecb7913ae5b72b22c7d6a | WANdisco/j | org.eclipse.jgit.http.server/src/org/eclipse/jgit/http/server/GitSmartHttpTools.java | [
"Apache-2.0"
] | Java | GitSmartHttpTools | /**
* Utility functions for handling the Git-over-HTTP protocol.
*/ | Utility functions for handling the Git-over-HTTP protocol. | [
"Utility",
"functions",
"for",
"handling",
"the",
"Git",
"-",
"over",
"-",
"HTTP",
"protocol",
"."
] | public class GitSmartHttpTools {
private static final String INFO_REFS = Constants.INFO_REFS;
/** Name of the git-upload-pack service. */
public static final String UPLOAD_PACK = "git-upload-pack";
/** Name of the git-receive-pack service. */
public static final String RECEIVE_PACK = "git-receive-pack";
/** Content type supplied by the client to the /git-upload-pack handler. */
public static final String UPLOAD_PACK_REQUEST_TYPE =
"application/x-git-upload-pack-request";
/** Content type returned from the /git-upload-pack handler. */
public static final String UPLOAD_PACK_RESULT_TYPE =
"application/x-git-upload-pack-result";
/** Content type supplied by the client to the /git-receive-pack handler. */
public static final String RECEIVE_PACK_REQUEST_TYPE =
"application/x-git-receive-pack-request";
/** Content type returned from the /git-receive-pack handler. */
public static final String RECEIVE_PACK_RESULT_TYPE =
"application/x-git-receive-pack-result";
/** Git service names accepted by the /info/refs?service= handler. */
public static final List<String> VALID_SERVICES =
Collections.unmodifiableList(Arrays.asList(new String[] {
UPLOAD_PACK, RECEIVE_PACK }));
private static final String INFO_REFS_PATH = "/" + INFO_REFS;
private static final String UPLOAD_PACK_PATH = "/" + UPLOAD_PACK;
private static final String RECEIVE_PACK_PATH = "/" + RECEIVE_PACK;
private static final List<String> SERVICE_SUFFIXES =
Collections.unmodifiableList(Arrays.asList(new String[] {
INFO_REFS_PATH, UPLOAD_PACK_PATH, RECEIVE_PACK_PATH }));
/**
* Check a request for Git-over-HTTP indicators.
*
* @param req
* the current HTTP request that may have been made by Git.
* @return true if the request is likely made by a Git client program.
*/
public static boolean isGitClient(HttpServletRequest req) {
return isInfoRefs(req) || isUploadPack(req) || isReceivePack(req);
}
/**
* Send an error to the Git client or browser.
* <p>
* Server implementors may use this method to send customized error messages
* to a Git protocol client using an HTTP 200 OK response with the error
* embedded in the payload. If the request was not issued by a Git client,
* an HTTP response code is returned instead.
*
* @param req
* current request.
* @param res
* current response.
* @param httpStatus
* HTTP status code to set if the client is not a Git client.
* @throws IOException
* the response cannot be sent.
*/
public static void sendError(HttpServletRequest req,
HttpServletResponse res, int httpStatus) throws IOException {
sendError(req, res, httpStatus, null);
}
/**
* Send an error to the Git client or browser.
* <p>
* Server implementors may use this method to send customized error messages
* to a Git protocol client using an HTTP 200 OK response with the error
* embedded in the payload. If the request was not issued by a Git client,
* an HTTP response code is returned instead.
* <p>
* This method may only be called before handing off the request to
* {@link org.eclipse.jgit.transport.UploadPack#upload(java.io.InputStream, OutputStream, OutputStream)}
* or
* {@link org.eclipse.jgit.transport.ReceivePack#receive(java.io.InputStream, OutputStream, OutputStream)}.
*
* @param req
* current request.
* @param res
* current response.
* @param httpStatus
* HTTP status code to set if the client is not a Git client.
* @param textForGit
* plain text message to display on the user's console. This is
* shown only if the client is likely to be a Git client. If null
* or the empty string a default text is chosen based on the HTTP
* response code.
* @throws IOException
* the response cannot be sent.
*/
public static void sendError(HttpServletRequest req,
HttpServletResponse res, int httpStatus, String textForGit)
throws IOException {
if (textForGit == null || textForGit.length() == 0) {
switch (httpStatus) {
case SC_FORBIDDEN:
textForGit = HttpServerText.get().repositoryAccessForbidden;
break;
case SC_NOT_FOUND:
textForGit = HttpServerText.get().repositoryNotFound;
break;
case SC_INTERNAL_SERVER_ERROR:
textForGit = HttpServerText.get().internalServerError;
break;
default:
textForGit = "HTTP " + httpStatus;
break;
}
}
if (isInfoRefs(req)) {
sendInfoRefsError(req, res, textForGit);
} else if (isUploadPack(req)) {
sendUploadPackError(req, res, textForGit);
} else if (isReceivePack(req)) {
sendReceivePackError(req, res, textForGit);
} else {
if (httpStatus < 400)
ServletUtils.consumeRequestBody(req);
res.sendError(httpStatus, textForGit);
}
}
private static void sendInfoRefsError(HttpServletRequest req,
HttpServletResponse res, String textForGit) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
PacketLineOut pck = new PacketLineOut(buf);
String svc = req.getParameter("service");
pck.writeString("# service=" + svc + "\n");
pck.end();
pck.writeString("ERR " + textForGit);
send(req, res, infoRefsResultType(svc), buf.toByteArray());
}
private static void sendUploadPackError(HttpServletRequest req,
HttpServletResponse res, String textForGit) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
PacketLineOut pckOut = new PacketLineOut(buf);
boolean sideband;
UploadPack up = (UploadPack) req.getAttribute(ATTRIBUTE_HANDLER);
if (up != null) {
try {
sideband = up.isSideBand();
} catch (RequestNotYetReadException e) {
sideband = isUploadPackSideBand(req);
}
} else
sideband = isUploadPackSideBand(req);
if (sideband)
writeSideBand(buf, textForGit);
else
writePacket(pckOut, textForGit);
send(req, res, UPLOAD_PACK_RESULT_TYPE, buf.toByteArray());
}
private static boolean isUploadPackSideBand(HttpServletRequest req) {
try {
// The client may be in a state where they have sent the sideband
// capability and are expecting a response in the sideband, but we might
// not have an UploadPack, or it might not have read any of the request.
// So, cheat and read the first line.
String line = new PacketLineIn(req.getInputStream()).readString();
UploadPack.FirstLine parsed = new UploadPack.FirstLine(line);
return (parsed.getOptions().contains(OPTION_SIDE_BAND)
|| parsed.getOptions().contains(OPTION_SIDE_BAND_64K));
} catch (IOException e) {
// Probably the connection is closed and a subsequent write will fail, but
// try it just in case.
return false;
}
}
private static void sendReceivePackError(HttpServletRequest req,
HttpServletResponse res, String textForGit) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream(128);
PacketLineOut pckOut = new PacketLineOut(buf);
boolean sideband;
ReceivePack rp = (ReceivePack) req.getAttribute(ATTRIBUTE_HANDLER);
if (rp != null) {
try {
sideband = rp.isSideBand();
} catch (RequestNotYetReadException e) {
sideband = isReceivePackSideBand(req);
}
} else
sideband = isReceivePackSideBand(req);
if (sideband)
writeSideBand(buf, textForGit);
else
writePacket(pckOut, textForGit);
send(req, res, RECEIVE_PACK_RESULT_TYPE, buf.toByteArray());
}
private static boolean isReceivePackSideBand(HttpServletRequest req) {
try {
// The client may be in a state where they have sent the sideband
// capability and are expecting a response in the sideband, but we might
// not have a ReceivePack, or it might not have read any of the request.
// So, cheat and read the first line.
String line = new PacketLineIn(req.getInputStream()).readString();
ReceivePack.FirstLine parsed = new ReceivePack.FirstLine(line);
return parsed.getCapabilities().contains(CAPABILITY_SIDE_BAND_64K);
} catch (IOException e) {
// Probably the connection is closed and a subsequent write will fail, but
// try it just in case.
return false;
}
}
private static void writeSideBand(OutputStream out, String textForGit)
throws IOException {
@SuppressWarnings("resource" /* java 7 */)
OutputStream msg = new SideBandOutputStream(CH_ERROR, SMALL_BUF, out);
msg.write(Constants.encode("error: " + textForGit));
msg.flush();
}
private static void writePacket(PacketLineOut pckOut, String textForGit)
throws IOException {
pckOut.writeString("error: " + textForGit);
}
private static void send(HttpServletRequest req, HttpServletResponse res,
String type, byte[] buf) throws IOException {
ServletUtils.consumeRequestBody(req);
res.setStatus(HttpServletResponse.SC_OK);
res.setContentType(type);
res.setContentLength(buf.length);
try (OutputStream os = res.getOutputStream()) {
os.write(buf);
}
}
/**
* Get the response Content-Type a client expects for the request.
* <p>
* This method should only be invoked if
* {@link #isGitClient(HttpServletRequest)} is true.
*
* @param req
* current request.
* @return the Content-Type the client expects.
* @throws IllegalArgumentException
* the request is not a Git client request. See
* {@link #isGitClient(HttpServletRequest)}.
*/
public static String getResponseContentType(HttpServletRequest req) {
if (isInfoRefs(req))
return infoRefsResultType(req.getParameter("service"));
else if (isUploadPack(req))
return UPLOAD_PACK_RESULT_TYPE;
else if (isReceivePack(req))
return RECEIVE_PACK_RESULT_TYPE;
else
throw new IllegalArgumentException();
}
static String infoRefsResultType(String svc) {
return "application/x-" + svc + "-advertisement";
}
/**
* Strip the Git service suffix from a request path.
*
* Generally the suffix is stripped by the {@code SuffixPipeline} handling
* the request, so this method is rarely needed.
*
* @param path
* the path of the request.
* @return the path up to the last path component before the service suffix;
* the path as-is if it contains no service suffix.
*/
public static String stripServiceSuffix(String path) {
for (String suffix : SERVICE_SUFFIXES) {
if (path.endsWith(suffix))
return path.substring(0, path.length() - suffix.length());
}
return path;
}
/**
* Check if the HTTP request was for the /info/refs?service= Git handler.
*
* @param req
* current request.
* @return true if the request is for the /info/refs service.
*/
public static boolean isInfoRefs(HttpServletRequest req) {
return req.getRequestURI().endsWith(INFO_REFS_PATH)
&& VALID_SERVICES.contains(req.getParameter("service"));
}
/**
* Check if the HTTP request path ends with the /git-upload-pack handler.
*
* @param pathOrUri
* path or URI of the request.
* @return true if the request is for the /git-upload-pack handler.
*/
public static boolean isUploadPack(String pathOrUri) {
return pathOrUri != null && pathOrUri.endsWith(UPLOAD_PACK_PATH);
}
/**
* Check if the HTTP request was for the /git-upload-pack Git handler.
*
* @param req
* current request.
* @return true if the request is for the /git-upload-pack handler.
*/
public static boolean isUploadPack(HttpServletRequest req) {
return isUploadPack(req.getRequestURI())
&& UPLOAD_PACK_REQUEST_TYPE.equals(req.getContentType());
}
/**
* Check if the HTTP request was for the /git-receive-pack Git handler.
*
* @param req
* current request.
* @return true if the request is for the /git-receive-pack handler.
*/
public static boolean isReceivePack(HttpServletRequest req) {
String uri = req.getRequestURI();
return uri != null && uri.endsWith(RECEIVE_PACK_PATH)
&& RECEIVE_PACK_REQUEST_TYPE.equals(req.getContentType());
}
private GitSmartHttpTools() {
}
} | [
"public",
"class",
"GitSmartHttpTools",
"{",
"private",
"static",
"final",
"String",
"INFO_REFS",
"=",
"Constants",
".",
"INFO_REFS",
";",
"/** Name of the git-upload-pack service. */",
"public",
"static",
"final",
"String",
"UPLOAD_PACK",
"=",
"\"",
"git-upload-pack",
"\"",
";",
"/** Name of the git-receive-pack service. */",
"public",
"static",
"final",
"String",
"RECEIVE_PACK",
"=",
"\"",
"git-receive-pack",
"\"",
";",
"/** Content type supplied by the client to the /git-upload-pack handler. */",
"public",
"static",
"final",
"String",
"UPLOAD_PACK_REQUEST_TYPE",
"=",
"\"",
"application/x-git-upload-pack-request",
"\"",
";",
"/** Content type returned from the /git-upload-pack handler. */",
"public",
"static",
"final",
"String",
"UPLOAD_PACK_RESULT_TYPE",
"=",
"\"",
"application/x-git-upload-pack-result",
"\"",
";",
"/** Content type supplied by the client to the /git-receive-pack handler. */",
"public",
"static",
"final",
"String",
"RECEIVE_PACK_REQUEST_TYPE",
"=",
"\"",
"application/x-git-receive-pack-request",
"\"",
";",
"/** Content type returned from the /git-receive-pack handler. */",
"public",
"static",
"final",
"String",
"RECEIVE_PACK_RESULT_TYPE",
"=",
"\"",
"application/x-git-receive-pack-result",
"\"",
";",
"/** Git service names accepted by the /info/refs?service= handler. */",
"public",
"static",
"final",
"List",
"<",
"String",
">",
"VALID_SERVICES",
"=",
"Collections",
".",
"unmodifiableList",
"(",
"Arrays",
".",
"asList",
"(",
"new",
"String",
"[",
"]",
"{",
"UPLOAD_PACK",
",",
"RECEIVE_PACK",
"}",
")",
")",
";",
"private",
"static",
"final",
"String",
"INFO_REFS_PATH",
"=",
"\"",
"/",
"\"",
"+",
"INFO_REFS",
";",
"private",
"static",
"final",
"String",
"UPLOAD_PACK_PATH",
"=",
"\"",
"/",
"\"",
"+",
"UPLOAD_PACK",
";",
"private",
"static",
"final",
"String",
"RECEIVE_PACK_PATH",
"=",
"\"",
"/",
"\"",
"+",
"RECEIVE_PACK",
";",
"private",
"static",
"final",
"List",
"<",
"String",
">",
"SERVICE_SUFFIXES",
"=",
"Collections",
".",
"unmodifiableList",
"(",
"Arrays",
".",
"asList",
"(",
"new",
"String",
"[",
"]",
"{",
"INFO_REFS_PATH",
",",
"UPLOAD_PACK_PATH",
",",
"RECEIVE_PACK_PATH",
"}",
")",
")",
";",
"/**\n\t * Check a request for Git-over-HTTP indicators.\n\t *\n\t * @param req\n\t * the current HTTP request that may have been made by Git.\n\t * @return true if the request is likely made by a Git client program.\n\t */",
"public",
"static",
"boolean",
"isGitClient",
"(",
"HttpServletRequest",
"req",
")",
"{",
"return",
"isInfoRefs",
"(",
"req",
")",
"||",
"isUploadPack",
"(",
"req",
")",
"||",
"isReceivePack",
"(",
"req",
")",
";",
"}",
"/**\n\t * Send an error to the Git client or browser.\n\t * <p>\n\t * Server implementors may use this method to send customized error messages\n\t * to a Git protocol client using an HTTP 200 OK response with the error\n\t * embedded in the payload. If the request was not issued by a Git client,\n\t * an HTTP response code is returned instead.\n\t *\n\t * @param req\n\t * current request.\n\t * @param res\n\t * current response.\n\t * @param httpStatus\n\t * HTTP status code to set if the client is not a Git client.\n\t * @throws IOException\n\t * the response cannot be sent.\n\t */",
"public",
"static",
"void",
"sendError",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"int",
"httpStatus",
")",
"throws",
"IOException",
"{",
"sendError",
"(",
"req",
",",
"res",
",",
"httpStatus",
",",
"null",
")",
";",
"}",
"/**\n\t * Send an error to the Git client or browser.\n\t * <p>\n\t * Server implementors may use this method to send customized error messages\n\t * to a Git protocol client using an HTTP 200 OK response with the error\n\t * embedded in the payload. If the request was not issued by a Git client,\n\t * an HTTP response code is returned instead.\n\t * <p>\n\t * This method may only be called before handing off the request to\n\t * {@link org.eclipse.jgit.transport.UploadPack#upload(java.io.InputStream, OutputStream, OutputStream)}\n\t * or\n\t * {@link org.eclipse.jgit.transport.ReceivePack#receive(java.io.InputStream, OutputStream, OutputStream)}.\n\t *\n\t * @param req\n\t * current request.\n\t * @param res\n\t * current response.\n\t * @param httpStatus\n\t * HTTP status code to set if the client is not a Git client.\n\t * @param textForGit\n\t * plain text message to display on the user's console. This is\n\t * shown only if the client is likely to be a Git client. If null\n\t * or the empty string a default text is chosen based on the HTTP\n\t * response code.\n\t * @throws IOException\n\t * the response cannot be sent.\n\t */",
"public",
"static",
"void",
"sendError",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"int",
"httpStatus",
",",
"String",
"textForGit",
")",
"throws",
"IOException",
"{",
"if",
"(",
"textForGit",
"==",
"null",
"||",
"textForGit",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"switch",
"(",
"httpStatus",
")",
"{",
"case",
"SC_FORBIDDEN",
":",
"textForGit",
"=",
"HttpServerText",
".",
"get",
"(",
")",
".",
"repositoryAccessForbidden",
";",
"break",
";",
"case",
"SC_NOT_FOUND",
":",
"textForGit",
"=",
"HttpServerText",
".",
"get",
"(",
")",
".",
"repositoryNotFound",
";",
"break",
";",
"case",
"SC_INTERNAL_SERVER_ERROR",
":",
"textForGit",
"=",
"HttpServerText",
".",
"get",
"(",
")",
".",
"internalServerError",
";",
"break",
";",
"default",
":",
"textForGit",
"=",
"\"",
"HTTP ",
"\"",
"+",
"httpStatus",
";",
"break",
";",
"}",
"}",
"if",
"(",
"isInfoRefs",
"(",
"req",
")",
")",
"{",
"sendInfoRefsError",
"(",
"req",
",",
"res",
",",
"textForGit",
")",
";",
"}",
"else",
"if",
"(",
"isUploadPack",
"(",
"req",
")",
")",
"{",
"sendUploadPackError",
"(",
"req",
",",
"res",
",",
"textForGit",
")",
";",
"}",
"else",
"if",
"(",
"isReceivePack",
"(",
"req",
")",
")",
"{",
"sendReceivePackError",
"(",
"req",
",",
"res",
",",
"textForGit",
")",
";",
"}",
"else",
"{",
"if",
"(",
"httpStatus",
"<",
"400",
")",
"ServletUtils",
".",
"consumeRequestBody",
"(",
"req",
")",
";",
"res",
".",
"sendError",
"(",
"httpStatus",
",",
"textForGit",
")",
";",
"}",
"}",
"private",
"static",
"void",
"sendInfoRefsError",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"String",
"textForGit",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"buf",
"=",
"new",
"ByteArrayOutputStream",
"(",
"128",
")",
";",
"PacketLineOut",
"pck",
"=",
"new",
"PacketLineOut",
"(",
"buf",
")",
";",
"String",
"svc",
"=",
"req",
".",
"getParameter",
"(",
"\"",
"service",
"\"",
")",
";",
"pck",
".",
"writeString",
"(",
"\"",
"# service=",
"\"",
"+",
"svc",
"+",
"\"",
"\\n",
"\"",
")",
";",
"pck",
".",
"end",
"(",
")",
";",
"pck",
".",
"writeString",
"(",
"\"",
"ERR ",
"\"",
"+",
"textForGit",
")",
";",
"send",
"(",
"req",
",",
"res",
",",
"infoRefsResultType",
"(",
"svc",
")",
",",
"buf",
".",
"toByteArray",
"(",
")",
")",
";",
"}",
"private",
"static",
"void",
"sendUploadPackError",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"String",
"textForGit",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"buf",
"=",
"new",
"ByteArrayOutputStream",
"(",
"128",
")",
";",
"PacketLineOut",
"pckOut",
"=",
"new",
"PacketLineOut",
"(",
"buf",
")",
";",
"boolean",
"sideband",
";",
"UploadPack",
"up",
"=",
"(",
"UploadPack",
")",
"req",
".",
"getAttribute",
"(",
"ATTRIBUTE_HANDLER",
")",
";",
"if",
"(",
"up",
"!=",
"null",
")",
"{",
"try",
"{",
"sideband",
"=",
"up",
".",
"isSideBand",
"(",
")",
";",
"}",
"catch",
"(",
"RequestNotYetReadException",
"e",
")",
"{",
"sideband",
"=",
"isUploadPackSideBand",
"(",
"req",
")",
";",
"}",
"}",
"else",
"sideband",
"=",
"isUploadPackSideBand",
"(",
"req",
")",
";",
"if",
"(",
"sideband",
")",
"writeSideBand",
"(",
"buf",
",",
"textForGit",
")",
";",
"else",
"writePacket",
"(",
"pckOut",
",",
"textForGit",
")",
";",
"send",
"(",
"req",
",",
"res",
",",
"UPLOAD_PACK_RESULT_TYPE",
",",
"buf",
".",
"toByteArray",
"(",
")",
")",
";",
"}",
"private",
"static",
"boolean",
"isUploadPackSideBand",
"(",
"HttpServletRequest",
"req",
")",
"{",
"try",
"{",
"String",
"line",
"=",
"new",
"PacketLineIn",
"(",
"req",
".",
"getInputStream",
"(",
")",
")",
".",
"readString",
"(",
")",
";",
"UploadPack",
".",
"FirstLine",
"parsed",
"=",
"new",
"UploadPack",
".",
"FirstLine",
"(",
"line",
")",
";",
"return",
"(",
"parsed",
".",
"getOptions",
"(",
")",
".",
"contains",
"(",
"OPTION_SIDE_BAND",
")",
"||",
"parsed",
".",
"getOptions",
"(",
")",
".",
"contains",
"(",
"OPTION_SIDE_BAND_64K",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}",
"private",
"static",
"void",
"sendReceivePackError",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"String",
"textForGit",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"buf",
"=",
"new",
"ByteArrayOutputStream",
"(",
"128",
")",
";",
"PacketLineOut",
"pckOut",
"=",
"new",
"PacketLineOut",
"(",
"buf",
")",
";",
"boolean",
"sideband",
";",
"ReceivePack",
"rp",
"=",
"(",
"ReceivePack",
")",
"req",
".",
"getAttribute",
"(",
"ATTRIBUTE_HANDLER",
")",
";",
"if",
"(",
"rp",
"!=",
"null",
")",
"{",
"try",
"{",
"sideband",
"=",
"rp",
".",
"isSideBand",
"(",
")",
";",
"}",
"catch",
"(",
"RequestNotYetReadException",
"e",
")",
"{",
"sideband",
"=",
"isReceivePackSideBand",
"(",
"req",
")",
";",
"}",
"}",
"else",
"sideband",
"=",
"isReceivePackSideBand",
"(",
"req",
")",
";",
"if",
"(",
"sideband",
")",
"writeSideBand",
"(",
"buf",
",",
"textForGit",
")",
";",
"else",
"writePacket",
"(",
"pckOut",
",",
"textForGit",
")",
";",
"send",
"(",
"req",
",",
"res",
",",
"RECEIVE_PACK_RESULT_TYPE",
",",
"buf",
".",
"toByteArray",
"(",
")",
")",
";",
"}",
"private",
"static",
"boolean",
"isReceivePackSideBand",
"(",
"HttpServletRequest",
"req",
")",
"{",
"try",
"{",
"String",
"line",
"=",
"new",
"PacketLineIn",
"(",
"req",
".",
"getInputStream",
"(",
")",
")",
".",
"readString",
"(",
")",
";",
"ReceivePack",
".",
"FirstLine",
"parsed",
"=",
"new",
"ReceivePack",
".",
"FirstLine",
"(",
"line",
")",
";",
"return",
"parsed",
".",
"getCapabilities",
"(",
")",
".",
"contains",
"(",
"CAPABILITY_SIDE_BAND_64K",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}",
"private",
"static",
"void",
"writeSideBand",
"(",
"OutputStream",
"out",
",",
"String",
"textForGit",
")",
"throws",
"IOException",
"{",
"@",
"SuppressWarnings",
"(",
"\"",
"resource",
"\"",
"/* java 7 */",
")",
"OutputStream",
"msg",
"=",
"new",
"SideBandOutputStream",
"(",
"CH_ERROR",
",",
"SMALL_BUF",
",",
"out",
")",
";",
"msg",
".",
"write",
"(",
"Constants",
".",
"encode",
"(",
"\"",
"error: ",
"\"",
"+",
"textForGit",
")",
")",
";",
"msg",
".",
"flush",
"(",
")",
";",
"}",
"private",
"static",
"void",
"writePacket",
"(",
"PacketLineOut",
"pckOut",
",",
"String",
"textForGit",
")",
"throws",
"IOException",
"{",
"pckOut",
".",
"writeString",
"(",
"\"",
"error: ",
"\"",
"+",
"textForGit",
")",
";",
"}",
"private",
"static",
"void",
"send",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"String",
"type",
",",
"byte",
"[",
"]",
"buf",
")",
"throws",
"IOException",
"{",
"ServletUtils",
".",
"consumeRequestBody",
"(",
"req",
")",
";",
"res",
".",
"setStatus",
"(",
"HttpServletResponse",
".",
"SC_OK",
")",
";",
"res",
".",
"setContentType",
"(",
"type",
")",
";",
"res",
".",
"setContentLength",
"(",
"buf",
".",
"length",
")",
";",
"try",
"(",
"OutputStream",
"os",
"=",
"res",
".",
"getOutputStream",
"(",
")",
")",
"{",
"os",
".",
"write",
"(",
"buf",
")",
";",
"}",
"}",
"/**\n\t * Get the response Content-Type a client expects for the request.\n\t * <p>\n\t * This method should only be invoked if\n\t * {@link #isGitClient(HttpServletRequest)} is true.\n\t *\n\t * @param req\n\t * current request.\n\t * @return the Content-Type the client expects.\n\t * @throws IllegalArgumentException\n\t * the request is not a Git client request. See\n\t * {@link #isGitClient(HttpServletRequest)}.\n\t */",
"public",
"static",
"String",
"getResponseContentType",
"(",
"HttpServletRequest",
"req",
")",
"{",
"if",
"(",
"isInfoRefs",
"(",
"req",
")",
")",
"return",
"infoRefsResultType",
"(",
"req",
".",
"getParameter",
"(",
"\"",
"service",
"\"",
")",
")",
";",
"else",
"if",
"(",
"isUploadPack",
"(",
"req",
")",
")",
"return",
"UPLOAD_PACK_RESULT_TYPE",
";",
"else",
"if",
"(",
"isReceivePack",
"(",
"req",
")",
")",
"return",
"RECEIVE_PACK_RESULT_TYPE",
";",
"else",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"static",
"String",
"infoRefsResultType",
"(",
"String",
"svc",
")",
"{",
"return",
"\"",
"application/x-",
"\"",
"+",
"svc",
"+",
"\"",
"-advertisement",
"\"",
";",
"}",
"/**\n\t * Strip the Git service suffix from a request path.\n\t *\n\t * Generally the suffix is stripped by the {@code SuffixPipeline} handling\n\t * the request, so this method is rarely needed.\n\t *\n\t * @param path\n\t * the path of the request.\n\t * @return the path up to the last path component before the service suffix;\n\t * the path as-is if it contains no service suffix.\n\t */",
"public",
"static",
"String",
"stripServiceSuffix",
"(",
"String",
"path",
")",
"{",
"for",
"(",
"String",
"suffix",
":",
"SERVICE_SUFFIXES",
")",
"{",
"if",
"(",
"path",
".",
"endsWith",
"(",
"suffix",
")",
")",
"return",
"path",
".",
"substring",
"(",
"0",
",",
"path",
".",
"length",
"(",
")",
"-",
"suffix",
".",
"length",
"(",
")",
")",
";",
"}",
"return",
"path",
";",
"}",
"/**\n\t * Check if the HTTP request was for the /info/refs?service= Git handler.\n\t *\n\t * @param req\n\t * current request.\n\t * @return true if the request is for the /info/refs service.\n\t */",
"public",
"static",
"boolean",
"isInfoRefs",
"(",
"HttpServletRequest",
"req",
")",
"{",
"return",
"req",
".",
"getRequestURI",
"(",
")",
".",
"endsWith",
"(",
"INFO_REFS_PATH",
")",
"&&",
"VALID_SERVICES",
".",
"contains",
"(",
"req",
".",
"getParameter",
"(",
"\"",
"service",
"\"",
")",
")",
";",
"}",
"/**\n\t * Check if the HTTP request path ends with the /git-upload-pack handler.\n\t *\n\t * @param pathOrUri\n\t * path or URI of the request.\n\t * @return true if the request is for the /git-upload-pack handler.\n\t */",
"public",
"static",
"boolean",
"isUploadPack",
"(",
"String",
"pathOrUri",
")",
"{",
"return",
"pathOrUri",
"!=",
"null",
"&&",
"pathOrUri",
".",
"endsWith",
"(",
"UPLOAD_PACK_PATH",
")",
";",
"}",
"/**\n\t * Check if the HTTP request was for the /git-upload-pack Git handler.\n\t *\n\t * @param req\n\t * current request.\n\t * @return true if the request is for the /git-upload-pack handler.\n\t */",
"public",
"static",
"boolean",
"isUploadPack",
"(",
"HttpServletRequest",
"req",
")",
"{",
"return",
"isUploadPack",
"(",
"req",
".",
"getRequestURI",
"(",
")",
")",
"&&",
"UPLOAD_PACK_REQUEST_TYPE",
".",
"equals",
"(",
"req",
".",
"getContentType",
"(",
")",
")",
";",
"}",
"/**\n\t * Check if the HTTP request was for the /git-receive-pack Git handler.\n\t *\n\t * @param req\n\t * current request.\n\t * @return true if the request is for the /git-receive-pack handler.\n\t */",
"public",
"static",
"boolean",
"isReceivePack",
"(",
"HttpServletRequest",
"req",
")",
"{",
"String",
"uri",
"=",
"req",
".",
"getRequestURI",
"(",
")",
";",
"return",
"uri",
"!=",
"null",
"&&",
"uri",
".",
"endsWith",
"(",
"RECEIVE_PACK_PATH",
")",
"&&",
"RECEIVE_PACK_REQUEST_TYPE",
".",
"equals",
"(",
"req",
".",
"getContentType",
"(",
")",
")",
";",
"}",
"private",
"GitSmartHttpTools",
"(",
")",
"{",
"}",
"}"
] | Utility functions for handling the Git-over-HTTP protocol. | [
"Utility",
"functions",
"for",
"handling",
"the",
"Git",
"-",
"over",
"-",
"HTTP",
"protocol",
"."
] | [
"// The client may be in a state where they have sent the sideband",
"// capability and are expecting a response in the sideband, but we might",
"// not have an UploadPack, or it might not have read any of the request.",
"// So, cheat and read the first line.",
"// Probably the connection is closed and a subsequent write will fail, but",
"// try it just in case.",
"// The client may be in a state where they have sent the sideband",
"// capability and are expecting a response in the sideband, but we might",
"// not have a ReceivePack, or it might not have read any of the request.",
"// So, cheat and read the first line.",
"// Probably the connection is closed and a subsequent write will fail, but",
"// try it just in case."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9ca3e874ad1df561e2024d9df77d87ee8138838 | SourceLabOrg/java-hkp-client | src/main/java/org/sourcelab/hkp/config/Configuration.java | [
"MIT"
] | Java | Configuration | /**
* Defines API Client Configuration.
* Use {@link ConfigurationBuilder} to create instances of these.
*/ | Defines API Client Configuration.
Use ConfigurationBuilder to create instances of these. | [
"Defines",
"API",
"Client",
"Configuration",
".",
"Use",
"ConfigurationBuilder",
"to",
"create",
"instances",
"of",
"these",
"."
] | public class Configuration {
// Proxy Configuration
private final ProxyConfiguration proxyConfiguration;
// Defines upstream keyserver host.
private final String keyServerHost;
/**
* Optional setting to skip validating SSL certificate.
* There should be no real valid use case for this option other then use against
* development environments.
*/
private final boolean ignoreInvalidSslCertificates;
private final int requestTimeoutSecs;
private final String basePath = "/pks/lookup";
/**
* Creates a new ConfigurationBuilder instance.
* @return ConfigurationBuilder instance.
*/
public static ConfigurationBuilder newBuilder() {
return new ConfigurationBuilder();
}
/**
* Constructor.
* Note: Use {@link ConfigurationBuilder} to create instances instead of calling this constructor.
*
* @param proxyConfiguration Defines Proxy Configuration.
* @param keyServerHost Defines KeyServer Host.
* @param ignoreInvalidSslCertificates Should SSL certificates be validated.
* @param requestTimeoutSecs Defines how long (in seconds) before a request times out.
*/
public Configuration(
final String keyServerHost,
final ProxyConfiguration proxyConfiguration,
final boolean ignoreInvalidSslCertificates,
final int requestTimeoutSecs) {
this.proxyConfiguration = Objects.requireNonNull(proxyConfiguration);
this.keyServerHost = Objects.requireNonNull(keyServerHost);
this.ignoreInvalidSslCertificates = ignoreInvalidSslCertificates;
this.requestTimeoutSecs = requestTimeoutSecs;
}
public boolean hasProxyConfigured() {
return proxyConfiguration.isConfigured();
}
public ProxyConfiguration getProxyConfiguration() {
return proxyConfiguration;
}
public boolean isIgnoreInvalidSslCertificates() {
return ignoreInvalidSslCertificates;
}
public String getKeyServerHost() {
return keyServerHost;
}
public int getRequestTimeoutSecs() {
return requestTimeoutSecs;
}
public String getBasePath() {
return basePath;
}
@Override
public String toString() {
return "Configuration{"
+ "keyServerHost='" + keyServerHost + '\''
+ ", proxyConfiguration=" + proxyConfiguration
+ ", ignoreInvalidSslCertificates=" + ignoreInvalidSslCertificates
+ '}';
}
} | [
"public",
"class",
"Configuration",
"{",
"private",
"final",
"ProxyConfiguration",
"proxyConfiguration",
";",
"private",
"final",
"String",
"keyServerHost",
";",
"/**\n * Optional setting to skip validating SSL certificate.\n * There should be no real valid use case for this option other then use against\n * development environments.\n */",
"private",
"final",
"boolean",
"ignoreInvalidSslCertificates",
";",
"private",
"final",
"int",
"requestTimeoutSecs",
";",
"private",
"final",
"String",
"basePath",
"=",
"\"",
"/pks/lookup",
"\"",
";",
"/**\n * Creates a new ConfigurationBuilder instance.\n * @return ConfigurationBuilder instance.\n */",
"public",
"static",
"ConfigurationBuilder",
"newBuilder",
"(",
")",
"{",
"return",
"new",
"ConfigurationBuilder",
"(",
")",
";",
"}",
"/**\n * Constructor.\n * Note: Use {@link ConfigurationBuilder} to create instances instead of calling this constructor.\n *\n * @param proxyConfiguration Defines Proxy Configuration.\n * @param keyServerHost Defines KeyServer Host.\n * @param ignoreInvalidSslCertificates Should SSL certificates be validated.\n * @param requestTimeoutSecs Defines how long (in seconds) before a request times out.\n */",
"public",
"Configuration",
"(",
"final",
"String",
"keyServerHost",
",",
"final",
"ProxyConfiguration",
"proxyConfiguration",
",",
"final",
"boolean",
"ignoreInvalidSslCertificates",
",",
"final",
"int",
"requestTimeoutSecs",
")",
"{",
"this",
".",
"proxyConfiguration",
"=",
"Objects",
".",
"requireNonNull",
"(",
"proxyConfiguration",
")",
";",
"this",
".",
"keyServerHost",
"=",
"Objects",
".",
"requireNonNull",
"(",
"keyServerHost",
")",
";",
"this",
".",
"ignoreInvalidSslCertificates",
"=",
"ignoreInvalidSslCertificates",
";",
"this",
".",
"requestTimeoutSecs",
"=",
"requestTimeoutSecs",
";",
"}",
"public",
"boolean",
"hasProxyConfigured",
"(",
")",
"{",
"return",
"proxyConfiguration",
".",
"isConfigured",
"(",
")",
";",
"}",
"public",
"ProxyConfiguration",
"getProxyConfiguration",
"(",
")",
"{",
"return",
"proxyConfiguration",
";",
"}",
"public",
"boolean",
"isIgnoreInvalidSslCertificates",
"(",
")",
"{",
"return",
"ignoreInvalidSslCertificates",
";",
"}",
"public",
"String",
"getKeyServerHost",
"(",
")",
"{",
"return",
"keyServerHost",
";",
"}",
"public",
"int",
"getRequestTimeoutSecs",
"(",
")",
"{",
"return",
"requestTimeoutSecs",
";",
"}",
"public",
"String",
"getBasePath",
"(",
")",
"{",
"return",
"basePath",
";",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"return",
"\"",
"Configuration{",
"\"",
"+",
"\"",
"keyServerHost='",
"\"",
"+",
"keyServerHost",
"+",
"'\\''",
"+",
"\"",
", proxyConfiguration=",
"\"",
"+",
"proxyConfiguration",
"+",
"\"",
", ignoreInvalidSslCertificates=",
"\"",
"+",
"ignoreInvalidSslCertificates",
"+",
"'}'",
";",
"}",
"}"
] | Defines API Client Configuration. | [
"Defines",
"API",
"Client",
"Configuration",
"."
] | [
"// Proxy Configuration",
"// Defines upstream keyserver host."
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
b9ce029502f0e08407cb515c0c90787e036cdac6 | hiya492/spring | modules/sbe-rest/sbe-rest-core/src/main/java/org/springbyexample/mvc/method/annotation/RestServiceComponentProvider.java | [
"Apache-2.0"
] | Java | RestServiceComponentProvider | /**
* Scans for REST service interfaces to register as controller endpoints.
*
* @author David Winterfeldt
*/ | Scans for REST service interfaces to register as controller endpoints.
@author David Winterfeldt | [
"Scans",
"for",
"REST",
"service",
"interfaces",
"to",
"register",
"as",
"controller",
"endpoints",
".",
"@author",
"David",
"Winterfeldt"
] | public class RestServiceComponentProvider extends ClassPathScanningCandidateComponentProvider {
final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Creates a new {@link RepositoryComponentProvider} using the given {@link TypeFilter} to include components to be
* picked up.
*
* @param includeFilters the {@link TypeFilter}s to select repository interfaces to consider, must not be
* {@literal null}.
*/
public RestServiceComponentProvider() { //Iterable<? extends TypeFilter> includeFilters) {
super(false);
// Assert.notNull(includeFilters);
//
// if (includeFilters.iterator().hasNext()) {
// for (TypeFilter filter : includeFilters) {
// addIncludeFilter(filter);
// }
// } else {
super.addIncludeFilter(new AnnotationTypeFilter(RestResource.class, true, true));
// super.addIncludeFilter(new InterfaceTypeFilter(PersistenceMarshallingService.class));
// super.addIncludeFilter(new AnnotationTypeFilter(RepositoryDefinition.class, true, true));
// }
// addExcludeFilter(new AnnotationTypeFilter(NoRepositoryBean.class));
}
/**
* Custom extension of {@link #addIncludeFilter(TypeFilter)} to extend the added {@link TypeFilter}. For the
* {@link TypeFilter} handed we'll have two filters registered: one additionally enforcing the
* {@link RepositoryDefinition} annotation, the other one forcing the extension of {@link Repository}.
*
* @see ClassPathScanningCandidateComponentProvider#addIncludeFilter(TypeFilter)
*/
@Override
public void addIncludeFilter(TypeFilter includeFilter) {
List<TypeFilter> filterPlusInterface = new ArrayList<TypeFilter>(2);
filterPlusInterface.add(includeFilter);
// filterPlusInterface.add(new InterfaceTypeFilter(PersistenceMarshallingService.class));
super.addIncludeFilter(new AllTypeFilter(filterPlusInterface));
List<TypeFilter> filterPlusAnnotation = new ArrayList<TypeFilter>(2);
filterPlusAnnotation.add(includeFilter);
// filterPlusAnnotation.add(new AnnotationTypeFilter(RepositoryDefinition.class, true, true));
super.addIncludeFilter(new AllTypeFilter(filterPlusAnnotation));
}
/*
* (non-Javadoc)
* @see org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#isCandidateComponent(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition)
*/
@Override
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
boolean isNonRepositoryInterface = RestServiceUtils.isRestServiceInterface(beanDefinition.getBeanClassName());
boolean isTopLevelType = !beanDefinition.getMetadata().hasEnclosingClass();
return isNonRepositoryInterface && isTopLevelType;
}
// /**
// * {@link org.springframework.core.type.filter.TypeFilter} that only matches interfaces. Thus setting this up makes
// * only sense providing an interface type as {@code targetType}.
// *
// * @author Oliver Gierke
// */
// private static class InterfaceTypeFilter extends AssignableTypeFilter {
//
// /**
// * Creates a new {@link InterfaceTypeFilter}.
// *
// * @param targetType
// */
// public InterfaceTypeFilter(Class<?> targetType) {
// super(targetType);
// }
//
// /*
// * (non-Javadoc)
// * @see org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter#match(org.springframework.core.type.classreading.MetadataReader, org.springframework.core.type.classreading.MetadataReaderFactory)
// */
// @Override
// public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
// return metadataReader.getClassMetadata().isInterface() && super.match(metadataReader, metadataReaderFactory);
// }
// }
// Copy of Spring's AnnotationTypeFilter until SPR-8336 gets resolved.
/**
* A simple filter which matches classes with a given annotation, checking inherited annotations as well.
* <p>
* The matching logic mirrors that of <code>Class.isAnnotationPresent()</code>.
*
* @author Mark Fisher
* @author Ramnivas Laddad
* @author Juergen Hoeller
* @since 2.5
*/
private class AnnotationTypeFilter extends AbstractTypeHierarchyTraversingFilter {
private final Class<? extends Annotation> annotationType;
private final boolean considerMetaAnnotations;
/**
* Create a new AnnotationTypeFilter for the given annotation type. This filter will also match meta-annotations. To
* disable the meta-annotation matching, use the constructor that accepts a ' <code>considerMetaAnnotations</code>'
* argument. The filter will not match interfaces.
*
* @param annotationType the annotation type to match
*/
// public AnnotationTypeFilter(Class<? extends Annotation> annotationType) {
// this(annotationType, true);
// }
/**
* Create a new AnnotationTypeFilter for the given annotation type. The filter will not match interfaces.
*
* @param annotationType the annotation type to match
* @param considerMetaAnnotations whether to also match on meta-annotations
*/
// public AnnotationTypeFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations) {
// this(annotationType, considerMetaAnnotations, false);
// }
/**
* Create a new {@link AnnotationTypeFilter} for the given annotation type.
*
* @param annotationType the annotation type to match
* @param considerMetaAnnotations whether to also match on meta-annotations
* @param considerInterfaces whether to also match interfaces
*/
public AnnotationTypeFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations,
boolean considerInterfaces) {
super(annotationType.isAnnotationPresent(Inherited.class), considerInterfaces);
this.annotationType = annotationType;
this.considerMetaAnnotations = considerMetaAnnotations;
}
@Override
protected boolean matchSelf(MetadataReader metadataReader) {
AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
return metadata.hasAnnotation(this.annotationType.getName())
|| (this.considerMetaAnnotations && metadata.hasMetaAnnotation(this.annotationType.getName()));
}
@Override
protected Boolean matchSuperClass(String superClassName) {
if (Object.class.getName().equals(superClassName)) {
return Boolean.FALSE;
} else if (superClassName.startsWith("java.")) {
try {
Class<?> clazz = getClass().getClassLoader().loadClass(superClassName);
return (clazz.getAnnotation(this.annotationType) != null);
} catch (ClassNotFoundException ex) {
// Class not found - can't determine a match that way.
}
}
return null;
}
}
/**
* Helper class to create a {@link TypeFilter} that matches if all the delegates match.
*
* @author Oliver Gierke
*/
private class AllTypeFilter implements TypeFilter {
private final List<TypeFilter> delegates;
/**
* Creates a new {@link AllTypeFilter} to match if all the given delegates match.
*
* @param delegates must not be {@literal null}.
*/
public AllTypeFilter(List<TypeFilter> delegates) {
Assert.notNull(delegates);
this.delegates = delegates;
}
/*
* (non-Javadoc)
* @see org.springframework.core.type.filter.TypeFilter#match(org.springframework.core.type.classreading.MetadataReader, org.springframework.core.type.classreading.MetadataReaderFactory)
*/
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
for (TypeFilter filter : delegates) {
if (!filter.match(metadataReader, metadataReaderFactory)) {
return false;
}
}
return true;
}
}
} | [
"public",
"class",
"RestServiceComponentProvider",
"extends",
"ClassPathScanningCandidateComponentProvider",
"{",
"final",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"getClass",
"(",
")",
")",
";",
"/**\n * Creates a new {@link RepositoryComponentProvider} using the given {@link TypeFilter} to include components to be\n * picked up.\n * \n * @param includeFilters the {@link TypeFilter}s to select repository interfaces to consider, must not be\n * {@literal null}.\n */",
"public",
"RestServiceComponentProvider",
"(",
")",
"{",
"super",
"(",
"false",
")",
";",
"super",
".",
"addIncludeFilter",
"(",
"new",
"AnnotationTypeFilter",
"(",
"RestResource",
".",
"class",
",",
"true",
",",
"true",
")",
")",
";",
"}",
"/**\n * Custom extension of {@link #addIncludeFilter(TypeFilter)} to extend the added {@link TypeFilter}. For the\n * {@link TypeFilter} handed we'll have two filters registered: one additionally enforcing the\n * {@link RepositoryDefinition} annotation, the other one forcing the extension of {@link Repository}.\n * \n * @see ClassPathScanningCandidateComponentProvider#addIncludeFilter(TypeFilter)\n */",
"@",
"Override",
"public",
"void",
"addIncludeFilter",
"(",
"TypeFilter",
"includeFilter",
")",
"{",
"List",
"<",
"TypeFilter",
">",
"filterPlusInterface",
"=",
"new",
"ArrayList",
"<",
"TypeFilter",
">",
"(",
"2",
")",
";",
"filterPlusInterface",
".",
"add",
"(",
"includeFilter",
")",
";",
"super",
".",
"addIncludeFilter",
"(",
"new",
"AllTypeFilter",
"(",
"filterPlusInterface",
")",
")",
";",
"List",
"<",
"TypeFilter",
">",
"filterPlusAnnotation",
"=",
"new",
"ArrayList",
"<",
"TypeFilter",
">",
"(",
"2",
")",
";",
"filterPlusAnnotation",
".",
"add",
"(",
"includeFilter",
")",
";",
"super",
".",
"addIncludeFilter",
"(",
"new",
"AllTypeFilter",
"(",
"filterPlusAnnotation",
")",
")",
";",
"}",
"/*\n * (non-Javadoc)\n * @see org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#isCandidateComponent(org.springframework.beans.factory.annotation.AnnotatedBeanDefinition)\n */",
"@",
"Override",
"protected",
"boolean",
"isCandidateComponent",
"(",
"AnnotatedBeanDefinition",
"beanDefinition",
")",
"{",
"boolean",
"isNonRepositoryInterface",
"=",
"RestServiceUtils",
".",
"isRestServiceInterface",
"(",
"beanDefinition",
".",
"getBeanClassName",
"(",
")",
")",
";",
"boolean",
"isTopLevelType",
"=",
"!",
"beanDefinition",
".",
"getMetadata",
"(",
")",
".",
"hasEnclosingClass",
"(",
")",
";",
"return",
"isNonRepositoryInterface",
"&&",
"isTopLevelType",
";",
"}",
"/**\n * A simple filter which matches classes with a given annotation, checking inherited annotations as well.\n * <p>\n * The matching logic mirrors that of <code>Class.isAnnotationPresent()</code>.\n * \n * @author Mark Fisher\n * @author Ramnivas Laddad\n * @author Juergen Hoeller\n * @since 2.5\n */",
"private",
"class",
"AnnotationTypeFilter",
"extends",
"AbstractTypeHierarchyTraversingFilter",
"{",
"private",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
";",
"private",
"final",
"boolean",
"considerMetaAnnotations",
";",
"/**\n * Create a new AnnotationTypeFilter for the given annotation type. This filter will also match meta-annotations. To\n * disable the meta-annotation matching, use the constructor that accepts a ' <code>considerMetaAnnotations</code>'\n * argument. The filter will not match interfaces.\n * \n * @param annotationType the annotation type to match\n */",
"/**\n * Create a new AnnotationTypeFilter for the given annotation type. The filter will not match interfaces.\n * \n * @param annotationType the annotation type to match\n * @param considerMetaAnnotations whether to also match on meta-annotations\n */",
"/**\n * Create a new {@link AnnotationTypeFilter} for the given annotation type.\n * \n * @param annotationType the annotation type to match\n * @param considerMetaAnnotations whether to also match on meta-annotations\n * @param considerInterfaces whether to also match interfaces\n */",
"public",
"AnnotationTypeFilter",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
",",
"boolean",
"considerMetaAnnotations",
",",
"boolean",
"considerInterfaces",
")",
"{",
"super",
"(",
"annotationType",
".",
"isAnnotationPresent",
"(",
"Inherited",
".",
"class",
")",
",",
"considerInterfaces",
")",
";",
"this",
".",
"annotationType",
"=",
"annotationType",
";",
"this",
".",
"considerMetaAnnotations",
"=",
"considerMetaAnnotations",
";",
"}",
"@",
"Override",
"protected",
"boolean",
"matchSelf",
"(",
"MetadataReader",
"metadataReader",
")",
"{",
"AnnotationMetadata",
"metadata",
"=",
"metadataReader",
".",
"getAnnotationMetadata",
"(",
")",
";",
"return",
"metadata",
".",
"hasAnnotation",
"(",
"this",
".",
"annotationType",
".",
"getName",
"(",
")",
")",
"||",
"(",
"this",
".",
"considerMetaAnnotations",
"&&",
"metadata",
".",
"hasMetaAnnotation",
"(",
"this",
".",
"annotationType",
".",
"getName",
"(",
")",
")",
")",
";",
"}",
"@",
"Override",
"protected",
"Boolean",
"matchSuperClass",
"(",
"String",
"superClassName",
")",
"{",
"if",
"(",
"Object",
".",
"class",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"superClassName",
")",
")",
"{",
"return",
"Boolean",
".",
"FALSE",
";",
"}",
"else",
"if",
"(",
"superClassName",
".",
"startsWith",
"(",
"\"",
"java.",
"\"",
")",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"getClass",
"(",
")",
".",
"getClassLoader",
"(",
")",
".",
"loadClass",
"(",
"superClassName",
")",
";",
"return",
"(",
"clazz",
".",
"getAnnotation",
"(",
"this",
".",
"annotationType",
")",
"!=",
"null",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"ex",
")",
"{",
"}",
"}",
"return",
"null",
";",
"}",
"}",
"/**\n * Helper class to create a {@link TypeFilter} that matches if all the delegates match.\n * \n * @author Oliver Gierke\n */",
"private",
"class",
"AllTypeFilter",
"implements",
"TypeFilter",
"{",
"private",
"final",
"List",
"<",
"TypeFilter",
">",
"delegates",
";",
"/**\n * Creates a new {@link AllTypeFilter} to match if all the given delegates match.\n * \n * @param delegates must not be {@literal null}.\n */",
"public",
"AllTypeFilter",
"(",
"List",
"<",
"TypeFilter",
">",
"delegates",
")",
"{",
"Assert",
".",
"notNull",
"(",
"delegates",
")",
";",
"this",
".",
"delegates",
"=",
"delegates",
";",
"}",
"/* \n * (non-Javadoc)\n * @see org.springframework.core.type.filter.TypeFilter#match(org.springframework.core.type.classreading.MetadataReader, org.springframework.core.type.classreading.MetadataReaderFactory)\n */",
"public",
"boolean",
"match",
"(",
"MetadataReader",
"metadataReader",
",",
"MetadataReaderFactory",
"metadataReaderFactory",
")",
"throws",
"IOException",
"{",
"for",
"(",
"TypeFilter",
"filter",
":",
"delegates",
")",
"{",
"if",
"(",
"!",
"filter",
".",
"match",
"(",
"metadataReader",
",",
"metadataReaderFactory",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"}",
"}"
] | Scans for REST service interfaces to register as controller endpoints. | [
"Scans",
"for",
"REST",
"service",
"interfaces",
"to",
"register",
"as",
"controller",
"endpoints",
"."
] | [
"//Iterable<? extends TypeFilter> includeFilters) {",
"// Assert.notNull(includeFilters);",
"//",
"// if (includeFilters.iterator().hasNext()) {",
"// for (TypeFilter filter : includeFilters) {",
"// addIncludeFilter(filter);",
"// }",
"// } else {",
"// super.addIncludeFilter(new InterfaceTypeFilter(PersistenceMarshallingService.class));",
"// super.addIncludeFilter(new AnnotationTypeFilter(RepositoryDefinition.class, true, true));",
"// }",
"// addExcludeFilter(new AnnotationTypeFilter(NoRepositoryBean.class));",
"// filterPlusInterface.add(new InterfaceTypeFilter(PersistenceMarshallingService.class));",
"// filterPlusAnnotation.add(new AnnotationTypeFilter(RepositoryDefinition.class, true, true));",
"// /**",
"// * {@link org.springframework.core.type.filter.TypeFilter} that only matches interfaces. Thus setting this up makes",
"// * only sense providing an interface type as {@code targetType}.",
"// * ",
"// * @author Oliver Gierke",
"// */",
"// private static class InterfaceTypeFilter extends AssignableTypeFilter {",
"//",
"// /**",
"// * Creates a new {@link InterfaceTypeFilter}.",
"// * ",
"// * @param targetType",
"// */",
"// public InterfaceTypeFilter(Class<?> targetType) {",
"// super(targetType);",
"// }",
"//",
"// /*",
"// * (non-Javadoc)",
"// * @see org.springframework.core.type.filter.AbstractTypeHierarchyTraversingFilter#match(org.springframework.core.type.classreading.MetadataReader, org.springframework.core.type.classreading.MetadataReaderFactory)",
"// */",
"// @Override",
"// public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {",
"// return metadataReader.getClassMetadata().isInterface() && super.match(metadataReader, metadataReaderFactory);",
"// }",
"// }",
"// Copy of Spring's AnnotationTypeFilter until SPR-8336 gets resolved.",
"// public AnnotationTypeFilter(Class<? extends Annotation> annotationType) {",
"// this(annotationType, true);",
"// }",
"// public AnnotationTypeFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations) {",
"// this(annotationType, considerMetaAnnotations, false);",
"// }",
"// Class not found - can't determine a match that way."
] | [
{
"param": "ClassPathScanningCandidateComponentProvider",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ClassPathScanningCandidateComponentProvider",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9ce029502f0e08407cb515c0c90787e036cdac6 | hiya492/spring | modules/sbe-rest/sbe-rest-core/src/main/java/org/springbyexample/mvc/method/annotation/RestServiceComponentProvider.java | [
"Apache-2.0"
] | Java | AnnotationTypeFilter | /**
* A simple filter which matches classes with a given annotation, checking inherited annotations as well.
* <p>
* The matching logic mirrors that of <code>Class.isAnnotationPresent()</code>.
*
* @author Mark Fisher
* @author Ramnivas Laddad
* @author Juergen Hoeller
* @since 2.5
*/ | A simple filter which matches classes with a given annotation, checking inherited annotations as well.
The matching logic mirrors that of Class.isAnnotationPresent().
@author Mark Fisher
@author Ramnivas Laddad
@author Juergen Hoeller
@since 2.5 | [
"A",
"simple",
"filter",
"which",
"matches",
"classes",
"with",
"a",
"given",
"annotation",
"checking",
"inherited",
"annotations",
"as",
"well",
".",
"The",
"matching",
"logic",
"mirrors",
"that",
"of",
"Class",
".",
"isAnnotationPresent",
"()",
".",
"@author",
"Mark",
"Fisher",
"@author",
"Ramnivas",
"Laddad",
"@author",
"Juergen",
"Hoeller",
"@since",
"2",
".",
"5"
] | private class AnnotationTypeFilter extends AbstractTypeHierarchyTraversingFilter {
private final Class<? extends Annotation> annotationType;
private final boolean considerMetaAnnotations;
/**
* Create a new AnnotationTypeFilter for the given annotation type. This filter will also match meta-annotations. To
* disable the meta-annotation matching, use the constructor that accepts a ' <code>considerMetaAnnotations</code>'
* argument. The filter will not match interfaces.
*
* @param annotationType the annotation type to match
*/
// public AnnotationTypeFilter(Class<? extends Annotation> annotationType) {
// this(annotationType, true);
// }
/**
* Create a new AnnotationTypeFilter for the given annotation type. The filter will not match interfaces.
*
* @param annotationType the annotation type to match
* @param considerMetaAnnotations whether to also match on meta-annotations
*/
// public AnnotationTypeFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations) {
// this(annotationType, considerMetaAnnotations, false);
// }
/**
* Create a new {@link AnnotationTypeFilter} for the given annotation type.
*
* @param annotationType the annotation type to match
* @param considerMetaAnnotations whether to also match on meta-annotations
* @param considerInterfaces whether to also match interfaces
*/
public AnnotationTypeFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations,
boolean considerInterfaces) {
super(annotationType.isAnnotationPresent(Inherited.class), considerInterfaces);
this.annotationType = annotationType;
this.considerMetaAnnotations = considerMetaAnnotations;
}
@Override
protected boolean matchSelf(MetadataReader metadataReader) {
AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
return metadata.hasAnnotation(this.annotationType.getName())
|| (this.considerMetaAnnotations && metadata.hasMetaAnnotation(this.annotationType.getName()));
}
@Override
protected Boolean matchSuperClass(String superClassName) {
if (Object.class.getName().equals(superClassName)) {
return Boolean.FALSE;
} else if (superClassName.startsWith("java.")) {
try {
Class<?> clazz = getClass().getClassLoader().loadClass(superClassName);
return (clazz.getAnnotation(this.annotationType) != null);
} catch (ClassNotFoundException ex) {
// Class not found - can't determine a match that way.
}
}
return null;
}
} | [
"private",
"class",
"AnnotationTypeFilter",
"extends",
"AbstractTypeHierarchyTraversingFilter",
"{",
"private",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
";",
"private",
"final",
"boolean",
"considerMetaAnnotations",
";",
"/**\n * Create a new AnnotationTypeFilter for the given annotation type. This filter will also match meta-annotations. To\n * disable the meta-annotation matching, use the constructor that accepts a ' <code>considerMetaAnnotations</code>'\n * argument. The filter will not match interfaces.\n * \n * @param annotationType the annotation type to match\n */",
"/**\n * Create a new AnnotationTypeFilter for the given annotation type. The filter will not match interfaces.\n * \n * @param annotationType the annotation type to match\n * @param considerMetaAnnotations whether to also match on meta-annotations\n */",
"/**\n * Create a new {@link AnnotationTypeFilter} for the given annotation type.\n * \n * @param annotationType the annotation type to match\n * @param considerMetaAnnotations whether to also match on meta-annotations\n * @param considerInterfaces whether to also match interfaces\n */",
"public",
"AnnotationTypeFilter",
"(",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
",",
"boolean",
"considerMetaAnnotations",
",",
"boolean",
"considerInterfaces",
")",
"{",
"super",
"(",
"annotationType",
".",
"isAnnotationPresent",
"(",
"Inherited",
".",
"class",
")",
",",
"considerInterfaces",
")",
";",
"this",
".",
"annotationType",
"=",
"annotationType",
";",
"this",
".",
"considerMetaAnnotations",
"=",
"considerMetaAnnotations",
";",
"}",
"@",
"Override",
"protected",
"boolean",
"matchSelf",
"(",
"MetadataReader",
"metadataReader",
")",
"{",
"AnnotationMetadata",
"metadata",
"=",
"metadataReader",
".",
"getAnnotationMetadata",
"(",
")",
";",
"return",
"metadata",
".",
"hasAnnotation",
"(",
"this",
".",
"annotationType",
".",
"getName",
"(",
")",
")",
"||",
"(",
"this",
".",
"considerMetaAnnotations",
"&&",
"metadata",
".",
"hasMetaAnnotation",
"(",
"this",
".",
"annotationType",
".",
"getName",
"(",
")",
")",
")",
";",
"}",
"@",
"Override",
"protected",
"Boolean",
"matchSuperClass",
"(",
"String",
"superClassName",
")",
"{",
"if",
"(",
"Object",
".",
"class",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"superClassName",
")",
")",
"{",
"return",
"Boolean",
".",
"FALSE",
";",
"}",
"else",
"if",
"(",
"superClassName",
".",
"startsWith",
"(",
"\"",
"java.",
"\"",
")",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"clazz",
"=",
"getClass",
"(",
")",
".",
"getClassLoader",
"(",
")",
".",
"loadClass",
"(",
"superClassName",
")",
";",
"return",
"(",
"clazz",
".",
"getAnnotation",
"(",
"this",
".",
"annotationType",
")",
"!=",
"null",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"ex",
")",
"{",
"}",
"}",
"return",
"null",
";",
"}",
"}"
] | A simple filter which matches classes with a given annotation, checking inherited annotations as well. | [
"A",
"simple",
"filter",
"which",
"matches",
"classes",
"with",
"a",
"given",
"annotation",
"checking",
"inherited",
"annotations",
"as",
"well",
"."
] | [
"// public AnnotationTypeFilter(Class<? extends Annotation> annotationType) {",
"// this(annotationType, true);",
"// }",
"// public AnnotationTypeFilter(Class<? extends Annotation> annotationType, boolean considerMetaAnnotations) {",
"// this(annotationType, considerMetaAnnotations, false);",
"// }",
"// Class not found - can't determine a match that way."
] | [
{
"param": "AbstractTypeHierarchyTraversingFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractTypeHierarchyTraversingFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9ce029502f0e08407cb515c0c90787e036cdac6 | hiya492/spring | modules/sbe-rest/sbe-rest-core/src/main/java/org/springbyexample/mvc/method/annotation/RestServiceComponentProvider.java | [
"Apache-2.0"
] | Java | AllTypeFilter | /**
* Helper class to create a {@link TypeFilter} that matches if all the delegates match.
*
* @author Oliver Gierke
*/ | Helper class to create a TypeFilter that matches if all the delegates match.
@author Oliver Gierke | [
"Helper",
"class",
"to",
"create",
"a",
"TypeFilter",
"that",
"matches",
"if",
"all",
"the",
"delegates",
"match",
".",
"@author",
"Oliver",
"Gierke"
] | private class AllTypeFilter implements TypeFilter {
private final List<TypeFilter> delegates;
/**
* Creates a new {@link AllTypeFilter} to match if all the given delegates match.
*
* @param delegates must not be {@literal null}.
*/
public AllTypeFilter(List<TypeFilter> delegates) {
Assert.notNull(delegates);
this.delegates = delegates;
}
/*
* (non-Javadoc)
* @see org.springframework.core.type.filter.TypeFilter#match(org.springframework.core.type.classreading.MetadataReader, org.springframework.core.type.classreading.MetadataReaderFactory)
*/
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
for (TypeFilter filter : delegates) {
if (!filter.match(metadataReader, metadataReaderFactory)) {
return false;
}
}
return true;
}
} | [
"private",
"class",
"AllTypeFilter",
"implements",
"TypeFilter",
"{",
"private",
"final",
"List",
"<",
"TypeFilter",
">",
"delegates",
";",
"/**\n * Creates a new {@link AllTypeFilter} to match if all the given delegates match.\n * \n * @param delegates must not be {@literal null}.\n */",
"public",
"AllTypeFilter",
"(",
"List",
"<",
"TypeFilter",
">",
"delegates",
")",
"{",
"Assert",
".",
"notNull",
"(",
"delegates",
")",
";",
"this",
".",
"delegates",
"=",
"delegates",
";",
"}",
"/* \n * (non-Javadoc)\n * @see org.springframework.core.type.filter.TypeFilter#match(org.springframework.core.type.classreading.MetadataReader, org.springframework.core.type.classreading.MetadataReaderFactory)\n */",
"public",
"boolean",
"match",
"(",
"MetadataReader",
"metadataReader",
",",
"MetadataReaderFactory",
"metadataReaderFactory",
")",
"throws",
"IOException",
"{",
"for",
"(",
"TypeFilter",
"filter",
":",
"delegates",
")",
"{",
"if",
"(",
"!",
"filter",
".",
"match",
"(",
"metadataReader",
",",
"metadataReaderFactory",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"}"
] | Helper class to create a {@link TypeFilter} that matches if all the delegates match. | [
"Helper",
"class",
"to",
"create",
"a",
"{",
"@link",
"TypeFilter",
"}",
"that",
"matches",
"if",
"all",
"the",
"delegates",
"match",
"."
] | [] | [
{
"param": "TypeFilter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "TypeFilter",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b9d10b26e263f62d42e97dcd9479a503fa940906 | klboke/p6spy | src/test/java/com/p6spy/engine/spy/appender/P6TestLogger.java | [
"Apache-2.0"
] | Java | P6TestLogger | /**
* {@link FileLogger} extension capable of keeping history of log messages as well as the last
* Stacktrace.<br>
* <br>
*
*
* @author peterb
*/ | FileLogger extension capable of keeping history of log messages as well as the last
Stacktrace.
@author peterb | [
"FileLogger",
"extension",
"capable",
"of",
"keeping",
"history",
"of",
"log",
"messages",
"as",
"well",
"as",
"the",
"last",
"Stacktrace",
".",
"@author",
"peterb"
] | public class P6TestLogger extends StdoutLogger {
private List<String> logs = new ArrayList<String>();
private List<Long> times = new ArrayList<Long>();
private String lastStacktrace;
@Override
public void logText(String text) {
if (null != text) {
logs.add(text);
}
super.logText(text);
}
@Override
public void logSQL(int connectionId, String now, long elapsed, Category category, String prepared, String sql, String url) {
super.logSQL(connectionId, now, elapsed, category, prepared, sql, url);
times.add(elapsed);
}
public List<String> getLogs() {
return Collections.unmodifiableList(logs);
}
public void clearLogs() {
clearLogEntries();
}
public String getLastEntry() {
return logs.isEmpty() ? null : logs.get(logs.size() - 1);
}
public Long getLastTimeElapsed() {
return times.isEmpty() ? null : times.get(times.size() - 1);
}
public String getLastButOneEntry() {
return logs.isEmpty() ? null : logs.get(logs.size() - 2);
}
public String getLastStacktrace() {
return lastStacktrace;
}
@Override
public void logException(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
lastStacktrace = sw.toString();
super.logException(e);
}
public void clearLastStacktrace() {
this.lastStacktrace = null;
}
public void clearLogEntries() {
this.logs.clear();
this.times.clear();
}
} | [
"public",
"class",
"P6TestLogger",
"extends",
"StdoutLogger",
"{",
"private",
"List",
"<",
"String",
">",
"logs",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"private",
"List",
"<",
"Long",
">",
"times",
"=",
"new",
"ArrayList",
"<",
"Long",
">",
"(",
")",
";",
"private",
"String",
"lastStacktrace",
";",
"@",
"Override",
"public",
"void",
"logText",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"null",
"!=",
"text",
")",
"{",
"logs",
".",
"add",
"(",
"text",
")",
";",
"}",
"super",
".",
"logText",
"(",
"text",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"logSQL",
"(",
"int",
"connectionId",
",",
"String",
"now",
",",
"long",
"elapsed",
",",
"Category",
"category",
",",
"String",
"prepared",
",",
"String",
"sql",
",",
"String",
"url",
")",
"{",
"super",
".",
"logSQL",
"(",
"connectionId",
",",
"now",
",",
"elapsed",
",",
"category",
",",
"prepared",
",",
"sql",
",",
"url",
")",
";",
"times",
".",
"add",
"(",
"elapsed",
")",
";",
"}",
"public",
"List",
"<",
"String",
">",
"getLogs",
"(",
")",
"{",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"logs",
")",
";",
"}",
"public",
"void",
"clearLogs",
"(",
")",
"{",
"clearLogEntries",
"(",
")",
";",
"}",
"public",
"String",
"getLastEntry",
"(",
")",
"{",
"return",
"logs",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"logs",
".",
"get",
"(",
"logs",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}",
"public",
"Long",
"getLastTimeElapsed",
"(",
")",
"{",
"return",
"times",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"times",
".",
"get",
"(",
"times",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}",
"public",
"String",
"getLastButOneEntry",
"(",
")",
"{",
"return",
"logs",
".",
"isEmpty",
"(",
")",
"?",
"null",
":",
"logs",
".",
"get",
"(",
"logs",
".",
"size",
"(",
")",
"-",
"2",
")",
";",
"}",
"public",
"String",
"getLastStacktrace",
"(",
")",
"{",
"return",
"lastStacktrace",
";",
"}",
"@",
"Override",
"public",
"void",
"logException",
"(",
"Exception",
"e",
")",
"{",
"StringWriter",
"sw",
"=",
"new",
"StringWriter",
"(",
")",
";",
"PrintWriter",
"pw",
"=",
"new",
"PrintWriter",
"(",
"sw",
")",
";",
"e",
".",
"printStackTrace",
"(",
"pw",
")",
";",
"lastStacktrace",
"=",
"sw",
".",
"toString",
"(",
")",
";",
"super",
".",
"logException",
"(",
"e",
")",
";",
"}",
"public",
"void",
"clearLastStacktrace",
"(",
")",
"{",
"this",
".",
"lastStacktrace",
"=",
"null",
";",
"}",
"public",
"void",
"clearLogEntries",
"(",
")",
"{",
"this",
".",
"logs",
".",
"clear",
"(",
")",
";",
"this",
".",
"times",
".",
"clear",
"(",
")",
";",
"}",
"}"
] | {@link FileLogger} extension capable of keeping history of log messages as well as the last
Stacktrace.<br>
<br> | [
"{",
"@link",
"FileLogger",
"}",
"extension",
"capable",
"of",
"keeping",
"history",
"of",
"log",
"messages",
"as",
"well",
"as",
"the",
"last",
"Stacktrace",
".",
"<br",
">",
"<br",
">"
] | [] | [
{
"param": "StdoutLogger",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "StdoutLogger",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |