#Java - Code Snippets for '#Code' - 533 code snippet(s) found |
|
Sample 1. Code Sample / Example / Snippet of org.apache.ace.agent.AgentContext | |
|
protected final AgentContext getAgentContext() {
AgentContext context = m_contextRef.get();
if (context == null) {
throw new IllegalStateException("Handler is not started: " + m_identifier);
}
return context;
}
|
|
Like Feedback org.apache.ace.agent.AgentContext |
|
|
Sample 2. Tricky code for String Comparison and String Pool | |
|
class BuggyBread {
public static void main(String[] args)
{
String s2 = "I am unique!";
String s5 = "I am unique!";
System.out.println(s2 == s5); // prints true
}
}
|
|
Like Feedback tricky code example string string comparison object comparison object equality string equality string pool |
|
|
Sample 3. Tricky Code for Overloading and Overriding | |
|
class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}
class BuggyBread2 extends BuggyBread1{
private static int counter = 0;
public String method(int x) {
return "Derived Class - BuggyBread2";
}
public static void main(String[] args) {
BuggyBread1 bg = new BuggyBread2();
System.out.println(bg.method()); // prints Base Class - BuggyBread1
}
}
|
|
Like Feedback overloading overriding tricky code examples inheritance |
|
|
Sample 4. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalProject | |
|
public RelNode convert(RelNode rel) {
final LogicalProject project = (LogicalProject) rel;
final RelTraitSet traitSet = project.getTraitSet().replace(out);
return new MongoProject(project.getCluster(), traitSet,
convert(project.getInput(), out), project.getProjects(),
project.getRowType());
}
|
|
Like Feedback org.apache.calcite.rel.logical.LogicalProject |
|
|
|
Sample 5. Code Sample / Example / Snippet of org.bouncycastle.asn1.x500.X500Name | |
|
public X509Certificate createCertificate(X500Principal issuerDN, PrivateKey issuerKey, String name, Date notBefore, Date notAfter, PublicKey key) throws IllegalArgumentException {
try {
X500Name issuer = new X500Name(issuerDN.getName());
X500Name commonName = new X500Name(name);
BigInteger serial = BigInteger.valueOf(++m_serial);
SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(key);
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, commonName, pubKeyInfo);
X509CertificateHolder certHolder = builder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(issuerKey));
return new JcaX509CertificateConverter().getCertificate(certHolder);
}
catch (IllegalArgumentException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
|
|
Like Feedback org.bouncycastle.asn1.x500.X500Name |
|
|
Sample 6. Using Pojomatic for overriding equals,hashcode and toString methods | |
|
import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;
@AutoProperty
public class Employee {
public String name;
public int age;
public int salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public int hashCode() {
return Pojomatic.hashCode(this);
}
@Override
public boolean equals(Object other) {
return Pojomatic.equals(this, other);
}
@Override
public String toString() {
return Pojomatic.toString(this);
}
}
|
|
Like Feedback pojomatic toString method toString hashcode method equals method overrding equals method overriding hashcode method overrding tostring method @autoproperty pojomatic autoproperty |
|
|
Sample 7. Code Sample / Example / Snippet of java.text.StringCharacterIterator | |
|
public static String encode(String source) {
if (source == null) {
return "$e";
}
StringBuffer result = new StringBuffer();
StringCharacterIterator sci = new StringCharacterIterator(source);
for (char c = sci.current(); c != CharacterIterator.DONE; c = sci.next()) {
if (c == '$') {
result.append("$$");
}
else if (c == ',') {
result.append("$k");
}
else if (c == '
') {
result.append("$n");
}
else if (c == '
') {
result.append("$r");
}
else {
result.append(c);
}
}
return result.toString();
}
|
|
Like Feedback java.text.StringCharacterIterator |
|
|
Sample 8. Code Sample / Example / Snippet of org.apache.spark.ml.classification.LogisticRegressionModel | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame training = sqlContext.read().format("libsvm")
.load("data/mllib/sample_libsvm_data.txt");
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8);
LogisticRegressionModel lrModel = lr.fit(training);
System.out.println("Coefficients: "
+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.classification.LogisticRegressionModel |
|
|
Sample 9. Code to find email ids in a string using Pattern. | |
|
String text="vivek boy goy vivek@tech.com viv@ek.com sdjs@adjk";
Pattern regex = Pattern.compile("[@]");
Matcher regexMatcher = regex.matcher(text);
int i =0;
int width = 0;
while (regexMatcher.find()) {
if((regexMatcher.start()-10 > 0) && (regexMatcher.end()+10 < text.length())){
width=10;
String[] substr=text.substring(regexMatcher.start()-width,regexMatcher.end()+width).split(" ");
for(int j=0;j<substr.length;j++){
if(substr[j].contains("@") && (substr[j].contains(".com") || substr[j].contains(".net"))){
System.out.println(substr[j]);
}
}
} else {
width=0;
}
}
|
|
Like Feedback regex pattern string regexMatcher.find java.util.regex.Matcher java.util.regex.Pattern |
|
|
|
Sample 10. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor.BlockTargetPair | |
|
public BlockCommand(int action, List<BlockTargetPair> blocktargetlist) {
super(action);
blocks = new Block[blocktargetlist.size()];
targets = new DatanodeInfo[blocks.length][];
for(int i = 0; i < blocks.length; i++) {
BlockTargetPair p = blocktargetlist.get(i);
blocks[i] = p.block;
targets[i] = p.targets;
}
}
|
|
Like Feedback org.apache.hadoop.hdfs.server.namenode.DatanodeDescriptor.BlockTargetPair |
|
|
Sample 11. Code Sample / Example / Snippet of org.apache.hadoop.io.ObjectWritable | |
|
public void readFields(DataInput in) throws IOException {
methodName = UTF8.readString(in);
parameters = new Object[in.readInt()];
parameterClasses = new Class[parameters.length];
ObjectWritable objectWritable = new ObjectWritable();
for (int i = 0; i < parameters.length; i++) {
parameters[i] = ObjectWritable.readObject(in, objectWritable, this.conf);
parameterClasses[i] = objectWritable.getDeclaredClass();
}
}
|
|
Like Feedback org.apache.hadoop.io.ObjectWritable |
|
|
Sample 12. Code Sample / Example / Snippet of java.util.zip.DeflaterOutputStream | |
|
private byte[] deflate(byte[] b) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(baos);
dos.write(b);
dos.close();
return baos.toByteArray();
}
|
|
Like Feedback java.util.zip.DeflaterOutputStream |
|
|
Sample 13. Code Sample / Example / Snippet of javax.swing.GrayFilter | |
|
public static Image createDisabledImage (Image i) {
GrayFilter filter = new GrayFilter(true, 50);
ImageProducer prod = new FilteredImageSource(i.getSource(), filter);
Image grayImage = Toolkit.getDefaultToolkit().createImage(prod);
return grayImage;
}
|
|
Like Feedback javax.swing.GrayFilter |
|
|
Sample 14. Code Sample / Example / Snippet of java.time.Instant | |
|
public Instant instant() {
if ((tickNanos % 1000_000) == 0) {
long millis = baseClock.millis();
return Instant.ofEpochMilli(millis - Math.floorMod(millis, tickNanos / 1000_000L));
}
Instant instant = baseClock.instant();
long nanos = instant.getNano();
long adjust = Math.floorMod(nanos, tickNanos);
return instant.minusNanos(adjust);
}
|
|
Like Feedback java.time.Instant |
|
|
|
Sample 15. Code Sample / Example / Snippet of java.time.LocalTime | |
|
public static LocalTime from(TemporalAccessor temporal) {
Objects.requireNonNull(temporal, "temporal");
LocalTime time = temporal.query(TemporalQueries.localTime());
if (time == null) {
throw new DateTimeException("Unable to obtain LocalTime from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName());
}
return time;
}
|
|
Like Feedback java.time.LocalTime |
|
|
Sample 16. Code Sample / Example / Snippet of org.apache.spark.TaskContext | |
|
public UnsafeExternalRowSorter(
StructType schema,
Ordering<InternalRow> ordering,
PrefixComparator prefixComparator,
PrefixComputer prefixComputer,
long pageSizeBytes) throws IOException {
this.schema = schema;
this.prefixComputer = prefixComputer;
final SparkEnv sparkEnv = SparkEnv.get();
final TaskContext taskContext = TaskContext.get();
sorter = UnsafeExternalSorter.create(
taskContext.taskMemoryManager(),
sparkEnv.blockManager(),
taskContext,
new RowComparator(ordering, schema.length()),
prefixComparator,
pageSizeBytes
);
}
|
|
Like Feedback org.apache.spark.TaskContext |
|
|
Sample 17. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StopWordsRemover | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaStopWordsRemoverExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
StopWordsRemover remover = new StopWordsRemover()
.setInputCol("raw")
.setOutputCol("filtered");
JavaRDD<Row> rdd = jsc.parallelize(Arrays.asList(
RowFactory.create(Arrays.asList("I", "saw", "the", "red", "baloon")),
RowFactory.create(Arrays.asList("Mary", "had", "a", "little", "lamb"))
));
StructType schema = new StructType(new StructField[]{
new StructField(
"raw", DataTypes.createArrayType(DataTypes.StringType), false, Metadata.empty())
});
DataFrame dataset = jsql.createDataFrame(rdd, schema);
remover.transform(dataset).show();
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.feature.StopWordsRemover |
|
|
Sample 18. Code Sample / Example / Snippet of org.apache.storm.task.OutputCollector | |
|
public void shouldEmitNothingIfNoObjectHasBeenCountedYetAndTickTupleIsReceived() {
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
RollingCountBolt bolt = new RollingCountBolt();
Map conf = mock(Map.class);
TopologyContext context = mock(TopologyContext.class);
OutputCollector collector = mock(OutputCollector.class);
bolt.prepare(conf, context, collector);
bolt.execute(tickTuple);
verifyZeroInteractions(collector);
}
|
|
Like Feedback org.apache.storm.task.OutputCollector |
|
|
Sample 19. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.DistributedLDAModel | |
|
DistributedLDAModel ldaModel = (DistributedLDAModel)new LDA().setK(3).run(corpus);
System.out.println("Learned topics (as distributions over vocab of " + ldaModel.vocabSize() + " words):");
Matrix topics = ldaModel.topicsMatrix(); for (int topic = 0; topic < 3; topic++) {
|
|
Like Feedback org.apache.spark.mllib.clustering.DistributedLDAModel |
|
|
|
Sample 20. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleClient | |
|
private void validate(String appId, String secretKey, boolean encrypt) throws IOException {
ExternalShuffleClient client =
new ExternalShuffleClient(conf, new TestSecretKeyHolder(appId, secretKey), true, encrypt);
client.init(appId);
client.registerWithShuffleServer(TestUtils.getLocalHost(), server.getPort(), "exec0",
new ExecutorShuffleInfo(new String[0], 0, ""));
client.close();
}
|
|
Like Feedback org.apache.spark.network.shuffle.ExternalShuffleClient |
|
|
Sample 21. Code Sample / Example / Snippet of org.apache.spark.network.client.TransportResponseHandler | |
|
public void handleSuccessfulFetch() throws Exception {
StreamChunkId streamChunkId = new StreamChunkId(1, 0);
TransportResponseHandler handler = new TransportResponseHandler(new LocalChannel());
ChunkReceivedCallback callback = mock(ChunkReceivedCallback.class);
handler.addFetchRequest(streamChunkId, callback);
assertEquals(1, handler.numOutstandingRequests());
handler.handle(new ChunkFetchSuccess(streamChunkId, new TestManagedBuffer(123)));
verify(callback, times(1)).onSuccess(eq(0), (ManagedBuffer) any());
assertEquals(0, handler.numOutstandingRequests());
}
|
|
Like Feedback org.apache.spark.network.client.TransportResponseHandler |
|
|
Sample 22. Code Sample / Example / Snippet of org.apache.storm.tuple.Tuple | |
|
public void shouldEmitSomethingIfTickTupleIsReceived() {
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
BasicOutputCollector collector = mock(BasicOutputCollector.class);
TotalRankingsBolt bolt = new TotalRankingsBolt();
bolt.execute(tickTuple, collector);
verify(collector).emit(any(Values.class));
}
|
|
Like Feedback org.apache.storm.tuple.Tuple |
|
|
Sample 23. Code Sample / Example / Snippet of org.apache.storm.tuple.Fields | |
|
public static StormTopology buildDevicesTopology() {
String deviceID = "device-id";
String count = "count";
Fields allFields = new Fields(deviceID, count);
RandomNumberGeneratorSpout spout = new RandomNumberGeneratorSpout(allFields, 10, 1000);
TridentTopology topology = new TridentTopology();
Stream devicesStream = topology.newStream("devicegen-spout", spout).
each(allFields, new Debug("##### devices"));
devicesStream.minBy(deviceID).
each(allFields, new Debug("#### device with min id"));
devicesStream.maxBy(count).
each(allFields, new Debug("#### device with max count"));
return topology.build();
}
|
|
Like Feedback org.apache.storm.tuple.Fields |
|
|
Sample 24. Code Sample / Example / Snippet of java.sql.ResultSetMetaData | |
|
private void output(ResultSet resultSet, PrintStream out)
throws SQLException {
final ResultSetMetaData metaData = resultSet.getMetaData();
final int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
for (int i = 1;; i++) {
out.print(resultSet.getString(i));
if (i < columnCount) {
out.print(", ");
} else {
out.println();
break;
}
}
}
}
|
|
Like Feedback java.sql.ResultSetMetaData |
|
|
|
Sample 25. Code Sample / Example / Snippet of java.util.zip.GZIPInputStream | |
|
private static CSVReader openCsv(File file) throws IOException {
final Reader fileReader;
if (file.getName().endsWith(".gz")) {
final GZIPInputStream inputStream =
new GZIPInputStream(new FileInputStream(file));
fileReader = new InputStreamReader(inputStream);
} else {
fileReader = new FileReader(file);
}
return new CSVReader(fileReader);
}
|
|
Like Feedback java.util.zip.GZIPInputStream |
|
|
Sample 26. Code Sample / Example / Snippet of org.apache.calcite.rel.metadata.RelMetadataQuery | |
|
public static PhysProj create(final RelNode input,
final List<RexNode> projects, RelDataType rowType) {
final RelOptCluster cluster = input.getCluster();
final RelMetadataQuery mq = RelMetadataQuery.instance();
final RelTraitSet traitSet =
cluster.traitSet().replace(PHYSICAL)
.replaceIfs(
RelCollationTraitDef.INSTANCE,
new Supplier<List<RelCollation>>() {
public List<RelCollation> get() {
return RelMdCollation.project(mq, input, projects);
}
});
return new PhysProj(cluster, traitSet, input, projects, rowType);
}
|
|
Like Feedback org.apache.calcite.rel.metadata.RelMetadataQuery |
|
|
Sample 27. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlCollation | |
|
public void checkCollation(
String expression,
String expectedCollationName,
SqlCollation.Coercibility expectedCoercibility) {
for (String sql : buildQueries(expression)) {
RelDataType actualType = getColumnType(sql);
SqlCollation collation = actualType.getCollation();
assertEquals(
expectedCollationName, collation.getCollationName());
assertEquals(expectedCoercibility, collation.getCoercibility());
}
}
|
|
Like Feedback org.apache.calcite.sql.SqlCollation |
|
|
Sample 28. Code Sample / Example / Snippet of com.google.common.base.Joiner | |
|
public static void assertArrayEqual(
String message, Object[] expected, Object[] actual) {
Joiner joiner = Joiner.on(' ');
String strExpected = expected == null ? null : joiner.join(expected);
String strActual = actual == null ? null : joiner.join(actual);
assertEquals(message, strExpected, strActual);
}
|
|
Like Feedback com.google.common.base.Joiner ternary operator joiner.join assertEquals |
|
|
Sample 29. Code Sample / Example / Snippet of java.util.Properties | |
|
public Connection createConnection() throws SQLException {
final Properties info = new Properties();
for (Map.Entry<String, String> entry : map.entrySet()) {
info.setProperty(entry.getKey(), entry.getValue());
}
Connection connection =
DriverManager.getConnection("jdbc:calcite:", info);
for (ConnectionPostProcessor postProcessor : postProcessors) {
connection = postProcessor.apply(connection);
}
return connection;
}
|
|
Like Feedback java.util.Properties |
|
|
|
Sample 30. Code Sample / Example / Snippet of java.security.KeyStore | |
|
public SSLContextBuilder loadTrustMaterial(
final File file,
final char[] storePassword,
final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
Args.notNull(file, "Truststore file");
final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
final FileInputStream instream = new FileInputStream(file);
try {
trustStore.load(instream, storePassword);
} finally {
instream.close();
}
return loadTrustMaterial(trustStore, trustStrategy);
}
|
|
Like Feedback java.security.KeyStore |
|
|
Sample 31. Code Sample / Example / Snippet of org.apache.hc.core5.http.protocol.RequestValidateHost | |
|
public void testRequestHttp11HostHeaderPresent() throws Exception {
final HttpContext context = new BasicHttpContext(null);
final BasicHttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);
request.setHeader(HttpHeaders.HOST, "blah");
final RequestValidateHost interceptor = new RequestValidateHost();
interceptor.process(request, context);
}
|
|
Like Feedback org.apache.hc.core5.http.protocol.RequestValidateHost |
|
|
Sample 32. Code Sample / Example / Snippet of java.lang.reflect.Field | |
|
public Object getDeclaredField(Class targetClass, String name, Object target)
throws Exception
{
if (System.getSecurityManager() != null)
{
Actions actions = (Actions) m_actions.get();
actions.set(Actions.GET_FIELD_ACTION, targetClass, name, target);
try
{
return AccessController.doPrivileged(actions, m_acc);
}
catch (PrivilegedActionException e)
{
throw e.getException();
}
}
else
{
Field field = targetClass.getDeclaredField(name);
field.setAccessible(true);
return field.get(target);
}
}
|
|
Like Feedback java.lang.reflect.Field |
|
|
Sample 33. Code Sample / Example / Snippet of org.apache.felix.framework.wiring.BundleRequirementImpl | |
|
private static List<BundleRevision> getResolvedSingletons(ResolverState state)
{
BundleRequirementImpl req = new BundleRequirementImpl(
null,
BundleCapabilityImpl.SINGLETON_NAMESPACE,
Collections.EMPTY_MAP,
Collections.EMPTY_MAP);
SortedSet<BundleCapability> caps = state.getCandidates(req, true);
List<BundleRevision> singletons = new ArrayList<>();
for (BundleCapability cap : caps)
{
if (cap.getRevision().getWiring() != null)
{
singletons.add(cap.getRevision());
}
}
return singletons;
}
|
|
Like Feedback org.apache.felix.framework.wiring.BundleRequirementImpl |
|
|
Sample 34. Code Sample / Example / Snippet of java.security.KeyStore | |
|
private KeyManager[] getKeyManagerFactory(String keystoreFile, String storePass) throws IOException, GeneralSecurityException {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
InputStream is = null;
try {
is = new FileInputStream(keystoreFile);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(is, storePass.toCharArray());
kmf.init(ks, storePass.toCharArray());
return kmf.getKeyManagers();
}
finally {
try {
if (is != null) {
is.close();
}
}
catch (IOException e) {
}
}
}
|
|
Like Feedback java.security.KeyStore |
|
|
|
Sample 35. Code Sample / Example / Snippet of java.util.jar.JarOutputStream | |
|
private File createBundle(String symbolicName, String version) throws IOException {
File tmpFile = File.createTempFile("tmpbundle-", "jar");
tmpFile.deleteOnExit();
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
if (symbolicName != null) {
manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, symbolicName);
}
if (version != null) {
manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version);
}
JarOutputStream target = new JarOutputStream(new FileOutputStream(tmpFile), manifest);
target.close();
return tmpFile;
}
|
|
Like Feedback java.util.jar.JarOutputStream |
|
|
Sample 36. Code Sample / Example / Snippet of org.apache.ace.agent.AgentControl | |
|
protected void configureProvisionedServices() throws Exception {
String serverURL = String.format("http://localhost:%d/", TestConstants.PORT);
String obrURL = serverURL.concat("obr/");
configure("org.apache.ace.deployment.servlet.agent",
"org.apache.ace.server.servlet.endpoint", "/agent",
"obr.url", obrURL,
"authentication.enabled", "false");
Map<String, String> props = new HashMap<>();
props.put(AgentConstants.CONFIG_DISCOVERY_SERVERURLS, serverURL);
AgentControl agentControl = getService(AgentControl.class);
agentControl.getConfigurationHandler().putAll(props);
}
|
|
Like Feedback org.apache.ace.agent.AgentControl |
|
|
Sample 37. Code Sample / Example / Snippet of java.io.FileOutputStream | |
|
public static void copy(File input, File output) throws IOException {
FileInputStream fis = new FileInputStream(input);
FileOutputStream fos = new FileOutputStream(output);
try {
FileChannel ic = fis.getChannel();
FileChannel oc = fos.getChannel();
try {
oc.transferFrom(ic, 0, ic.size());
}
finally {
oc.close();
ic.close();
}
}
finally {
fis.close();
fos.close();
}
}
|
|
Like Feedback java.io.FileOutputStream |
|
|
Sample 38. Code Sample / Example / Snippet of javax.swing.JTextArea | |
|
private static final String DEFAULT_PROPERTIES_FILE = "QueueMonitor.properties";
String propertiesFile = DEFAULT_PROPERTIES_FILE;
String broker = "tcp://localhost:61616";
String connectID = "QueueMonitor";
String username = "QueueMonitor";
String password = "QueueMonitor";
String browseQueues = "Q1,Q2,Q3";
String textFontName = "Dialog";
String textFontStyle = "PLAIN";
String textFontSize = "12";
String title = "QueueMonitor";
JTextArea textArea = new JTextArea();
|
|
Like Feedback javax.swing.JTextArea |
|
|
Sample 39. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationEntry | |
|
protected String dumpAnnotationEntries(final AnnotationEntry[] as)
{
final StringBuilder result = new StringBuilder();
result.append("[");
for (int i = 0; i < as.length; i++)
{
final AnnotationEntry annotation = as[i];
result.append(annotation.toShortString());
if (i + 1 < as.length) {
result.append(",");
}
}
result.append("]");
return result.toString();
}
|
|
Like Feedback org.apache.bcel.classfile.AnnotationEntry |
|
|
|
Sample 40. Code Sample / Example / Snippet of org.apache.bcel.generic.ConstantPoolGen | |
|
public void testCreateIntegerElementValue() throws Exception
{
final ClassGen cg = createClassGen("HelloWorld");
final ConstantPoolGen cp = cg.getConstantPool();
final SimpleElementValueGen evg = new SimpleElementValueGen(
ElementValueGen.PRIMITIVE_INT, cp, 555);
assertTrue("Should have the same index in the constantpool but "
+ evg.getIndex() + "!=" + cp.lookupInteger(555),
evg.getIndex() == cp.lookupInteger(555));
checkSerialize(evg, cp);
}
|
|
Like Feedback org.apache.bcel.generic.ConstantPoolGen |
|
|
Sample 41. Code Sample / Example / Snippet of org.apache.bcel.generic.Type | |
|
Type t = BasicType.getType((byte)idents[i].getType());
LocalVariableGen lg = method.addLocalVariable(ident, t, null, null);
int slot = lg.getIndex();
entry.setLocalVariable(lg);
InstructionHandle start = il.getEnd();
exprs[i].byte_code(il, method, cp);
start = (start == null)? il.getStart() : start.getNext();
lg.setStart(start);
il.append(new ISTORE(slot)); ASTFunDecl.pop();
l[i] = lg;
|
|
Like Feedback org.apache.bcel.generic.Type |
|
|
Sample 42. Code Sample / Example / Snippet of org.apache.bcel.classfile.Deprecated | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final Deprecated c = (Deprecated) clone();
if (bytes != null) {
c.bytes = new byte[bytes.length];
System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.Deprecated |
|
|
Sample 43. Code Sample / Example / Snippet of org.apache.bcel.classfile.Field | |
|
public void visitGETSTATIC(final GETSTATIC o) {
try {
final String field_name = o.getFieldName(cpg);
final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
final Field[] fields = jc.getFields();
Field f = null;
for (final Field field : fields) {
if (field.getName().equals(field_name)) {
f = field;
break;
}
}
if (f == null) {
throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
}
if (! (f.isStatic())) {
constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
}
} catch (final ClassNotFoundException e) {
throw new AssertionViolatedException("Missing class: " + e, e);
}
}
|
|
Like Feedback org.apache.bcel.classfile.Field |
|
|
Sample 44. Java Code to get all images url from html code. | |
|
regex = Pattern.compile("[http]");
regexMatcher = regex.matcher(htmlParseData.getHtml());
List tr=htmlParseData.getOutgoingUrls();
imgUrlCounter=0;
for(i=0;i<tr.size();i++){
if(tr.get(i).toString().contains(".jpg") || tr.get(i).toString().contains(".jpeg") || tr.get(i).toString().contains(".gif") || tr.get(i).toString().contains(".bmp")){
url = new URL(tr.get(i).toString());
Image image = new ImageIcon(url).getImage();
}
}
|
|
Like Feedback regex pattern regex.matcher html java.util.regex.pattern regular expressions |
|
|
|
Sample 45. Card Number Validation using CodeValidator and RegexValidator | |
|
String CARD_REGEX = "^(5[1-5]d{2})(?:[- ])?(d{4})(?:[- ])?(d{4})(?:[- ])?(d{4})$";
CodeValidator validator = new CodeValidator(CARD_REGEX, LuhnCheckDigit.LUHN_CHECK_DIGIT);
RegexValidator regex = validator.getRegexValidator();
|
|
Like Feedback Card Number Validation Apache Commons CodeValidator LuhnCheckDigit.LUHN_CHECK_DIGIT RegexValidator |
|
|
Sample 46. Code Sample / Example / Snippet of org.apache.hadoop.util.Daemon | |
|
public static void main(String[] argv) throws Exception {
StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);
Configuration tconf = new Configuration();
if (argv.length >= 1) {
SecondaryNameNode secondary = new SecondaryNameNode(tconf);
int ret = secondary.processArgs(argv);
System.exit(ret);
}
Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));
checkpointThread.start();
}
|
|
Like Feedback org.apache.hadoop.util.Daemon |
|
|
Sample 47. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.namenode.NameNode | |
|
protected ClientProtocol createNameNodeProxy(UnixUserGroupInformation ugi
) throws IOException {
ServletContext context = getServletContext();
NameNode nn = (NameNode)context.getAttribute("name.node");
Configuration conf = new Configuration(
(Configuration)context.getAttribute("name.conf"));
UnixUserGroupInformation.saveToConf(conf,
UnixUserGroupInformation.UGI_PROPERTY_NAME, ugi);
return DFSClient.createNamenode(nn.getNameNodeAddress(), conf);
}
|
|
Like Feedback org.apache.hadoop.hdfs.server.namenode.NameNode |
|
|
Sample 48. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.namenode.FSNamesystem | |
|
private void doMerge(CheckpointSignature sig) throws IOException {
FSNamesystem namesystem =
new FSNamesystem(checkpointImage, conf);
assert namesystem.dir.fsImage == checkpointImage;
checkpointImage.doMerge(sig);
}
|
|
Like Feedback org.apache.hadoop.hdfs.server.namenode.FSNamesystem |
|
|
Sample 49. Code Sample / Example / Snippet of org.apache.hadoop.fs.FileStatus | |
|
public synchronized void setPermission(String src, FsPermission permission
) throws IOException {
checkOwner(src);
dir.setPermission(src, permission);
getEditLog().logSync();
if (auditLog.isInfoEnabled()) {
final FileStatus stat = dir.getFileInfo(src);
logAuditEvent(UserGroupInformation.getCurrentUGI(),
Server.getRemoteIp(),
"setPermission", src, null, stat);
}
}
|
|
Like Feedback org.apache.hadoop.fs.FileStatus |
|
|
|
Sample 50. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.protocol.Block | |
|
private Block allocateBlock(String src, INode[] inodes) throws IOException {
Block b = null;
do {
b = new Block(FSNamesystem.randBlockId.nextLong(), 0,
getGenerationStamp());
} while (isValidBlock(b));
b = dir.addBlock(src, inodes, b);
NameNode.stateChangeLog.info("BLOCK* NameSystem.allocateBlock: "
+src+ ". "+b);
return b;
}
|
|
Like Feedback org.apache.hadoop.hdfs.protocol.Block |
|
|
Sample 51. Code Sample / Example / Snippet of javax.rmi.CORBA.ValueHandler | |
|
public synchronized IOR getFVDCodeBaseIOR()
{
checkShutdownState();
if (codeBaseIOR != null) // i.e. We are already connected to it
return codeBaseIOR;
CodeBase cb;
ValueHandler vh = ORBUtility.createValueHandler();
cb = (CodeBase)vh.getRunTimeCodeBase();
return ORBUtility.connectAndGetIOR( this, cb ) ;
}
|
|
Like Feedback javax.rmi.CORBA.ValueHandler |
|
|
Sample 52. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory | |
|
public File getFsEditName() throws IOException {
return getEditLog().getFsEditName();
}
File getFsTimeName() {
StorageDirectory sd = null;
for (Iterator<StorageDirectory> it =
dirIterator(); it.hasNext();)
sd = it.next();
return getImageFile(sd, NameNodeFile.TIME);
}
|
|
Like Feedback org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory |
|
|
Sample 53. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.server.common.UpgradeStatusReport | |
|
public String getUpgradeStatusText() {
String statusText = "";
try {
UpgradeStatusReport status =
fsn.distributedUpgradeProgress(UpgradeAction.GET_STATUS);
statusText = (status == null ?
"There are no upgrades in progress." :
status.getStatusText(false));
} catch(IOException e) {
statusText = "Upgrade status unknown.";
}
return statusText;
}
|
|
Like Feedback org.apache.hadoop.hdfs.server.common.UpgradeStatusReport |
|
|
Sample 54. Code Sample / Example / Snippet of org.apache.hadoop.util.DataChecksum | |
|
private static BlockMetadataHeader readHeader(short version, DataInputStream in)
throws IOException {
DataChecksum checksum = DataChecksum.newDataChecksum(in);
return new BlockMetadataHeader(version, checksum);
}
|
|
Like Feedback org.apache.hadoop.util.DataChecksum |
|
|
|
Sample 55. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.protocol.UnregisteredDatanodeException | |
|
public DatanodeDescriptor getDatanode(DatanodeID nodeID) throws IOException {
UnregisteredDatanodeException e = null;
DatanodeDescriptor node = datanodeMap.get(nodeID.getStorageID());
if (node == null)
return null;
if (!node.getName().equals(nodeID.getName())) {
e = new UnregisteredDatanodeException(nodeID, node);
NameNode.stateChangeLog.fatal("BLOCK* NameSystem.getDatanode: "
+ e.getLocalizedMessage());
throw e;
}
return node;
}
|
|
Like Feedback org.apache.hadoop.hdfs.protocol.UnregisteredDatanodeException |
|
|
Sample 56. Code Sample / Example / Snippet of org.apache.hadoop.hdfs.DistributedFileSystem | |
|
public int metaSave(String[] argv, int idx) throws IOException {
String pathname = argv[idx];
DistributedFileSystem dfs = (DistributedFileSystem) fs;
dfs.metaSave(pathname);
System.out.println("Created file " + pathname + " on server " +
dfs.getUri());
return 0;
}
|
|
Like Feedback org.apache.hadoop.hdfs.DistributedFileSystem |
|
|
Sample 57. Code Sample / Example / Snippet of org.mortbay.jetty.servlet.FilterHolder | |
|
protected void defineFilter(WebApplicationContext ctx, String name,
String classname, Map<String, String> parameters, String[] urls) {
WebApplicationHandler handler = ctx.getWebApplicationHandler();
FilterHolder holder = handler.defineFilter(name, classname);
if (parameters != null) {
for(Map.Entry<String, String> e : parameters.entrySet()) {
holder.setInitParameter(e.getKey(), e.getValue());
}
}
for (String url : urls) {
handler.addFilterPathMapping(url, name, Dispatcher.__ALL);
}
}
|
|
Like Feedback org.mortbay.jetty.servlet.FilterHolder |
|
|
Sample 58. Code Sample / Example / Snippet of org.mortbay.jetty.servlet.WebApplicationHandler | |
|
protected void defineFilter(WebApplicationContext ctx, String name,
String classname, Map<String, String> parameters, String[] urls) {
WebApplicationHandler handler = ctx.getWebApplicationHandler();
FilterHolder holder = handler.defineFilter(name, classname);
if (parameters != null) {
for(Map.Entry<String, String> e : parameters.entrySet()) {
holder.setInitParameter(e.getKey(), e.getValue());
}
}
for (String url : urls) {
handler.addFilterPathMapping(url, name, Dispatcher.__ALL);
}
}
|
|
Like Feedback org.mortbay.jetty.servlet.WebApplicationHandler |
|
|
Sample 59. Code Sample / Example / Snippet of org.apache.hadoop.io.DataOutputBuffer | |
|
private void writeHeader() throws IOException {
out.write(Server.HEADER.array());
out.write(Server.CURRENT_VERSION);
DataOutputBuffer buf = new DataOutputBuffer();
ObjectWritable.writeObject(buf, remoteId.getTicket(),
UserGroupInformation.class, conf);
int bufLen = buf.getLength();
out.writeInt(bufLen);
out.write(buf.getData(), 0, bufLen);
}
|
|
Like Feedback org.apache.hadoop.io.DataOutputBuffer |
|
|
|
Sample 60. Code Sample / Example / Snippet of org.apache.hadoop.security.UserGroupInformation | |
|
public Connection(ConnectionId remoteId) throws IOException {
if (remoteId.getAddress().isUnresolved()) {
throw new UnknownHostException("unknown host: " +
remoteId.getAddress().getHostName());
}
this.remoteId = remoteId;
UserGroupInformation ticket = remoteId.getTicket();
this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " +
remoteId.getAddress().toString() +
" from " + ((ticket==null)?"an unknown user":ticket.getUserName()));
this.setDaemon(true);
}
|
|
Like Feedback org.apache.hadoop.security.UserGroupInformation |
|
|
Sample 61. Code Sample / Example / Snippet of org.apache.hadoop.fs.FileSystem | |
|
public static long getTimestamp(Configuration conf, URI cache)
throws IOException {
FileSystem fileSystem = FileSystem.get(cache, conf);
Path filePath = new Path(cache.getPath());
return fileSystem.getFileStatus(filePath).getModificationTime();
}
|
|
Like Feedback org.apache.hadoop.fs.FileSystem |
|
|
Sample 62. Code Sample / Example / Snippet of org.apache.hadoop.util.Shell.ShellCommandExecutor | |
|
public void runScript(List<String> args, File dir) throws IOException {
ShellCommandExecutor shexec =
new ShellCommandExecutor(args.toArray(new String[0]), dir);
shexec.execute();
int exitCode = shexec.getExitCode();
if (exitCode != 0) {
throw new IOException("Task debug script exit with nonzero status of "
+ exitCode + ".");
}
}
|
|
Like Feedback org.apache.hadoop.util.Shell.ShellCommandExecutor |
|
|
Sample 63. Code Sample / Example / Snippet of java.text.NumberFormat | |
|
public static String getUniqueName(JobConf conf, String name) {
int partition = conf.getInt("mapred.task.partition", -1);
if (partition == -1) {
throw new IllegalArgumentException(
"This method can only be called from within a Job");
}
String taskType = (conf.getBoolean("mapred.task.is.map", true)) ? "m" : "r";
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMinimumIntegerDigits(5);
numberFormat.setGroupingUsed(false);
return name + "-" + taskType + "-" + numberFormat.format(partition);
}
|
|
Like Feedback java.text.NumberFormat |
|
|
Sample 64. Code Sample / Example / Snippet of org.apache.hadoop.fs.FSDataInputStream | |
|
private void init() throws IOException {
if (reader == null) {
FSDataInputStream in = fs.open(file);
in.seek(segmentOffset);
reader = new Reader<K, V>(conf, in, segmentLength, codec);
}
}
|
|
Like Feedback org.apache.hadoop.fs.FSDataInputStream |
|
|
|
Sample 65. Code Sample / Example / Snippet of org.apache.hadoop.fs.BlockLocation | |
|
protected int getBlockIndex(BlockLocation[] blkLocations,
long offset) {
for (int i = 0 ; i < blkLocations.length; i++) {
if ((blkLocations[i].getOffset() <= offset) &&
(offset < blkLocations[i].getOffset() + blkLocations[i].getLength())){
return i;
}
}
BlockLocation last = blkLocations[blkLocations.length -1];
long fileLength = last.getOffset() + last.getLength() -1;
throw new IllegalArgumentException("Offset " + offset +
" is outside of file (0.." +
fileLength + ")");
}
|
|
Like Feedback org.apache.hadoop.fs.BlockLocation |
|
|
Sample 66. Code Sample / Example / Snippet of org.apache.commons.httpclient.HttpMethod | |
|
private static int httpNotification(String uri) throws IOException {
URI url = new URI(uri, false);
HttpClient m_client = new HttpClient();
HttpMethod method = new GetMethod(url.getEscapedURI());
method.setRequestHeader("Accept", "*/*");
return m_client.executeMethod(method);
}
|
|
Like Feedback org.apache.commons.httpclient.HttpMethod |
|
|
Sample 67. Code Sample / Example / Snippet of org.apache.commons.httpclient.HttpClient | |
|
private static int httpNotification(String uri) throws IOException {
URI url = new URI(uri, false);
HttpClient m_client = new HttpClient();
HttpMethod method = new GetMethod(url.getEscapedURI());
method.setRequestHeader("Accept", "*/*");
return m_client.executeMethod(method);
}
|
|
Like Feedback org.apache.commons.httpclient.HttpClient |
|
|
Sample 68. Code Sample / Example / Snippet of org.apache.hadoop.util.MergeSort | |
|
public RawKeyValueIterator sort() {
MergeSort m = new MergeSort(this);
int count = super.count;
if (count == 0) return null;
int [] pointers = super.pointers;
int [] pointersCopy = new int[count];
System.arraycopy(pointers, 0, pointersCopy, 0, count);
m.mergeSort(pointers, pointersCopy, 0, count);
return new MRSortResultIterator(super.keyValBuffer, pointersCopy,
super.startOffsets, super.keyLengths, super.valueLengths);
}
|
|
Like Feedback org.apache.hadoop.util.MergeSort |
|
|
Sample 69. Code Sample / Example / Snippet of org.apache.hadoop.mapred.TaskTracker.TaskInProgress | |
|
public synchronized boolean statusUpdate(TaskAttemptID taskid,
TaskStatus taskStatus)
throws IOException {
TaskInProgress tip = tasks.get(taskid);
if (tip != null) {
tip.reportProgress(taskStatus);
return true;
} else {
LOG.warn("Progress from unknown child task: "+taskid);
return false;
}
}
|
|
Like Feedback org.apache.hadoop.mapred.TaskTracker.TaskInProgress |
|
|
|
Sample 70. Code Sample / Example / Snippet of org.apache.hadoop.mapred.Counters.Counter | |
|
public synchronized void incrAllCounters(Counters other) {
for (Group otherGroup: other) {
Group group = getGroup(otherGroup.getName());
group.displayName = otherGroup.displayName;
for (Counter otherCounter : otherGroup) {
Counter counter = group.getCounterForName(otherCounter.getName());
counter.displayName = otherCounter.displayName;
counter.value += otherCounter.value;
}
}
}
|
|
Like Feedback org.apache.hadoop.mapred.Counters.Counter |
|
|
Sample 71. Code Sample / Example / Snippet of org.apache.hadoop.mapred.Mapper | |
|
public void map(Object key, Object value, OutputCollector output,
Reporter reporter) throws IOException {
Mapper mapper = chain.getFirstMap();
if (mapper != null) {
mapper.map(key, value, chain.getMapperCollector(0, output, reporter),
reporter);
}
}
|
|
Like Feedback org.apache.hadoop.mapred.Mapper |
|
|
Sample 72. Code Sample / Example / Snippet of java.util.StringTokenizer | |
|
public static List<String> getNamedOutputsList(JobConf conf) {
List<String> names = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(conf.get(NAMED_OUTPUTS, ""), " ");
while (st.hasMoreTokens()) {
names.add(st.nextToken());
}
return names;
}
|
|
Like Feedback java.util.StringTokenizer |
|
|
Sample 73. Code Sample / Example / Snippet of org.apache.hadoop.io.serializer.Serialization | |
|
public OutputCollector getMapperCollector(int mapperIndex,
OutputCollector output,
Reporter reporter) {
Serialization keySerialization = mappersKeySerialization.get(mapperIndex);
Serialization valueSerialization =
mappersValueSerialization.get(mapperIndex);
return new ChainOutputCollector(mapperIndex, keySerialization,
valueSerialization, output, reporter);
}
|
|
Like Feedback org.apache.hadoop.io.serializer.Serialization |
|
|
Sample 74. Code Sample / Example / Snippet of org.apache.hadoop.mapred.lib.KeyFieldHelper.KeyDescription | |
|
public void setKeyFieldSpec(int start, int end) {
if (end >= start) {
KeyDescription k = new KeyDescription();
k.beginFieldIdx = start;
k.endFieldIdx = end;
keySpecSeen = true;
allKeySpecs.add(k);
}
}
|
|
Like Feedback org.apache.hadoop.mapred.lib.KeyFieldHelper.KeyDescription |
|
|
|
Sample 75. Code Sample / Example / Snippet of com.sun.corba.se.spi.orb.PropertyParser | |
|
protected PropertyParser makeParser()
{
PropertyParser result = new PropertyParser() ;
for (int ctr=0; ctr<entries.length; ctr++ ) {
ParserData entry = entries[ctr] ;
entry.addToParser( result ) ;
}
return result ;
}
|
|
Like Feedback com.sun.corba.se.spi.orb.PropertyParser |
|
|
Sample 76. Code Sample / Example / Snippet of com.sun.corba.se.spi.orb.Operation | |
|
public PropertyParser makeParser()
{
PropertyParser parser = new PropertyParser() ;
Operation action = OperationFactory.compose(
OperationFactory.suffixAction(),
OperationFactory.classAction()
) ;
parser.addPrefix( ORBConstants.SUN_PREFIX + "ORBUserConfigurators",
action, "userConfigurators", Class.class ) ;
return parser ;
}
|
|
Like Feedback com.sun.corba.se.spi.orb.Operation |
|
|
Sample 77. Code Sample / Example / Snippet of java.util.Calendar | |
|
public static double year()
{
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.YEAR);
}
|
|
Like Feedback java.util.Calendar |
|
|
Sample 78. Code Sample / Example / Snippet of java.text.SimpleDateFormat | |
|
private static String getNameOrAbbrev(String format)
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.ENGLISH);
return dateFormat.format(cal.getTime());
}
|
|
Like Feedback java.text.SimpleDateFormat |
|
|
Sample 79. Code Sample / Example / Snippet of javax.swing.MenuElement | |
|
public MenuElement[] getSelectedPath() {
MenuElement res[] = new MenuElement[selection.size()];
int i,c;
for(i=0,c=selection.size();i<c;i++)
res[i] = selection.elementAt(i);
return res;
}
|
|
Like Feedback javax.swing.MenuElement |
|
|
|
Sample 80. Code Sample / Example / Snippet of java.util.EventListener | |
|
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
listenerList = NULL_ARRAY;
s.defaultReadObject();
Object listenerTypeOrNull;
while (null != (listenerTypeOrNull = s.readObject())) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
EventListener l = (EventListener)s.readObject();
String name = (String) listenerTypeOrNull;
ReflectUtil.checkPackageAccess(name);
add((Class<EventListener>)Class.forName(name, true, cl), l);
}
}
|
|
Like Feedback java.util.EventListener |
|
|
Sample 81. Code Sample / Example / Snippet of java.awt.Polygon | |
|
private Polygon getBorderShape(int side) {
Polygon shape = null;
int[] widths = getWidths();
if (widths[side] != 0) {
shape = new Polygon(new int[4], new int[4], 0);
shape.addPoint(0, 0);
shape.addPoint(-widths[(side + 3) % 4], -widths[side]);
shape.addPoint(widths[(side + 1) % 4], -widths[side]);
shape.addPoint(0, 0);
}
return shape;
}
|
|
Like Feedback java.awt.Polygon |
|
|
Sample 82. Code Sample / Example / Snippet of javax.swing.JEditorPane | |
|
public EditorKit getEditorKitForContentType(String type) {
EditorKit editorKit = super.getEditorKitForContentType(type);
JEditorPane outerMostJEditorPane = null;
if ((outerMostJEditorPane = getOutermostJEditorPane()) != null) {
EditorKit inheritedEditorKit = outerMostJEditorPane.getEditorKitForContentType(type);
if (! editorKit.getClass().equals(inheritedEditorKit.getClass())) {
editorKit = (EditorKit) inheritedEditorKit.clone();
setEditorKitForContentType(type, editorKit);
}
}
return editorKit;
}
|
|
Like Feedback javax.swing.JEditorPane |
|
|
Sample 83. Code Sample / Example / Snippet of javax.naming.CompositeName | |
|
public static void main(String[] args) throws Exception {
CompositeName c = new CompositeName("aaa/bbb");
java.io.FileOutputStream f1 = new java.io.FileOutputStream("/tmp/ser");
java.io.ObjectOutputStream s1 = new java.io.ObjectOutputStream(f1);
s1.writeObject(c);
s1.close();
java.io.FileInputStream f2 = new java.io.FileInputStream("/tmp/ser");
java.io.ObjectInputStream s2 = new java.io.ObjectInputStream(f2);
c = (CompositeName)s2.readObject();
System.out.println("Size: " + c.size());
System.out.println("Size: " + c.snit);
}
|
|
Like Feedback javax.naming.CompositeName |
|
|
Sample 84. Code Sample / Example / Snippet of java.time.zone.ZoneRules | |
|
public static LocalDateTime ofInstant(Instant instant, ZoneId zone) {
Objects.requireNonNull(instant, "instant");
Objects.requireNonNull(zone, "zone");
ZoneRules rules = zone.getRules();
ZoneOffset offset = rules.getOffset(instant);
return ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
}
|
|
Like Feedback java.time.zone.ZoneRules |
|
|
|
Sample 85. Code Sample / Example / Snippet of java.time.temporal.ChronoUnit | |
|
public LocalDateTime plus(long amountToAdd, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
ChronoUnit f = (ChronoUnit) unit;
switch (f) {
case NANOS: return plusNanos(amountToAdd);
case MICROS: return plusDays(amountToAdd / MICROS_PER_DAY).plusNanos((amountToAdd % MICROS_PER_DAY) * 1000);
case MILLIS: return plusDays(amountToAdd / MILLIS_PER_DAY).plusNanos((amountToAdd % MILLIS_PER_DAY) * 1000_000);
case SECONDS: return plusSeconds(amountToAdd);
case MINUTES: return plusMinutes(amountToAdd);
case HOURS: return plusHours(amountToAdd);
case HALF_DAYS: return plusDays(amountToAdd / 256).plusHours((amountToAdd % 256) * 12); // no overflow (256 is multiple of 2)
}
return with(date.plus(amountToAdd, unit), time);
}
return unit.addTo(this, amountToAdd);
}
|
|
Like Feedback java.time.temporal.ChronoUnit |
|
|
Sample 86. Code Sample / Example / Snippet of java.time.zone.ZoneOffsetTransition | |
|
public static ZonedDateTime ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset) {
Objects.requireNonNull(localDateTime, "localDateTime");
Objects.requireNonNull(zone, "zone");
if (zone instanceof ZoneOffset) {
return new ZonedDateTime(localDateTime, (ZoneOffset) zone, zone);
}
ZoneRules rules = zone.getRules();
List<ZoneOffset> validOffsets = rules.getValidOffsets(localDateTime);
ZoneOffset offset;
if (validOffsets.size() == 1) {
offset = validOffsets.get(0);
} else if (validOffsets.size() == 0) {
ZoneOffsetTransition trans = rules.getTransition(localDateTime);
localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());
offset = trans.getOffsetAfter();
} else {
if (preferredOffset != null && validOffsets.contains(preferredOffset)) {
offset = preferredOffset;
} else {
offset = Objects.requireNonNull(validOffsets.get(0), "offset"); // protect against bad ZoneRules
}
}
return new ZonedDateTime(localDateTime, offset, zone);
}
|
|
Like Feedback java.time.zone.ZoneOffsetTransition |
|
|
Sample 87. Code Sample / Example / Snippet of java.time.LocalDateTime | |
|
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof LocalDateTime) {
LocalDateTime other = (LocalDateTime) obj;
return date.equals(other.date) && time.equals(other.time);
}
return false;
}
|
|
Like Feedback java.time.LocalDateTime |
|
|
Sample 88. Code Sample / Example / Snippet of java.time.ZoneOffset | |
|
public static LocalTime now(Clock clock) {
Objects.requireNonNull(clock, "clock");
final Instant now = clock.instant(); // called once
ZoneOffset offset = clock.getZone().getRules().getOffset(now);
long localSecond = now.getEpochSecond() + offset.getTotalSeconds(); // overflow caught later
int secsOfDay = (int) Math.floorMod(localSecond, SECONDS_PER_DAY);
return ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + now.getNano());
}
|
|
Like Feedback java.time.ZoneOffset |
|
|
Sample 89. Code Sample / Example / Snippet of java.time.ZoneId | |
|
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
void writeExternal(DataOutput out) throws IOException {
dateTime.writeExternal(out);
offset.writeExternal(out);
zone.write(out);
}
static ZonedDateTime readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
LocalDateTime dateTime = LocalDateTime.readExternal(in);
ZoneOffset offset = ZoneOffset.readExternal(in);
ZoneId zone = (ZoneId) Ser.read(in);
return ZonedDateTime.ofLenient(dateTime, offset, zone);
}
|
|
Like Feedback java.time.ZoneId |
|
|
|
Sample 90. Code Sample / Example / Snippet of java.time.ZonedDateTime | |
|
public long until(Temporal endExclusive, TemporalUnit unit) {
ZonedDateTime end = ZonedDateTime.from(endExclusive);
if (unit instanceof ChronoUnit) {
end = end.withZoneSameInstant(zone);
if (unit.isDateBased()) {
return dateTime.until(end.dateTime, unit);
} else {
return toOffsetDateTime().until(end.toOffsetDateTime(), unit);
}
}
return unit.between(this, end);
}
|
|
Like Feedback java.time.ZonedDateTime |
|
|
Sample 91. Code Sample / Example / Snippet of java.time.Year | |
|
private ZoneOffsetTransition[] findTransitionArray(int year) {
Integer yearObj = year;
ZoneOffsetTransition[] transArray = lastRulesCache.get(yearObj);
if (transArray != null) {
return transArray;
}
ZoneOffsetTransitionRule[] ruleArray = lastRules;
transArray = new ZoneOffsetTransition[ruleArray.length];
for (int i = 0; i < ruleArray.length; i++) {
transArray[i] = ruleArray[i].createTransition(year);
}
if (year < LAST_CACHED_YEAR) {
lastRulesCache.putIfAbsent(yearObj, transArray);
}
return transArray;
}
|
|
Like Feedback java.time.Year |
|
|
Sample 92. Code Sample / Example / Snippet of java.time.LocalDate | |
|
public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) {
LocalDate date = LocalDate.of(year, month, dayOfMonth);
LocalTime time = LocalTime.of(hour, minute);
return new LocalDateTime(date, time);
}
|
|
Like Feedback java.time.LocalDate |
|
|
Sample 93. Code Sample / Example / Snippet of java.time.Month | |
|
public static LocalDate ofYearDay(int year, int dayOfYear) {
YEAR.checkValidValue(year);
DAY_OF_YEAR.checkValidValue(dayOfYear);
boolean leap = IsoChronology.INSTANCE.isLeapYear(year);
if (dayOfYear == 366 && leap == false) {
throw new DateTimeException("Invalid date 'DayOfYear 366' as '" + year + "' is not a leap year");
}
Month moy = Month.of((dayOfYear - 1) / 31 + 1);
int monthEnd = moy.firstDayOfYear(leap) + moy.length(leap) - 1;
if (dayOfYear > monthEnd) {
moy = moy.plus(1);
}
int dom = dayOfYear - moy.firstDayOfYear(leap) + 1;
return new LocalDate(year, moy.getValue(), dom);
}
|
|
Like Feedback java.time.Month |
|
|
Sample 94. Code Sample / Example / Snippet of java.time.Period | |
|
public Period plus(TemporalAmount amountToAdd) {
Period isoAmount = Period.from(amountToAdd);
return create(
Math.addExact(years, isoAmount.years),
Math.addExact(months, isoAmount.months),
Math.addExact(days, isoAmount.days));
}
|
|
Like Feedback java.time.Period |
|
|
|
Sample 95. Code Sample / Example / Snippet of java.time.chrono.Chronology | |
|
public ChronoLocalDate resolve(
Map<TemporalField, Long> fieldValues, TemporalAccessor partialTemporal, ResolverStyle resolverStyle) {
long value = fieldValues.remove(this);
Chronology chrono = Chronology.from(partialTemporal);
if (resolverStyle == ResolverStyle.LENIENT) {
return chrono.dateEpochDay(Math.subtractExact(value, offset));
}
range().checkValidValue(value, this);
return chrono.dateEpochDay(value - offset);
}
|
|
Like Feedback java.time.chrono.Chronology |
|
|
Sample 96. Code Sample / Example / Snippet of java.time.temporal.ValueRange | |
|
private int localizedWeekBasedYear(TemporalAccessor temporal) {
int dow = localizedDayOfWeek(temporal);
int year = temporal.get(YEAR);
int doy = temporal.get(DAY_OF_YEAR);
int offset = startOfWeekOffset(doy, dow);
int week = computeWeek(offset, doy);
if (week == 0) {
return year - 1;
} else {
ValueRange dayRange = temporal.range(DAY_OF_YEAR);
int yearLen = (int)dayRange.getMaximum();
int newYearWeek = computeWeek(offset, yearLen + weekDef.getMinimalDaysInFirstWeek());
if (week >= newYearWeek) {
return year + 1;
}
}
return year;
}
|
|
Like Feedback java.time.temporal.ValueRange |
|
|
Sample 97. Code Sample / Example / Snippet of org.apache.spark.sql.expressions.UserDefinedAggregateFunction | |
|
public void testUDAF() {
DataFrame df = hc.range(0, 100).unionAll(hc.range(0, 100)).select(col("id").as("value"));
UserDefinedAggregateFunction udaf = new MyDoubleSum();
UserDefinedAggregateFunction registeredUDAF = hc.udf().register("mydoublesum", udaf);
DataFrame aggregatedDF =
df.groupBy()
.agg(
udaf.distinct(col("value")),
udaf.apply(col("value")),
registeredUDAF.apply(col("value")),
callUDF("mydoublesum", col("value")));
List<Row> expectedResult = new ArrayList<>();
expectedResult.add(RowFactory.create(4950.0, 9900.0, 9900.0, 9900.0));
checkAnswer(
aggregatedDF,
expectedResult);
}
|
|
Like Feedback org.apache.spark.sql.expressions.UserDefinedAggregateFunction |
|
|
Sample 98. Code Sample / Example / Snippet of org.apache.spark.SparkEnv | |
|
public UnsafeExternalRowSorter(
StructType schema,
Ordering<InternalRow> ordering,
PrefixComparator prefixComparator,
PrefixComputer prefixComputer,
long pageSizeBytes) throws IOException {
this.schema = schema;
this.prefixComputer = prefixComputer;
final SparkEnv sparkEnv = SparkEnv.get();
final TaskContext taskContext = TaskContext.get();
sorter = UnsafeExternalSorter.create(
taskContext.taskMemoryManager(),
sparkEnv.blockManager(),
taskContext,
new RowComparator(ordering, schema.length()),
prefixComparator,
pageSizeBytes
);
}
|
|
Like Feedback org.apache.spark.SparkEnv |
|
|
Sample 99. Code Sample / Example / Snippet of org.apache.spark.sql.catalyst.expressions.UnsafeRow | |
|
public UnsafeRow next() {
try {
sortedIterator.loadNext();
row.pointTo(
sortedIterator.getBaseObject(),
sortedIterator.getBaseOffset(),
numFields,
sortedIterator.getRecordLength());
if (!hasNext()) {
UnsafeRow copy = row.copy(); // so that we don't have dangling pointers to freed page
row = null; // so that we don't keep references to the base object
cleanupResources();
return copy;
} else {
return row;
}
} catch (IOException e) {
cleanupResources();
Platform.throwException(e);
}
throw new RuntimeException("Exception should have been re-thrown in next()");
};
|
|
Like Feedback org.apache.spark.sql.catalyst.expressions.UnsafeRow |
|
|
|
Sample 100. Code Sample / Example / Snippet of org.apache.spark.sql.Row | |
|
public List<String> getD() {
return d;
}
}
void validateDataFrameWithBeans(Bean bean, DataFrame df) {
StructType schema = df.schema();
Assert.assertEquals(new StructField("a", DoubleType$.MODULE$, false, Metadata.empty()),
schema.apply("a"));
Assert.assertEquals(
new StructField("b", new ArrayType(IntegerType$.MODULE$, true), true, Metadata.empty()),
schema.apply("b"));
ArrayType valueType = new ArrayType(DataTypes.IntegerType, false);
MapType mapType = new MapType(DataTypes.StringType, valueType, true);
Assert.assertEquals(
new StructField("c", mapType, true, Metadata.empty()),
schema.apply("c"));
Assert.assertEquals(
new StructField("d", new ArrayType(DataTypes.StringType, true), true, Metadata.empty()),
schema.apply("d"));
Row first = df.select("a", "b", "c", "d").first();
|
|
Like Feedback org.apache.spark.sql.Row |
|
|
Sample 101. Code Sample / Example / Snippet of org.apache.spark.sql.types.StructType | |
|
public List<String> getD() {
return d;
}
}
void validateDataFrameWithBeans(Bean bean, DataFrame df) {
StructType schema = df.schema();
|
|
Like Feedback org.apache.spark.sql.types.StructType |
|
|
Sample 102. Code Sample / Example / Snippet of org.apache.spark.sql.catalyst.expressions.UnsafeProjection | |
|
public UnsafeFixedWidthAggregationMap(
InternalRow emptyAggregationBuffer,
StructType aggregationBufferSchema,
StructType groupingKeySchema,
TaskMemoryManager taskMemoryManager,
int initialCapacity,
long pageSizeBytes,
boolean enablePerfMetrics) {
this.aggregationBufferSchema = aggregationBufferSchema;
this.groupingKeyProjection = UnsafeProjection.create(groupingKeySchema);
this.groupingKeySchema = groupingKeySchema;
this.map =
new BytesToBytesMap(taskMemoryManager, initialCapacity, pageSizeBytes, enablePerfMetrics);
this.enablePerfMetrics = enablePerfMetrics;
final UnsafeProjection valueProjection = UnsafeProjection.create(aggregationBufferSchema);
this.emptyAggregationBuffer = valueProjection.apply(emptyAggregationBuffer).getBytes();
}
|
|
Like Feedback org.apache.spark.sql.catalyst.expressions.UnsafeProjection |
|
|
Sample 103. Code Sample / Example / Snippet of org.apache.spark.unsafe.memory.MemoryLocation | |
|
public boolean next() {
if (mapLocationIterator.hasNext()) {
final BytesToBytesMap.Location loc = mapLocationIterator.next();
final MemoryLocation keyAddress = loc.getKeyAddress();
final MemoryLocation valueAddress = loc.getValueAddress();
key.pointTo(
keyAddress.getBaseObject(),
keyAddress.getBaseOffset(),
groupingKeySchema.length(),
loc.getKeyLength()
);
value.pointTo(
valueAddress.getBaseObject(),
valueAddress.getBaseOffset(),
aggregationBufferSchema.length(),
loc.getValueLength()
);
return true;
} else {
return false;
}
}
|
|
Like Feedback org.apache.spark.unsafe.memory.MemoryLocation |
|
|
Sample 104. Code Sample / Example / Snippet of org.apache.spark.api.java.JavaDoubleRDD | |
|
public void map() {
JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5));
JavaDoubleRDD doubles = rdd.mapToDouble(x -> 1.0 * x).cache();
doubles.collect();
JavaPairRDD<Integer, Integer> pairs = rdd.mapToPair(x -> new Tuple2<>(x, x))
.cache();
pairs.collect();
JavaRDD<String> strings = rdd.map(Object::toString).cache();
strings.collect();
}
|
|
Like Feedback org.apache.spark.api.java.JavaDoubleRDD |
|
|
|
Sample 105. Code Sample / Example / Snippet of org.apache.spark.SparkConf | |
|
public static void main(String[] args) throws Exception {
SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);
final JavaSparkContext sc = new JavaSparkContext(sparkConf);
JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(
new IdentityWithDelay<Integer>());
JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();
while (!jobFuture.isDone()) {
Thread.sleep(1000); // 1 second
List<Integer> jobIds = jobFuture.jobIds();
if (jobIds.isEmpty()) {
continue;
}
int currentJobId = jobIds.get(jobIds.size() - 1);
SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);
SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);
System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +
" active, " + stageInfo.numCompletedTasks() + " complete");
}
System.out.println("Job results are: " + jobFuture.get());
sc.stop();
}
|
|
Like Feedback org.apache.spark.SparkConf |
|
|
Sample 106. Code Sample / Example / Snippet of org.apache.spark.SparkJobInfo | |
|
public static void main(String[] args) throws Exception {
SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);
final JavaSparkContext sc = new JavaSparkContext(sparkConf);
JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(
new IdentityWithDelay<Integer>());
JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();
while (!jobFuture.isDone()) {
Thread.sleep(1000); // 1 second
List<Integer> jobIds = jobFuture.jobIds();
if (jobIds.isEmpty()) {
continue;
}
int currentJobId = jobIds.get(jobIds.size() - 1);
SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);
SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);
System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +
" active, " + stageInfo.numCompletedTasks() + " complete");
}
System.out.println("Job results are: " + jobFuture.get());
sc.stop();
}
|
|
Like Feedback org.apache.spark.SparkJobInfo |
|
|
Sample 107. Code Sample / Example / Snippet of org.apache.spark.SparkStageInfo | |
|
public static void main(String[] args) throws Exception {
SparkConf sparkConf = new SparkConf().setAppName(APP_NAME);
final JavaSparkContext sc = new JavaSparkContext(sparkConf);
JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4, 5), 5).map(
new IdentityWithDelay<Integer>());
JavaFutureAction<List<Integer>> jobFuture = rdd.collectAsync();
while (!jobFuture.isDone()) {
Thread.sleep(1000); // 1 second
List<Integer> jobIds = jobFuture.jobIds();
if (jobIds.isEmpty()) {
continue;
}
int currentJobId = jobIds.get(jobIds.size() - 1);
SparkJobInfo jobInfo = sc.statusTracker().getJobInfo(currentJobId);
SparkStageInfo stageInfo = sc.statusTracker().getStageInfo(jobInfo.stageIds()[0]);
System.out.println(stageInfo.numTasks() + " tasks total: " + stageInfo.numActiveTasks() +
" active, " + stageInfo.numCompletedTasks() + " complete");
}
System.out.println("Job results are: " + jobFuture.get());
sc.stop();
}
|
|
Like Feedback org.apache.spark.SparkStageInfo |
|
|
Sample 108. Code Sample / Example / Snippet of org.apache.spark.sql.SQLContext | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaDCTExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
JavaRDD<Row> data = jsc.parallelize(Arrays.asList(
RowFactory.create(Vectors.dense(0.0, 1.0, -2.0, 3.0)),
RowFactory.create(Vectors.dense(-1.0, 2.0, 4.0, -7.0)),
RowFactory.create(Vectors.dense(14.0, -2.0, -5.0, 1.0))
));
StructType schema = new StructType(new StructField[]{
new StructField("features", new VectorUDT(), false, Metadata.empty()),
});
DataFrame df = jsql.createDataFrame(data, schema);
DCT dct = new DCT()
.setInputCol("features")
.setOutputCol("featuresDCT")
.setInverse(false);
DataFrame dctDf = dct.transform(df);
dctDf.select("featuresDCT").show(3);
jsc.stop();
}
|
|
Like Feedback org.apache.spark.sql.SQLContext |
|
|
Sample 109. Code Sample / Example / Snippet of org.apache.spark.ml.feature.DCT | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaDCTExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
JavaRDD<Row> data = jsc.parallelize(Arrays.asList(
RowFactory.create(Vectors.dense(0.0, 1.0, -2.0, 3.0)),
RowFactory.create(Vectors.dense(-1.0, 2.0, 4.0, -7.0)),
RowFactory.create(Vectors.dense(14.0, -2.0, -5.0, 1.0))
));
StructType schema = new StructType(new StructField[]{
new StructField("features", new VectorUDT(), false, Metadata.empty()),
});
DataFrame df = jsql.createDataFrame(data, schema);
DCT dct = new DCT()
.setInputCol("features")
.setOutputCol("featuresDCT")
.setInverse(false);
DataFrame dctDf = dct.transform(df);
dctDf.select("featuresDCT").show(3);
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.feature.DCT |
|
|
|
Sample 110. Code Sample / Example / Snippet of org.apache.spark.ml.param.IntParam | |
|
public String uid() {
return uid_;
}
IntParam maxIter = new IntParam(this, "maxIter", "max number of iterations");
|
|
Like Feedback org.apache.spark.ml.param.IntParam |
|
|
Sample 111. Code Sample / Example / Snippet of org.apache.spark.mllib.linalg.Vector | |
|
public MyJavaLogisticRegressionModel train(DataFrame dataset) {
JavaRDD<LabeledPoint> oldDataset = extractLabeledPoints(dataset).toJavaRDD();
int numFeatures = oldDataset.take(1).get(0).features().size();
Vector weights = Vectors.zeros(numFeatures); // Learning would happen here.
return new MyJavaLogisticRegressionModel(uid(), weights).setParent(this);
}
|
|
Like Feedback org.apache.spark.mllib.linalg.Vector |
|
|
Sample 112. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StandardScaler | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaStandardScalerExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
StandardScaler scaler = new StandardScaler()
.setInputCol("features")
.setOutputCol("scaledFeatures")
.setWithStd(true)
.setWithMean(false);
StandardScalerModel scalerModel = scaler.fit(dataFrame);
DataFrame scaledData = scalerModel.transform(dataFrame);
scaledData.show();
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.feature.StandardScaler |
|
|
Sample 113. Code Sample / Example / Snippet of org.apache.spark.ml.feature.StandardScalerModel | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaStandardScalerExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
StandardScaler scaler = new StandardScaler()
.setInputCol("features")
.setOutputCol("scaledFeatures")
.setWithStd(true)
.setWithMean(false);
StandardScalerModel scalerModel = scaler.fit(dataFrame);
DataFrame scaledData = scalerModel.transform(dataFrame);
scaledData.show();
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.feature.StandardScalerModel |
|
|
Sample 114. Code Sample / Example / Snippet of org.apache.spark.ml.feature.Normalizer | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaNormalizerExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
Normalizer normalizer = new Normalizer()
.setInputCol("features")
.setOutputCol("normFeatures")
.setP(1.0);
DataFrame l1NormData = normalizer.transform(dataFrame);
l1NormData.show();
DataFrame lInfNormData =
normalizer.transform(dataFrame, normalizer.p().w(Double.POSITIVE_INFINITY));
lInfNormData.show();
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.feature.Normalizer |
|
|
|
Sample 115. Code Sample / Example / Snippet of org.apache.spark.ml.classification.LogisticRegression | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame training = sqlContext.read().format("libsvm")
.load("data/mllib/sample_libsvm_data.txt");
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8);
LogisticRegressionModel lrModel = lr.fit(training);
System.out.println("Coefficients: "
+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.classification.LogisticRegression |
|
|
Sample 116. Code Sample / Example / Snippet of org.apache.spark.ml.feature.SQLTransformer | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaSQLTransformerExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(jsc);
JavaRDD<Row> jrdd = jsc.parallelize(Arrays.asList(
RowFactory.create(0, 1.0, 3.0),
RowFactory.create(2, 2.0, 5.0)
));
StructType schema = new StructType(new StructField [] {
new StructField("id", DataTypes.IntegerType, false, Metadata.empty()),
new StructField("v1", DataTypes.DoubleType, false, Metadata.empty()),
new StructField("v2", DataTypes.DoubleType, false, Metadata.empty())
});
DataFrame df = sqlContext.createDataFrame(jrdd, schema);
SQLTransformer sqlTrans = new SQLTransformer().setStatement(
"SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__");
sqlTrans.transform(df).show();
}
|
|
Like Feedback org.apache.spark.ml.feature.SQLTransformer |
|
|
Sample 117. Code Sample / Example / Snippet of org.apache.spark.ml.feature.MinMaxScalerModel | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JaveMinMaxScalerExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
MinMaxScaler scaler = new MinMaxScaler()
.setInputCol("features")
.setOutputCol("scaledFeatures");
MinMaxScalerModel scalerModel = scaler.fit(dataFrame);
DataFrame scaledData = scalerModel.transform(dataFrame);
scaledData.show();
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.feature.MinMaxScalerModel |
|
|
Sample 118. Code Sample / Example / Snippet of org.apache.spark.ml.feature.MinMaxScaler | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JaveMinMaxScalerExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext jsql = new SQLContext(jsc);
DataFrame dataFrame = jsql.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
MinMaxScaler scaler = new MinMaxScaler()
.setInputCol("features")
.setOutputCol("scaledFeatures");
MinMaxScalerModel scalerModel = scaler.fit(dataFrame);
DataFrame scaledData = scalerModel.transform(dataFrame);
scaledData.show();
jsc.stop();
}
|
|
Like Feedback org.apache.spark.ml.feature.MinMaxScaler |
|
|
Sample 119. Code Sample / Example / Snippet of org.apache.spark.mllib.classification.LogisticRegressionModel | |
|
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JavaLogisticRegressionWithElasticNetExample");
JavaSparkContext jsc = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(jsc);
DataFrame training = sqlContext.read().format("libsvm")
.load("data/mllib/sample_libsvm_data.txt");
LogisticRegression lr = new LogisticRegression()
.setMaxIter(10)
.setRegParam(0.3)
.setElasticNetParam(0.8);
LogisticRegressionModel lrModel = lr.fit(training);
System.out.println("Coefficients: "
+ lrModel.coefficients() + " Intercept: " + lrModel.intercept());
jsc.stop();
}
|
|
Like Feedback org.apache.spark.mllib.classification.LogisticRegressionModel |
|
|
|
Sample 120. Code Sample / Example / Snippet of org.apache.storm.task.TopologyContext | |
|
public void shouldEmitNothingIfNoObjectHasBeenCountedYetAndTickTupleIsReceived() {
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
RollingCountBolt bolt = new RollingCountBolt();
Map conf = mock(Map.class);
TopologyContext context = mock(TopologyContext.class);
OutputCollector collector = mock(OutputCollector.class);
bolt.prepare(conf, context, collector);
bolt.execute(tickTuple);
verifyZeroInteractions(collector);
}
|
|
Like Feedback org.apache.storm.task.TopologyContext |
|
|
Sample 121. Code Sample / Example / Snippet of org.apache.spark.mllib.fpm.AssociationRules | |
|
public static void main(String[] args) {
SparkConf sparkConf = new SparkConf().setAppName("JavaAssociationRulesExample");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
JavaRDD<FPGrowth.FreqItemset<String>> freqItemsets = sc.parallelize(Arrays.asList(
new FreqItemset<String>(new String[] {"a"}, 15L),
new FreqItemset<String>(new String[] {"b"}, 35L),
new FreqItemset<String>(new String[] {"a", "b"}, 12L)
));
AssociationRules arules = new AssociationRules()
.setMinConfidence(0.8);
JavaRDD<AssociationRules.Rule<String>> results = arules.run(freqItemsets);
for (AssociationRules.Rule<String> rule : results.collect()) {
System.out.println(
rule.javaAntecedent() + " => " + rule.javaConsequent() + ", " + rule.confidence());
}
}
|
|
Like Feedback org.apache.spark.mllib.fpm.AssociationRules |
|
|
Sample 122. Code Sample / Example / Snippet of org.apache.spark.mllib.regression.IsotonicRegressionModel | |
|
public Tuple3<Double, Double, Double> call(String line) {
String[] parts = line.split(",");
return new Tuple3<>(new Double(parts[0]), new Double(parts[1]), 1.0);
}
}
);
JavaRDD<Tuple3<Double, Double, Double>>[] splits = parsedData.randomSplit(new double[]{0.6, 0.4}, 11L);
JavaRDD<Tuple3<Double, Double, Double>> training = splits[0];
JavaRDD<Tuple3<Double, Double, Double>> test = splits[1];
final IsotonicRegressionModel model = new IsotonicRegression().setIsotonic(true).run(training);
JavaPairRDD<Double, Double> predictionAndLabel = test.mapToPair(
new PairFunction<Tuple3<Double, Double, Double>, Double, Double>() {
|
|
Like Feedback org.apache.spark.mllib.regression.IsotonicRegressionModel |
|
|
Sample 123. Code Sample / Example / Snippet of org.apache.spark.mllib.fpm.PrefixSpan | |
|
public static void main(String[] args) {
SparkConf sparkConf = new SparkConf().setAppName("JavaPrefixSpanExample");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
JavaRDD<List<List<Integer>>> sequences = sc.parallelize(Arrays.asList(
Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3)),
Arrays.asList(Arrays.asList(1), Arrays.asList(3, 2), Arrays.asList(1, 2)),
Arrays.asList(Arrays.asList(1, 2), Arrays.asList(5)),
Arrays.asList(Arrays.asList(6))
), 2);
PrefixSpan prefixSpan = new PrefixSpan()
.setMinSupport(0.5)
.setMaxPatternLength(5);
PrefixSpanModel<Integer> model = prefixSpan.run(sequences);
for (PrefixSpan.FreqSequence<Integer> freqSeq: model.freqSequences().toJavaRDD().collect()) {
System.out.println(freqSeq.javaSequence() + ", " + freqSeq.freq());
}
}
|
|
Like Feedback org.apache.spark.mllib.fpm.PrefixSpan |
|
|
Sample 124. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.PowerIterationClustering | |
|
public static void main(String[] args) {
SparkConf sparkConf = new SparkConf().setAppName("JavaPowerIterationClusteringExample");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
@SuppressWarnings("unchecked")
JavaRDD<Tuple3<Long, Long, Double>> similarities = sc.parallelize(Lists.newArrayList(
new Tuple3<Long, Long, Double>(0L, 1L, 0.9),
new Tuple3<Long, Long, Double>(1L, 2L, 0.9),
new Tuple3<Long, Long, Double>(2L, 3L, 0.9),
new Tuple3<Long, Long, Double>(3L, 4L, 0.1),
new Tuple3<Long, Long, Double>(4L, 5L, 0.9)));
PowerIterationClustering pic = new PowerIterationClustering()
.setK(2)
.setMaxIterations(10);
PowerIterationClusteringModel model = pic.run(similarities);
for (PowerIterationClustering.Assignment a: model.assignments().toJavaRDD().collect()) {
System.out.println(a.id() + " -> " + a.cluster());
}
sc.stop();
}
|
|
Like Feedback org.apache.spark.mllib.clustering.PowerIterationClustering |
|
|
|
Sample 125. Code Sample / Example / Snippet of org.apache.spark.mllib.clustering.PowerIterationClusteringModel | |
|
public static void main(String[] args) {
SparkConf sparkConf = new SparkConf().setAppName("JavaPowerIterationClusteringExample");
JavaSparkContext sc = new JavaSparkContext(sparkConf);
@SuppressWarnings("unchecked")
JavaRDD<Tuple3<Long, Long, Double>> similarities = sc.parallelize(Lists.newArrayList(
new Tuple3<Long, Long, Double>(0L, 1L, 0.9),
new Tuple3<Long, Long, Double>(1L, 2L, 0.9),
new Tuple3<Long, Long, Double>(2L, 3L, 0.9),
new Tuple3<Long, Long, Double>(3L, 4L, 0.1),
new Tuple3<Long, Long, Double>(4L, 5L, 0.9)));
PowerIterationClustering pic = new PowerIterationClustering()
.setK(2)
.setMaxIterations(10);
PowerIterationClusteringModel model = pic.run(similarities);
for (PowerIterationClustering.Assignment a: model.assignments().toJavaRDD().collect()) {
System.out.println(a.id() + " -> " + a.cluster());
}
sc.stop();
}
|
|
Like Feedback org.apache.spark.mllib.clustering.PowerIterationClusteringModel |
|
|
Sample 126. Code Sample / Example / Snippet of org.apache.spark.mllib.stat.test.StreamingTest | |
|
public void streamingTest() {
List<BinarySample> trainingBatch = Arrays.asList(
new BinarySample(true, 1.0),
new BinarySample(false, 2.0));
JavaDStream<BinarySample> training =
attachTestInputStream(ssc, Arrays.asList(trainingBatch, trainingBatch), 2);
int numBatches = 2;
StreamingTest model = new StreamingTest()
.setWindowSize(0)
.setPeacePeriod(0)
.setTestMethod("welch");
model.registerStream(training);
attachTestOutputStream(training);
runStreams(ssc, numBatches, numBatches);
}
|
|
Like Feedback org.apache.spark.mllib.stat.test.StreamingTest |
|
|
Sample 127. Code Sample / Example / Snippet of org.apache.spark.network.server.TransportServerBootstrap | |
|
public void beforeEach() throws IOException {
TransportContext context =
new TransportContext(conf, new ExternalShuffleBlockHandler(conf, null));
TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf,
new TestSecretKeyHolder("my-app-id", "secret"));
this.server = context.createServer(Arrays.asList(bootstrap));
}
|
|
Like Feedback org.apache.spark.network.server.TransportServerBootstrap |
|
|
Sample 128. Code Sample / Example / Snippet of org.apache.spark.network.TransportContext | |
|
public void beforeEach() throws IOException {
TransportContext context =
new TransportContext(conf, new ExternalShuffleBlockHandler(conf, null));
TransportServerBootstrap bootstrap = new SaslServerBootstrap(conf,
new TestSecretKeyHolder("my-app-id", "secret"));
this.server = context.createServer(Arrays.asList(bootstrap));
}
|
|
Like Feedback org.apache.spark.network.TransportContext |
|
|
Sample 129. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleBlockResolver.AppExecId | |
|
public void jsonSerializationOfExecutorRegistration() throws IOException {
ObjectMapper mapper = new ObjectMapper();
AppExecId appId = new AppExecId("foo", "bar");
String appIdJson = mapper.writeValueAsString(appId);
AppExecId parsedAppId = mapper.readValue(appIdJson, AppExecId.class);
assertEquals(parsedAppId, appId);
ExecutorShuffleInfo shuffleInfo =
new ExecutorShuffleInfo(new String[]{"/bippy", "/flippy"}, 7, "hash");
String shuffleJson = mapper.writeValueAsString(shuffleInfo);
ExecutorShuffleInfo parsedShuffleInfo =
mapper.readValue(shuffleJson, ExecutorShuffleInfo.class);
assertEquals(parsedShuffleInfo, shuffleInfo);
String legacyAppIdJson = "{"appId":"foo", "execId":"bar"}";
assertEquals(appId, mapper.readValue(legacyAppIdJson, AppExecId.class));
String legacyShuffleJson = "{"localDirs": ["/bippy", "/flippy"], " +
""subDirsPerLocalDir": 7, "shuffleManager": "hash"}";
assertEquals(shuffleInfo, mapper.readValue(legacyShuffleJson, ExecutorShuffleInfo.class));
}
|
|
Like Feedback org.apache.spark.network.shuffle.ExternalShuffleBlockResolver.AppExecId |
|
|
|
Sample 130. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo | |
|
public void jsonSerializationOfExecutorRegistration() throws IOException {
ObjectMapper mapper = new ObjectMapper();
AppExecId appId = new AppExecId("foo", "bar");
String appIdJson = mapper.writeValueAsString(appId);
AppExecId parsedAppId = mapper.readValue(appIdJson, AppExecId.class);
assertEquals(parsedAppId, appId);
ExecutorShuffleInfo shuffleInfo =
new ExecutorShuffleInfo(new String[]{"/bippy", "/flippy"}, 7, "hash");
String shuffleJson = mapper.writeValueAsString(shuffleInfo);
ExecutorShuffleInfo parsedShuffleInfo =
mapper.readValue(shuffleJson, ExecutorShuffleInfo.class);
assertEquals(parsedShuffleInfo, shuffleInfo);
String legacyAppIdJson = "{"appId":"foo", "execId":"bar"}";
assertEquals(appId, mapper.readValue(legacyAppIdJson, AppExecId.class));
String legacyShuffleJson = "{"localDirs": ["/bippy", "/flippy"], " +
""subDirsPerLocalDir": 7, "shuffleManager": "hash"}";
assertEquals(shuffleInfo, mapper.readValue(legacyShuffleJson, ExecutorShuffleInfo.class));
}
|
|
Like Feedback org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo |
|
|
Sample 131. Code Sample / Example / Snippet of org.apache.spark.network.server.RpcHandler | |
|
public void testNoSaslServer() {
RpcHandler handler = new TestRpcHandler();
TransportContext context = new TransportContext(conf, handler);
clientFactory = context.createClientFactory(
Lists.<TransportClientBootstrap>newArrayList(
new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));
TransportServer server = context.createServer();
try {
clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
} catch (Exception e) {
assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));
} finally {
server.close();
}
}
|
|
Like Feedback org.apache.spark.network.server.RpcHandler |
|
|
Sample 132. Code Sample / Example / Snippet of org.apache.spark.network.server.TransportServer | |
|
public void testNoSaslServer() {
RpcHandler handler = new TestRpcHandler();
TransportContext context = new TransportContext(conf, handler);
clientFactory = context.createClientFactory(
Lists.<TransportClientBootstrap>newArrayList(
new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));
TransportServer server = context.createServer();
try {
clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
} catch (Exception e) {
assertTrue(e.getMessage(), e.getMessage().contains("Digest-challenge format violation"));
} finally {
server.close();
}
}
|
|
Like Feedback org.apache.spark.network.server.TransportServer |
|
|
Sample 133. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.BlockFetchingListener | |
|
public void testNoFailures() throws IOException {
BlockFetchingListener listener = mock(BlockFetchingListener.class);
List<? extends Map<String, Object>> interactions = Arrays.asList(
ImmutableMap.<String, Object>builder()
.put("b0", block0)
.put("b1", block1)
.build()
);
performInteractions(interactions, listener);
verify(listener).onBlockFetchSuccess("b0", block0);
verify(listener).onBlockFetchSuccess("b1", block1);
verifyNoMoreInteractions(listener);
}
|
|
Like Feedback org.apache.spark.network.shuffle.BlockFetchingListener |
|
|
Sample 134. Code Sample / Example / Snippet of org.apache.spark.network.client.TransportClient | |
|
public void testGoodClient() throws IOException {
clientFactory = context.createClientFactory(
Lists.<TransportClientBootstrap>newArrayList(
new SaslClientBootstrap(conf, "app-1", secretKeyHolder)));
TransportClient client = clientFactory.createClient(TestUtils.getLocalHost(), server.getPort());
String msg = "Hello, World!";
ByteBuffer resp = client.sendRpcSync(JavaUtils.stringToBytes(msg), TIMEOUT_MS);
assertEquals(msg, JavaUtils.bytesToString(resp));
}
|
|
Like Feedback org.apache.spark.network.client.TransportClient |
|
|
|
Sample 135. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.ExternalShuffleBlockResolver | |
|
public void noCleanupAndCleanup() throws IOException {
TestShuffleDataContext dataContext = createSomeData();
ExternalShuffleBlockResolver resolver =
new ExternalShuffleBlockResolver(conf, null, sameThreadExecutor);
resolver.registerExecutor("app", "exec0", dataContext.createExecutorInfo("shuffleMgr"));
resolver.applicationRemoved("app", false /* cleanup */);
assertStillThere(dataContext);
resolver.registerExecutor("app", "exec1", dataContext.createExecutorInfo("shuffleMgr"));
resolver.applicationRemoved("app", true /* cleanup */);
assertCleanedUp(dataContext);
}
|
|
Like Feedback org.apache.spark.network.shuffle.ExternalShuffleBlockResolver |
|
|
Sample 136. Code Sample / Example / Snippet of org.apache.spark.network.protocol.StreamChunkId | |
|
public void handleSuccessfulFetch() throws Exception {
StreamChunkId streamChunkId = new StreamChunkId(1, 0);
TransportResponseHandler handler = new TransportResponseHandler(new LocalChannel());
ChunkReceivedCallback callback = mock(ChunkReceivedCallback.class);
handler.addFetchRequest(streamChunkId, callback);
assertEquals(1, handler.numOutstandingRequests());
handler.handle(new ChunkFetchSuccess(streamChunkId, new TestManagedBuffer(123)));
verify(callback, times(1)).onSuccess(eq(0), (ManagedBuffer) any());
assertEquals(0, handler.numOutstandingRequests());
}
|
|
Like Feedback org.apache.spark.network.protocol.StreamChunkId |
|
|
Sample 137. Code Sample / Example / Snippet of org.apache.storm.topology.BasicOutputCollector | |
|
public void shouldEmitSomethingIfTickTupleIsReceived() {
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
BasicOutputCollector collector = mock(BasicOutputCollector.class);
TotalRankingsBolt bolt = new TotalRankingsBolt();
bolt.execute(tickTuple, collector);
verify(collector).emit(any(Values.class));
}
|
|
Like Feedback org.apache.storm.topology.BasicOutputCollector |
|
|
Sample 138. Code Sample / Example / Snippet of org.apache.storm.starter.tools.Rankings | |
|
public void copyConstructorShouldReturnCopy(int topN, List<Rankable> rankables) {
Rankings rankings = new Rankings(topN);
for (Rankable r : rankables) {
rankings.updateWith(r);
}
Rankings copy = new Rankings(rankings);
assertThat(copy.maxSize()).isEqualTo(rankings.maxSize());
assertThat(copy.getRankings()).isEqualTo(rankings.getRankings());
}
|
|
Like Feedback org.apache.storm.starter.tools.Rankings |
|
|
Sample 139. Code Sample / Example / Snippet of org.apache.storm.Config | |
|
public static void main(String[] args) throws Exception {
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new RandomIntegerSpout());
builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))
.withMessageIdField("msgid"), 1).shuffleGrouping("spout");
builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");
Config conf = new Config();
conf.setDebug(false);
if (args != null && args.length > 0) {
conf.setNumWorkers(1);
StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());
} else {
LocalCluster cluster = new LocalCluster();
StormTopology topology = builder.createTopology();
cluster.submitTopology("test", conf, topology);
Utils.sleep(40000);
cluster.killTopology("test");
cluster.shutdown();
}
}
|
|
Like Feedback org.apache.storm.Config |
|
|
|
Sample 140. Code Sample / Example / Snippet of org.apache.storm.topology.TopologyBuilder | |
|
public static void main(String[] args) throws Exception {
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new RandomIntegerSpout());
builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))
.withMessageIdField("msgid"), 1).shuffleGrouping("spout");
builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");
Config conf = new Config();
conf.setDebug(false);
if (args != null && args.length > 0) {
conf.setNumWorkers(1);
StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());
} else {
LocalCluster cluster = new LocalCluster();
StormTopology topology = builder.createTopology();
cluster.submitTopology("test", conf, topology);
Utils.sleep(40000);
cluster.killTopology("test");
cluster.shutdown();
}
}
|
|
Like Feedback org.apache.storm.topology.TopologyBuilder |
|
|
Sample 141. Code Sample / Example / Snippet of org.apache.storm.LocalCluster | |
|
public static void main(String[] args) throws Exception {
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new RandomIntegerSpout());
builder.setBolt("sumbolt", new WindowSumBolt().withWindow(new Count(5), new Count(3))
.withMessageIdField("msgid"), 1).shuffleGrouping("spout");
builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("sumbolt");
Config conf = new Config();
conf.setDebug(false);
if (args != null && args.length > 0) {
conf.setNumWorkers(1);
StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());
} else {
LocalCluster cluster = new LocalCluster();
StormTopology topology = builder.createTopology();
cluster.submitTopology("test", conf, topology);
Utils.sleep(40000);
cluster.killTopology("test");
cluster.shutdown();
}
}
|
|
Like Feedback org.apache.storm.LocalCluster |
|
|
Sample 142. Code Sample / Example / Snippet of org.apache.storm.testing.MemoryTransactionalSpout | |
|
public static void main(String[] args) throws Exception {
MemoryTransactionalSpout spout = new MemoryTransactionalSpout(DATA, new Fields("word"), PARTITION_TAKE_PER_BATCH);
TransactionalTopologyBuilder builder = new TransactionalTopologyBuilder("global-count", "spout", spout, 3);
builder.setBolt("partial-count", new BatchCount(), 5).noneGrouping("spout");
builder.setBolt("sum", new UpdateGlobalCount()).globalGrouping("partial-count");
LocalCluster cluster = new LocalCluster();
Config config = new Config();
config.setDebug(true);
config.setMaxSpoutPending(3);
cluster.submitTopology("global-count-topology", config, builder.buildTopology());
Thread.sleep(3000);
cluster.shutdown();
}
|
|
Like Feedback org.apache.storm.testing.MemoryTransactionalSpout |
|
|
Sample 143. Code Sample / Example / Snippet of org.apache.storm.transactional.TransactionalTopologyBuilder | |
|
public static void main(String[] args) throws Exception {
MemoryTransactionalSpout spout = new MemoryTransactionalSpout(DATA, new Fields("word"), PARTITION_TAKE_PER_BATCH);
TransactionalTopologyBuilder builder = new TransactionalTopologyBuilder("global-count", "spout", spout, 3);
builder.setBolt("partial-count", new BatchCount(), 5).noneGrouping("spout");
builder.setBolt("sum", new UpdateGlobalCount()).globalGrouping("partial-count");
LocalCluster cluster = new LocalCluster();
Config config = new Config();
config.setDebug(true);
config.setMaxSpoutPending(3);
cluster.submitTopology("global-count-topology", config, builder.buildTopology());
Thread.sleep(3000);
cluster.shutdown();
}
|
|
Like Feedback org.apache.storm.transactional.TransactionalTopologyBuilder |
|
|
Sample 144. Code Sample / Example / Snippet of org.apache.storm.trident.windowing.WindowsStoreFactory | |
|
public static void main(String[] args) throws Exception {
Config conf = new Config();
WindowsStoreFactory mapState = new InMemoryWindowsStoreFactory();
if (args.length == 0) {
List<? extends WindowConfig> list = Arrays.asList(
SlidingCountWindow.of(1000, 100)
,TumblingCountWindow.of(1000)
,SlidingDurationWindow.of(new BaseWindowedBolt.Duration(6, TimeUnit.SECONDS), new BaseWindowedBolt.Duration(3, TimeUnit.SECONDS))
,TumblingDurationWindow.of(new BaseWindowedBolt.Duration(3, TimeUnit.SECONDS))
);
for (WindowConfig windowConfig : list) {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("wordCounter", conf, buildTopology(mapState, windowConfig));
Utils.sleep(60 * 1000);
cluster.shutdown();
}
System.exit(0);
} else {
conf.setNumWorkers(3);
StormSubmitter.submitTopologyWithProgressBar(args[0], conf, buildTopology(mapState, SlidingCountWindow.of(1000, 100)));
}
}
|
|
Like Feedback org.apache.storm.trident.windowing.WindowsStoreFactory |
|
|
|
Sample 145. Code Sample / Example / Snippet of org.apache.storm.trident.Stream | |
|
public static StormTopology buildTopology(WindowsStoreFactory windowStore, WindowConfig windowConfig) throws Exception {
FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),
new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),
new Values("how many apples can you eat"), new Values("to be or not to be the person"));
spout.setCycle(true);
TridentTopology topology = new TridentTopology();
Stream stream = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),
new Split(), new Fields("word"))
.window(windowConfig, windowStore, new Fields("word"), new CountAsAggregator(), new Fields("count"))
.peek(new Consumer() {
@Override
public void accept(TridentTuple input) {
LOG.info("Received tuple: [{}]", input);
}
});
return topology.build();
}
|
|
Like Feedback org.apache.storm.trident.Stream |
|
|
Sample 146. Code Sample / Example / Snippet of org.apache.storm.trident.TridentTopology | |
|
public static StormTopology buildTopology(WindowsStoreFactory windowStore, WindowConfig windowConfig) throws Exception {
FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),
new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),
new Values("how many apples can you eat"), new Values("to be or not to be the person"));
spout.setCycle(true);
TridentTopology topology = new TridentTopology();
Stream stream = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),
new Split(), new Fields("word"))
.window(windowConfig, windowStore, new Fields("word"), new CountAsAggregator(), new Fields("count"))
.peek(new Consumer() {
@Override
public void accept(TridentTuple input) {
LOG.info("Received tuple: [{}]", input);
}
});
return topology.build();
}
|
|
Like Feedback org.apache.storm.trident.TridentTopology |
|
|
Sample 147. Code Sample / Example / Snippet of org.apache.storm.kafka.ZkHosts | |
|
private TransactionalTridentKafkaSpout createKafkaSpout() {
ZkHosts hosts = new ZkHosts(zkUrl);
TridentKafkaConfig config = new TridentKafkaConfig(hosts, "test");
config.scheme = new SchemeAsMultiScheme(new StringScheme());
config.startOffsetTime = kafka.api.OffsetRequest.LatestTime();
return new TransactionalTridentKafkaSpout(config);
}
|
|
Like Feedback org.apache.storm.kafka.ZkHosts |
|
|
Sample 148. Code Sample / Example / Snippet of org.apache.storm.kafka.trident.TridentKafkaConfig | |
|
private TransactionalTridentKafkaSpout createKafkaSpout() {
ZkHosts hosts = new ZkHosts(zkUrl);
TridentKafkaConfig config = new TridentKafkaConfig(hosts, "test");
config.scheme = new SchemeAsMultiScheme(new StringScheme());
config.startOffsetTime = kafka.api.OffsetRequest.LatestTime();
return new TransactionalTridentKafkaSpout(config);
}
|
|
Like Feedback org.apache.storm.kafka.trident.TridentKafkaConfig |
|
|
Sample 149. Code Sample / Example / Snippet of org.apache.storm.kafka.bolt.KafkaBolt | |
|
public StormTopology buildProducerTopology(Properties prop) {
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("spout", new RandomSentenceSpout(), 2);
KafkaBolt bolt = new KafkaBolt().withProducerProperties(prop)
.withTopicSelector(new DefaultTopicSelector("test"))
.withTupleToKafkaMapper(new FieldNameBasedTupleToKafkaMapper("key", "word"));
builder.setBolt("forwardToKafka", bolt, 1).shuffleGrouping("spout");
return builder.createTopology();
}
|
|
Like Feedback org.apache.storm.kafka.bolt.KafkaBolt |
|
|
|
Sample 150. Code Sample / Example / Snippet of org.apache.storm.trident.TridentState | |
|
public static StormTopology buildTopology(LocalDRPC drpc) {
FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),
new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),
new Values("how many apples can you eat"), new Values("to be or not to be the person"));
spout.setCycle(true);
TridentTopology topology = new TridentTopology();
TridentState wordCounts = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),
new Split(), new Fields("word")).groupBy(new Fields("word")).persistentAggregate(new MemoryMapState.Factory(),
new Count(), new Fields("count")).parallelismHint(16);
topology.newDRPCStream("words", drpc).each(new Fields("args"), new Split(), new Fields("word")).groupBy(new Fields(
"word")).stateQuery(wordCounts, new Fields("word"), new MapGet(), new Fields("count")).each(new Fields("count"),
new FilterNull()).aggregate(new Fields("count"), new Sum(), new Fields("sum"));
return topology.build();
}
|
|
Like Feedback org.apache.storm.trident.TridentState |
|
|
Sample 151. Code Sample / Example / Snippet of org.apache.storm.topology.base.BaseWindowedBolt | |
|
public static void main(String[] args) throws Exception {
TopologyBuilder builder = new TopologyBuilder();
BaseWindowedBolt bolt = new SlidingWindowSumBolt()
.withWindow(new Duration(5, TimeUnit.SECONDS), new Duration(3, TimeUnit.SECONDS))
.withTimestampField("ts")
.withLag(new Duration(5, TimeUnit.SECONDS));
builder.setSpout("integer", new RandomIntegerSpout(), 1);
builder.setBolt("slidingsum", bolt, 1).shuffleGrouping("integer");
builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("slidingsum");
Config conf = new Config();
conf.setDebug(true);
if (args != null && args.length > 0) {
conf.setNumWorkers(1);
StormSubmitter.submitTopologyWithProgressBar(args[0], conf, builder.createTopology());
} else {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("test", conf, builder.createTopology());
Utils.sleep(40000);
cluster.killTopology("test");
cluster.shutdown();
}
}
|
|
Like Feedback org.apache.storm.topology.base.BaseWindowedBolt |
|
|
Sample 152. Code Sample / Example / Snippet of org.apache.storm.drpc.LinearDRPCTopologyBuilder | |
|
public static LinearDRPCTopologyBuilder construct() {
LinearDRPCTopologyBuilder builder = new LinearDRPCTopologyBuilder("reach");
builder.addBolt(new GetTweeters(), 4);
builder.addBolt(new GetFollowers(), 12).shuffleGrouping();
builder.addBolt(new PartialUniquer(), 6).fieldsGrouping(new Fields("id", "follower"));
builder.addBolt(new CountAggregator(), 3).fieldsGrouping(new Fields("id"));
return builder;
}
|
|
Like Feedback org.apache.storm.drpc.LinearDRPCTopologyBuilder |
|
|
Sample 153. Code Sample / Example / Snippet of org.apache.storm.starter.bolt.IntermediateRankingsBolt | |
|
public void shouldEmitSomethingIfTickTupleIsReceived() {
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
BasicOutputCollector collector = mock(BasicOutputCollector.class);
IntermediateRankingsBolt bolt = new IntermediateRankingsBolt();
bolt.execute(tickTuple, collector);
verify(collector).emit(any(Values.class));
}
|
|
Like Feedback org.apache.storm.starter.bolt.IntermediateRankingsBolt |
|
|
Sample 154. Code Sample / Example / Snippet of org.apache.storm.starter.bolt.TotalRankingsBolt | |
|
public void shouldEmitSomethingIfTickTupleIsReceived() {
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
BasicOutputCollector collector = mock(BasicOutputCollector.class);
TotalRankingsBolt bolt = new TotalRankingsBolt();
bolt.execute(tickTuple, collector);
verify(collector).emit(any(Values.class));
}
|
|
Like Feedback org.apache.storm.starter.bolt.TotalRankingsBolt |
|
|
|
Sample 155. Code Sample / Example / Snippet of org.apache.storm.starter.bolt.RollingCountBolt | |
|
public void shouldEmitNothingIfNoObjectHasBeenCountedYetAndTickTupleIsReceived() {
Tuple tickTuple = MockTupleHelpers.mockTickTuple();
RollingCountBolt bolt = new RollingCountBolt();
Map conf = mock(Map.class);
TopologyContext context = mock(TopologyContext.class);
OutputCollector collector = mock(OutputCollector.class);
bolt.prepare(conf, context, collector);
bolt.execute(tickTuple);
verifyZeroInteractions(collector);
}
|
|
Like Feedback org.apache.storm.starter.bolt.RollingCountBolt |
|
|
Sample 156. Code Sample / Example / Snippet of org.apache.storm.blobstore.AtomicOutputStream | |
|
private static void createBlobWithContent(String blobKey, ClientBlobStore clientBlobStore, File file)
throws AuthorizationException, KeyAlreadyExistsException, IOException,KeyNotFoundException {
String stringBlobACL = "o::rwa";
AccessControl blobACL = BlobStoreAclHandler.parseAccessControl(stringBlobACL);
List<AccessControl> acls = new LinkedList<AccessControl>();
acls.add(blobACL); // more ACLs can be added here
SettableBlobMeta settableBlobMeta = new SettableBlobMeta(acls);
AtomicOutputStream blobStream = clientBlobStore.createBlob(blobKey,settableBlobMeta);
blobStream.write(readFile(file).toString().getBytes());
blobStream.close();
}
|
|
Like Feedback org.apache.storm.blobstore.AtomicOutputStream |
|
|
Sample 157. Code Sample / Example / Snippet of org.apache.storm.transactional.TransactionAttempt | |
|
public void execute(Tuple tuple, BasicOutputCollector collector) {
TransactionAttempt attempt = (TransactionAttempt) tuple.getValue(0);
int curr = tuple.getInteger(2);
Integer prev = tuple.getInteger(3);
int currBucket = curr / BUCKET_SIZE;
Integer prevBucket = null;
if (prev != null) {
prevBucket = prev / BUCKET_SIZE;
}
if (prevBucket == null) {
collector.emit(new Values(attempt, currBucket, 1));
}
else if (currBucket != prevBucket) {
collector.emit(new Values(attempt, currBucket, 1));
collector.emit(new Values(attempt, prevBucket, -1));
}
}
|
|
Like Feedback org.apache.storm.transactional.TransactionAttempt |
|
|
Sample 158. Code Sample / Example / Snippet of org.apache.storm.starter.tools.Rankable | |
|
public Object[][] duplicatesData() {
Rankable A1 = new RankableObjectWithFields("A", 1);
Rankable A2 = new RankableObjectWithFields("A", 2);
Rankable A3 = new RankableObjectWithFields("A", 3);
return new Object[][]{ { Lists.newArrayList(ANY_RANKABLE, ANY_RANKABLE, ANY_RANKABLE) }, { Lists.newArrayList(A1,
A2, A3) }, };
}
|
|
Like Feedback org.apache.storm.starter.tools.Rankable |
|
|
Sample 159. Code Sample / Example / Snippet of org.apache.storm.starter.tools.RankableObjectWithFields | |
|
public void toStringShouldContainStringRepresentationsOfObjectAndCount(Object obj, long count) {
RankableObjectWithFields r = new RankableObjectWithFields(obj, count);
String strRepresentation = r.toString();
assertThat(strRepresentation).contains(obj.toString()).contains("" + count);
}
|
|
Like Feedback org.apache.storm.starter.tools.RankableObjectWithFields |
|
|
|
Sample 160. Code Sample / Example / Snippet of org.apache.storm.starter.tools.NthLastModifiedTimeTracker | |
|
public void shouldReturnCorrectModifiedTimeEvenWhenNotYetMarkedAsModified(int secondsToAdvance) {
Time.startSimulating();
NthLastModifiedTimeTracker tracker = new NthLastModifiedTimeTracker(ANY_NUM_TIMES_TO_TRACK);
advanceSimulatedTimeBy(secondsToAdvance);
int seconds = tracker.secondsSinceOldestModification();
assertThat(seconds).isEqualTo(secondsToAdvance);
Time.stopSimulating();
}
|
|
Like Feedback org.apache.storm.starter.tools.NthLastModifiedTimeTracker |
|
|
Sample 161. Code Sample / Example / Snippet of org.apache.storm.kafka.trident.GlobalPartitionInformation | |
|
public static GlobalPartitionInformation buildPartitionInfo(int numPartitions, int brokerPort) {
GlobalPartitionInformation globalPartitionInformation = new GlobalPartitionInformation(TOPIC);
for (int i = 0; i < numPartitions; i++) {
globalPartitionInformation.addPartition(i, Broker.fromString("broker-" + i + " :" + brokerPort));
}
return globalPartitionInformation;
}
|
|
Like Feedback org.apache.storm.kafka.trident.GlobalPartitionInformation |
|
|
Sample 162. Code Sample / Example / Snippet of org.apache.storm.kafka.DynamicBrokersReader | |
|
public void testErrorLogsWhenConfigIsMissing() throws Exception {
String connectionString = server.getConnectString();
Map conf = new HashMap();
conf.put(Config.STORM_ZOOKEEPER_SESSION_TIMEOUT, 1000);
conf.put(Config.STORM_ZOOKEEPER_RETRY_TIMES, 4);
conf.put(Config.STORM_ZOOKEEPER_RETRY_INTERVAL, 5);
DynamicBrokersReader dynamicBrokersReader1 = new DynamicBrokersReader(conf, connectionString, masterPath, topic);
}
|
|
Like Feedback org.apache.storm.kafka.DynamicBrokersReader |
|
|
Sample 163. Code Sample / Example / Snippet of org.apache.storm.trident.topology.TransactionAttempt | |
|
public void execute(Tuple tuple, BasicOutputCollector collector) {
TransactionAttempt attempt = (TransactionAttempt) tuple.getValue(0);
int curr = tuple.getInteger(2);
Integer prev = tuple.getInteger(3);
int currBucket = curr / BUCKET_SIZE;
Integer prevBucket = null;
if (prev != null) {
prevBucket = prev / BUCKET_SIZE;
}
if (prevBucket == null) {
collector.emit(new Values(attempt, currBucket, 1));
}
else if (currBucket != prevBucket) {
collector.emit(new Values(attempt, currBucket, 1));
collector.emit(new Values(attempt, prevBucket, -1));
}
}
|
|
Like Feedback org.apache.storm.trident.topology.TransactionAttempt |
|
|
Sample 164. Code Sample / Example / Snippet of org.apache.storm.kafka.Partition | |
|
public void generateTuplesWithMessageAndMetadataScheme() {
String value = "value";
Partition mockPartition = Mockito.mock(Partition.class);
mockPartition.partition = 0;
long offset = 0L;
MessageMetadataSchemeAsMultiScheme scheme = new MessageMetadataSchemeAsMultiScheme(new StringMessageAndMetadataScheme());
createTopicAndSendMessage(null, value);
ByteBufferMessageSet messageAndOffsets = getLastMessage();
for (MessageAndOffset msg : messageAndOffsets) {
Iterable<List<Object>> lists = KafkaUtils.generateTuples(scheme, msg.message(), mockPartition, offset);
List<Object> values = lists.iterator().next();
assertEquals("Message is incorrect", value, values.get(0));
assertEquals("Partition is incorrect", mockPartition.partition, values.get(1));
assertEquals("Offset is incorrect", offset, values.get(2));
}
}
|
|
Like Feedback org.apache.storm.kafka.Partition |
|
|
|
Sample 165. Code Sample / Example / Snippet of org.apache.storm.kafka.PartitionManager.KafkaMessageId | |
|
public void ack(Object msgId) {
KafkaMessageId id = (KafkaMessageId) msgId;
PartitionManager m = _coordinator.getManager(id.partition);
if (m != null) {
m.ack(id.offset);
}
}
|
|
Like Feedback org.apache.storm.kafka.PartitionManager.KafkaMessageId |
|
|
Sample 166. Code Sample / Example / Snippet of org.apache.storm.trident.state.StateFactory | |
|
protected StormTopology getTopology() throws IOException {
final TridentTopology tridentTopology = new TridentTopology();
final SolrFieldsSpout spout = new SolrFieldsSpout();
final Stream stream = tridentTopology.newStream("SolrFieldsSpout", spout);
final StateFactory solrStateFactory = new SolrStateFactory(getSolrConfig(), getSolrMapper());
stream.partitionPersist(solrStateFactory, spout.getOutputFields(), new SolrUpdater(), new Fields());
return tridentTopology.build();
}
|
|
Like Feedback org.apache.storm.trident.state.StateFactory |
|
|
Sample 167. Code Sample / Example / Snippet of org.apache.storm.solr.spout.SolrFieldsSpout | |
|
protected StormTopology getTopology() throws IOException {
final TridentTopology tridentTopology = new TridentTopology();
final SolrFieldsSpout spout = new SolrFieldsSpout();
final Stream stream = tridentTopology.newStream("SolrFieldsSpout", spout);
final StateFactory solrStateFactory = new SolrStateFactory(getSolrConfig(), getSolrMapper());
stream.partitionPersist(solrStateFactory, spout.getOutputFields(), new SolrUpdater(), new Fields());
return tridentTopology.build();
}
|
|
Like Feedback org.apache.storm.solr.spout.SolrFieldsSpout |
|
|
Sample 168. Code Sample / Example / Snippet of org.apache.storm.solr.spout.SolrJsonSpout | |
|
protected StormTopology getTopology() throws IOException {
final TridentTopology topology = new TridentTopology();
final SolrJsonSpout spout = new SolrJsonSpout();
final Stream stream = topology.newStream("SolrJsonSpout", spout);
final StateFactory solrStateFactory = new SolrStateFactory(getSolrConfig(), getSolrMapper());
stream.partitionPersist(solrStateFactory, spout.getOutputFields(), new SolrUpdater(), new Fields());
return topology.build();
}
|
|
Like Feedback org.apache.storm.solr.spout.SolrJsonSpout |
|
|
Sample 169. Code Sample / Example / Snippet of org.apache.storm.generated.StormTopology | |
|
public void run(String[] args) throws Exception {
final StormTopology topology = getTopology();
final Config config = getConfig();
if (args.length == 0) {
submitTopologyLocalCluster(topology, config);
} else {
submitTopologyRemoteCluster(args[1], topology, config);
}
}
|
|
Like Feedback org.apache.storm.generated.StormTopology |
|
|
|
Sample 170. Code Sample / Example / Snippet of static org.apache.storm.solr.schema.SolrFieldTypeFinder.FieldTypeWrapper | |
|
private SolrInputDocument buildDocument(ITuple tuple) {
SolrInputDocument doc = new SolrInputDocument();
for (String tupleField : tuple.getFields()) {
FieldTypeWrapper fieldTypeWrapper = typeFinder.getFieldTypeWrapper(tupleField);
if (fieldTypeWrapper != null) {
FieldType fieldType = fieldTypeWrapper.getType();
if (fieldType.isMultiValued()) {
addMultivalueFieldToDoc(doc, tupleField, tuple);
} else {
addFieldToDoc(doc, tupleField, tuple);
}
} else {
log.debug("Field [{}] does NOT match static or dynamic field declared in schema. Not added to document", tupleField);
}
}
return doc;
}
|
|
Like Feedback static org.apache.storm.solr.schema.SolrFieldTypeFinder.FieldTypeWrapper |
|
|
Sample 171. Code Sample / Example / Snippet of org.apache.storm.solr.schema.FieldType | |
|
private SolrInputDocument buildDocument(ITuple tuple) {
SolrInputDocument doc = new SolrInputDocument();
for (String tupleField : tuple.getFields()) {
FieldTypeWrapper fieldTypeWrapper = typeFinder.getFieldTypeWrapper(tupleField);
if (fieldTypeWrapper != null) {
FieldType fieldType = fieldTypeWrapper.getType();
if (fieldType.isMultiValued()) {
addMultivalueFieldToDoc(doc, tupleField, tuple);
} else {
addFieldToDoc(doc, tupleField, tuple);
}
} else {
log.debug("Field [{}] does NOT match static or dynamic field declared in schema. Not added to document", tupleField);
}
}
return doc;
}
|
|
Like Feedback org.apache.storm.solr.schema.FieldType |
|
|
Sample 172. Code Sample / Example / Snippet of org.apache.storm.blobstore.BlobStoreFile | |
|
public void testGetFileLength() throws IOException {
FileSystem fs = dfscluster.getFileSystem();
Map conf = new HashMap();
String validKey = "validkeyBasic";
String testString = "testingblob";
TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, hadoopConf);
BlobStoreFile pfile = hbs.write(validKey, false);
SettableBlobMeta meta = new SettableBlobMeta();
meta.set_replication_factor(1);
pfile.setMetadata(meta);
OutputStream ios = pfile.getOutputStream();
ios.write(testString.getBytes(Charset.forName("UTF-8")));
ios.close();
assertEquals(testString.getBytes(Charset.forName("UTF-8")).length, pfile.getFileLength());
}
|
|
Like Feedback org.apache.storm.blobstore.BlobStoreFile |
|
|
Sample 173. Code Sample / Example / Snippet of org.apache.calcite.linq4j.tree.BlockBuilder | |
|
public static BlockStatement optimizeStatement(Statement statement) {
BlockBuilder b = new BlockBuilder(true);
if (!(statement instanceof BlockStatement)) {
b.add(statement);
} else {
BlockStatement bs = (BlockStatement) statement;
for (Statement stmt : bs.statements) {
b.add(stmt);
}
}
BlockStatement bs = b.toBlock();
return bs;
}
|
|
Like Feedback org.apache.calcite.linq4j.tree.BlockBuilder |
|
|
Sample 174. Code Sample / Example / Snippet of org.apache.calcite.linq4j.tree.Expression | |
|
public void prepareBuilder() {
b = new BlockBuilder(true);
}
@Test public void testReuseExpressionsFromUpperLevel() {
Expression x = b.append("x", Expressions.add(ONE, TWO));
BlockBuilder nested = new BlockBuilder(true, b);
Expression y = nested.append("y", Expressions.add(ONE, TWO));
nested.add(Expressions.return_(null, Expressions.add(y, y)));
b.add(nested.toBlock());
assertEquals(
"{
"
+ " final int x = 1 + 2;
"
+ " {
"
+ " return x + x;
"
+ " }
"
+ "}
",
b.toBlock().toString());
}
|
|
Like Feedback org.apache.calcite.linq4j.tree.Expression |
|
|
|
Sample 175. Code Sample / Example / Snippet of java.lang.reflect.Type | |
|
public static Type stripGenerics(Type type) {
if (type instanceof GenericArrayType) {
final Type componentType =
((GenericArrayType) type).getGenericComponentType();
return new ArrayType(stripGenerics(componentType));
} else if (type instanceof ParameterizedType) {
return ((ParameterizedType) type).getRawType();
} else {
return type;
}
}
|
|
Like Feedback java.lang.reflect.Type |
|
|
Sample 176. Code Sample / Example / Snippet of org.openjdk.jmh.runner.options.Options | |
|
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(PreconditionTest.class.getSimpleName())
.addProfiler(GCProfiler.class)
.detectJvmArgs()
.build();
new Runner(opt).run();
}
|
|
Like Feedback org.openjdk.jmh.runner.options.Options |
|
|
Sample 177. Code Sample / Example / Snippet of java.sql.Connection | |
|
public String prepareBindExecute(HrConnection state) throws SQLException {
Connection con = state.con;
Statement st = null;
ResultSet rs = null;
String ename = null;
try {
final PreparedStatement ps =
con.prepareStatement("select name from emps where empid = ?");
st = ps;
ps.setInt(1, state.id);
rs = ps.executeQuery();
rs.next();
ename = rs.getString(1);
} finally {
close(rs, st);
}
return ename;
}
|
|
Like Feedback java.sql.Connection |
|
|
Sample 178. Code Sample / Example / Snippet of java.sql.ResultSet | |
|
public String prepareBindExecute(HrConnection state) throws SQLException {
Connection con = state.con;
Statement st = null;
ResultSet rs = null;
String ename = null;
try {
final PreparedStatement ps =
con.prepareStatement("select name from emps where empid = ?");
st = ps;
ps.setInt(1, state.id);
rs = ps.executeQuery();
rs.next();
ename = rs.getString(1);
} finally {
close(rs, st);
}
return ename;
}
|
|
Like Feedback java.sql.ResultSet |
|
|
Sample 179. Code Sample / Example / Snippet of java.sql.Statement | |
|
public ForStatement(List<DeclarationStatement> declarations,
Expression condition, Expression post, Statement body) {
super(ExpressionType.For, Void.TYPE);
assert declarations != null;
assert body != null;
this.declarations = declarations; // may be empty, not null
this.condition = condition; // may be null
this.post = post; // may be null
this.body = body; // may be empty block, not null
}
@Override public ForStatement accept(Visitor visitor) {
visitor = visitor.preVisit(this);
List<DeclarationStatement> decls1 =
Expressions.acceptDeclarations(declarations, visitor);
final Expression condition1 =
condition == null ? null : condition.accept(visitor);
final Expression post1 = post == null ? null : post.accept(visitor);
final Statement body1 = body.accept(visitor);
return visitor.visit(this, decls1, condition1, post1, body1);
}
|
|
Like Feedback java.sql.Statement |
|
|
|
Sample 180. Code Sample / Example / Snippet of java.sql.PreparedStatement | |
|
public String prepareBindExecute(HrConnection state) throws SQLException {
Connection con = state.con;
Statement st = null;
ResultSet rs = null;
String ename = null;
try {
final PreparedStatement ps =
con.prepareStatement("select name from emps where empid = ?");
st = ps;
ps.setInt(1, state.id);
rs = ps.executeQuery();
rs.next();
ename = rs.getString(1);
} finally {
close(rs, st);
}
return ename;
}
|
|
Like Feedback java.sql.PreparedStatement |
|
|
Sample 181. Code Sample / Example / Snippet of com.mongodb.DBObject | |
|
private Enumerable<Object> find(DB mongoDb, String filterJson,
String projectJson, List<Map.Entry<String, Class>> fields) {
final DBCollection collection =
mongoDb.getCollection(collectionName);
final DBObject filter =
filterJson == null ? null : (DBObject) JSON.parse(filterJson);
final DBObject project =
projectJson == null ? null : (DBObject) JSON.parse(projectJson);
final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);
return new AbstractEnumerable<Object>() {
public Enumerator<Object> enumerator() {
final DBCursor cursor = collection.find(filter, project);
return new MongoEnumerator(cursor, getter);
}
};
}
|
|
Like Feedback com.mongodb.DBObject |
|
|
Sample 182. Code Sample / Example / Snippet of com.mongodb.DBCollection | |
|
private Enumerable<Object> find(DB mongoDb, String filterJson,
String projectJson, List<Map.Entry<String, Class>> fields) {
final DBCollection collection =
mongoDb.getCollection(collectionName);
final DBObject filter =
filterJson == null ? null : (DBObject) JSON.parse(filterJson);
final DBObject project =
projectJson == null ? null : (DBObject) JSON.parse(projectJson);
final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);
return new AbstractEnumerable<Object>() {
public Enumerator<Object> enumerator() {
final DBCursor cursor = collection.find(filter, project);
return new MongoEnumerator(cursor, getter);
}
};
}
|
|
Like Feedback com.mongodb.DBCollection |
|
|
Sample 183. Code Sample / Example / Snippet of org.apache.calcite.rel.type.RelDataType | |
|
public RelDataType getRowType(RelDataTypeFactory typeFactory) {
final RelDataType mapType =
typeFactory.createMapType(
typeFactory.createSqlType(SqlTypeName.VARCHAR),
typeFactory.createTypeWithNullability(
typeFactory.createSqlType(SqlTypeName.ANY), true));
return typeFactory.builder().add("_MAP", mapType).build();
}
|
|
Like Feedback org.apache.calcite.rel.type.RelDataType |
|
|
Sample 184. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptCluster | |
|
public RelNode toRel(
RelOptTable.ToRelContext context,
RelOptTable relOptTable) {
final RelOptCluster cluster = context.getCluster();
return new MongoTableScan(cluster, cluster.traitSetOf(MongoRel.CONVENTION),
relOptTable, this, null);
}
|
|
Like Feedback org.apache.calcite.plan.RelOptCluster |
|
|
|
Sample 185. Code Sample / Example / Snippet of java.util.Map | |
|
public Schema create(SchemaPlus parentSchema, String name,
Map<String, Object> operand) {
Map map = (Map) operand;
String host = (String) map.get("host");
String database = (String) map.get("database");
return new MongoSchema(host, database);
}
|
|
Like Feedback java.util.Map |
|
|
Sample 186. Code Sample / Example / Snippet of org.apache.calcite.plan.RelTraitSet | |
|
public RelNode convert(RelNode rel) {
final Sort sort = (Sort) rel;
final RelTraitSet traitSet =
sort.getTraitSet().replace(out)
.replace(sort.getCollation());
return new MongoSort(rel.getCluster(), traitSet,
convert(sort.getInput(), traitSet.replace(RelCollations.EMPTY)),
sort.getCollation(), sort.offset, sort.fetch);
}
|
|
Like Feedback org.apache.calcite.plan.RelTraitSet |
|
|
Sample 187. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalFilter | |
|
public RelNode convert(RelNode rel) {
final LogicalFilter filter = (LogicalFilter) rel;
final RelTraitSet traitSet = filter.getTraitSet().replace(out);
return new MongoFilter(
rel.getCluster(),
traitSet,
convert(filter.getInput(), out),
filter.getCondition());
}
|
|
Like Feedback org.apache.calcite.rel.logical.LogicalFilter |
|
|
Sample 188. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalAggregate | |
|
public RelNode convert(RelNode rel) {
final LogicalAggregate agg = (LogicalAggregate) rel;
final RelTraitSet traitSet =
agg.getTraitSet().replace(out);
try {
return new MongoAggregate(
rel.getCluster(),
traitSet,
convert(agg.getInput(), traitSet.simplify()),
agg.indicator,
agg.getGroupSet(),
agg.getGroupSets(),
agg.getAggCallList());
} catch (InvalidRelException e) {
LOGGER.warn(e.toString());
return null;
}
}
|
|
Like Feedback org.apache.calcite.rel.logical.LogicalAggregate |
|
|
Sample 189. Code Sample / Example / Snippet of org.apache.calcite.rex.RexNode | |
|
public static final RelOptRule[] RULES = {
MongoSortRule.INSTANCE,
MongoFilterRule.INSTANCE,
MongoProjectRule.INSTANCE,
MongoAggregateRule.INSTANCE,
};
static String isItem(RexCall call) {
if (call.getOperator() != SqlStdOperatorTable.ITEM) {
return null;
}
final RexNode op0 = call.operands.get(0);
final RexNode op1 = call.operands.get(1);
if (op0 instanceof RexInputRef
&& ((RexInputRef) op0).getIndex() == 0
&& op1 instanceof RexLiteral
&& ((RexLiteral) op1).getValue2() instanceof String) {
return (String) ((RexLiteral) op1).getValue2();
}
return null;
}
|
|
Like Feedback org.apache.calcite.rex.RexNode |
|
|
|
Sample 190. Code Sample / Example / Snippet of org.apache.calcite.rel.core.Sort | |
|
public RelNode convert(RelNode rel) {
final Sort sort = (Sort) rel;
final RelTraitSet traitSet =
sort.getTraitSet().replace(out)
.replace(sort.getCollation());
return new MongoSort(rel.getCluster(), traitSet,
convert(sort.getInput(), traitSet.replace(RelCollations.EMPTY)),
sort.getCollation(), sort.offset, sort.fetch);
}
|
|
Like Feedback org.apache.calcite.rel.core.Sort |
|
|
Sample 191. Code Sample / Example / Snippet of org.apache.calcite.linq4j.tree.Primitive | |
|
public static Type box(Type type) {
Primitive primitive = Primitive.of(type);
if (primitive != null) {
return primitive.boxClass;
} else {
return type;
}
}
|
|
Like Feedback org.apache.calcite.linq4j.tree.Primitive |
|
|
Sample 192. Code Sample / Example / Snippet of org.apache.calcite.plan.Convention | |
|
public interface MongoRel extends RelNode {
void implement(Implementor implementor);
Convention CONVENTION = new Convention.Impl("MONGO", MongoRel.class);
class Implementor {
final List<Pair<String, String>> list =
new ArrayList<Pair<String, String>>();
RelOptTable table;
MongoTable mongoTable;
public void add(String findOp, String aggOp) {
list.add(Pair.of(findOp, aggOp));
}
public void visitChild(int ordinal, RelNode input) {
assert ordinal == 0;
((MongoRel) input).implement(this);
}
}
}
|
|
Like Feedback org.apache.calcite.plan.Convention |
|
|
Sample 193. Code Sample / Example / Snippet of com.mongodb.MongoClient | |
|
public MongoSchema(String host, String database) {
super();
try {
MongoClient mongo = new MongoClient(host);
this.mongoDb = mongo.getDB(database);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
|
Like Feedback com.mongodb.MongoClient |
|
|
Sample 194. Code Sample / Example / Snippet of org.apache.calcite.rel.core.TableScan | |
|
public RelNode toRel(RelOptTable.ToRelContext context,
RelOptTable relOptTable) {
final RelOptCluster cluster = context.getCluster();
final TableScan scan = LogicalTableScan.create(cluster, relOptTable);
return DruidQuery.create(cluster,
cluster.traitSetOf(BindableConvention.INSTANCE), relOptTable, this,
ImmutableList.<RelNode>of(scan));
}
|
|
Like Feedback org.apache.calcite.rel.core.TableScan |
|
|
|
Sample 195. Code Sample / Example / Snippet of static org.apache.calcite.runtime.HttpUtils.post | |
|
public ForStatement visit(ForStatement forStatement,
List<DeclarationStatement> declarations, Expression condition,
Expression post, Statement body) {
return declarations.equals(forStatement.declarations)
&& condition == forStatement.condition
&& post == forStatement.post
&& body == forStatement.body
? forStatement
: Expressions.for_(declarations, condition, post, body);
}
|
|
Like Feedback static org.apache.calcite.runtime.HttpUtils.post |
|
|
Sample 196. Code Sample / Example / Snippet of com.fasterxml.jackson.core.JsonToken | |
|
private void expectScalarField(JsonParser parser, String name)
throws IOException {
expect(parser, JsonToken.FIELD_NAME);
if (!parser.getCurrentName().equals(name)) {
throw new RuntimeException("expected field " + name + ", got "
+ parser.getCurrentName());
}
final JsonToken t = parser.nextToken();
switch (t) {
case VALUE_NULL:
case VALUE_FALSE:
case VALUE_TRUE:
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
case VALUE_STRING:
break;
default:
throw new RuntimeException("expected scalar field, got " + t);
}
}
|
|
Like Feedback com.fasterxml.jackson.core.JsonToken |
|
|
Sample 197. Code Sample / Example / Snippet of java.util.Random | |
|
public Enumerable<Object[]> scan(DataContext root) {
final Random random = seed >= 0 ? new Random(seed) : new Random();
final Maze maze = new Maze(width, height);
final PrintWriter pw = new PrintWriter(System.out);
maze.layout(random, pw);
if (Maze.DEBUG) {
maze.print(pw, true);
}
return new AbstractEnumerable<Object[]>() {
public Enumerator<Object[]> enumerator() {
final Set<Integer> solutionSet;
if (solution) {
solutionSet = maze.solve(0, 0);
} else {
solutionSet = null;
}
return Linq4j.transform(maze.enumerator(solutionSet),
new Function1<String, Object[]>() {
public Object[] apply(String s) {
return new Object[] {s};
}
});
}
};
}
|
|
Like Feedback java.util.Random |
|
|
Sample 198. Code Sample / Example / Snippet of java.io.PrintWriter | |
|
public Enumerable<Object[]> scan(DataContext root) {
final Random random = seed >= 0 ? new Random(seed) : new Random();
final Maze maze = new Maze(width, height);
final PrintWriter pw = new PrintWriter(System.out);
maze.layout(random, pw);
if (Maze.DEBUG) {
maze.print(pw, true);
}
return new AbstractEnumerable<Object[]>() {
public Enumerator<Object[]> enumerator() {
final Set<Integer> solutionSet;
if (solution) {
solutionSet = maze.solve(0, 0);
} else {
solutionSet = null;
}
return Linq4j.transform(maze.enumerator(solutionSet),
new Function1<String, Object[]>() {
public Object[] apply(String s) {
return new Object[] {s};
}
});
}
};
}
|
|
Like Feedback java.io.PrintWriter |
|
|
Sample 199. Code Sample / Example / Snippet of java.net.URL | |
|
private String resourcePath(String path) {
final URL url = CsvTest.class.getResource("/" + path);
String s = url.toString();
if (s.startsWith("file:")) {
s = s.substring("file:".length());
}
return s;
}
|
|
Like Feedback java.net.URL |
|
|
|
Sample 200. Code Sample / Example / Snippet of org.apache.calcite.rel.type.RelProtoDataType | |
|
public CsvTable create(SchemaPlus schema, String name,
Map<String, Object> operand, RelDataType rowType) {
String fileName = (String) operand.get("file");
File file = new File(fileName);
final File base =
(File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);
if (base != null && !file.isAbsolute()) {
file = new File(base, fileName);
}
final RelProtoDataType protoRowType =
rowType != null ? RelDataTypeImpl.proto(rowType) : null;
return new CsvScannableTable(file, protoRowType);
}
|
|
Like Feedback org.apache.calcite.rel.type.RelProtoDataType |
|
|
Sample 201. Code Sample / Example / Snippet of org.apache.calcite.adapter.enumerable.PhysType | |
|
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
PhysType physType =
PhysTypeImpl.of(
implementor.getTypeFactory(),
getRowType(),
pref.preferArray());
if (table instanceof JsonTable) {
return implementor.result(
physType,
Blocks.toBlock(
Expressions.call(table.getExpression(JsonTable.class),
"enumerable")));
}
return implementor.result(
physType,
Blocks.toBlock(
Expressions.call(table.getExpression(CsvTranslatableTable.class),
"project", Expressions.constant(fields))));
}
|
|
Like Feedback org.apache.calcite.adapter.enumerable.PhysType |
|
|
Sample 202. Code Sample / Example / Snippet of java.util.TimeZone | |
|
private static final FastDateFormat TIME_FORMAT_TIMESTAMP;
static {
TimeZone gmt = TimeZone.getTimeZone("GMT");
TIME_FORMAT_DATE = FastDateFormat.getInstance("yyyy-MM-dd", gmt);
TIME_FORMAT_TIME = FastDateFormat.getInstance("HH:mm:ss", gmt);
TIME_FORMAT_TIMESTAMP =
FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", gmt);
}
|
|
Like Feedback java.util.TimeZone |
|
|
Sample 203. Code Sample / Example / Snippet of org.apache.calcite.rex.RexCall | |
|
private boolean addFilter(RexNode filter, Object[] filterValues) {
if (filter.isA(SqlKind.EQUALS)) {
final RexCall call = (RexCall) filter;
RexNode left = call.getOperands().get(0);
if (left.isA(SqlKind.CAST)) {
left = ((RexCall) left).operands.get(0);
}
final RexNode right = call.getOperands().get(1);
if (left instanceof RexInputRef
&& right instanceof RexLiteral) {
final int index = ((RexInputRef) left).getIndex();
if (filterValues[index] == null) {
filterValues[index] = ((RexLiteral) right).getValue2().toString();
return true;
}
}
}
return false;
}
|
|
Like Feedback org.apache.calcite.rex.RexCall |
|
|
Sample 204. Code Sample / Example / Snippet of com.fasterxml.jackson.databind.ObjectMapper | |
|
public JsonEnumerator(File file) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
List<Object> list = mapper.readValue(file, List.class);
enumerator = Linq4j.enumerator(list);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
|
Like Feedback com.fasterxml.jackson.databind.ObjectMapper |
|
|
|
Sample 205. Code Sample / Example / Snippet of java.io.File | |
|
public Schema create(SchemaPlus parentSchema, String name,
Map<String, Object> operand) {
final String directory = (String) operand.get("directory");
final File base =
(File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);
File directoryFile = new File(directory);
if (base != null && !directoryFile.isAbsolute()) {
directoryFile = new File(base, directory);
}
String flavorName = (String) operand.get("flavor");
CsvTable.Flavor flavor;
if (flavorName == null) {
flavor = CsvTable.Flavor.SCANNABLE;
} else {
flavor = CsvTable.Flavor.valueOf(flavorName.toUpperCase());
}
return new CsvSchema(directoryFile, flavor);
}
|
|
Like Feedback java.io.File |
|
|
Sample 206. Code Sample / Example / Snippet of static org.hamcrest.CoreMatchers.not | |
|
public ParameterExpression(int modifier, Type type, String name) {
super(ExpressionType.Parameter, type);
assert name != null : "name should not be null";
assert Character.isJavaIdentifierStart(name.charAt(0))
: "parameter name should be valid java identifier: "
+ name + ". The first character is invalid.";
this.modifier = modifier;
this.name = name;
}
|
|
Like Feedback static org.hamcrest.CoreMatchers.not |
|
|
Sample 207. Code Sample / Example / Snippet of org.elasticsearch.client.transport.TransportClient | |
|
private void open(List<InetSocketAddress> transportAddresses, Map<String, String> userConfig) {
final List<TransportAddress> transportNodes = new ArrayList<>(transportAddresses.size());
for (InetSocketAddress address : transportAddresses) {
transportNodes.add(new InetSocketTransportAddress(address));
}
Settings settings = Settings.settingsBuilder().put(userConfig).build();
final TransportClient transportClient = TransportClient.builder().settings(settings).build();
for (TransportAddress transport : transportNodes) {
transportClient.addTransportAddress(transport);
}
final List<DiscoveryNode> nodes = ImmutableList.copyOf(transportClient.connectedNodes());
if (nodes.isEmpty()) {
throw new RuntimeException("Cannot connect to any elasticsearch nodes");
}
client = transportClient;
}
|
|
Like Feedback org.elasticsearch.client.transport.TransportClient |
|
|
Sample 208. Code Sample / Example / Snippet of java.util.Calendar | |
|
private SparkHandlerImpl() {
classServer = new HttpServer(CLASS_DIR);
classServer.start();
System.setProperty("spark.repl.class.uri", classServer.uri());
final Calendar calendar = Calendar.getInstance();
classId = new AtomicInteger(
calendar.get(Calendar.HOUR_OF_DAY) * 10000
+ calendar.get(Calendar.MINUTE) * 100
+ calendar.get(Calendar.SECOND));
}
|
|
Like Feedback java.util.Calendar |
|
|
Sample 209. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalValues | |
|
private MongoValuesRule(MongoConvention out) {
super(
LogicalValues.class,
Convention.NONE,
out,
"MongoValuesRule");
}
@Override public RelNode convert(RelNode rel) {
LogicalValues valuesRel = (LogicalValues) rel;
return new MongoValuesRel(
valuesRel.getCluster(),
valuesRel.getRowType(),
valuesRel.getTuples(),
valuesRel.getTraitSet().plus(out));
}
|
|
Like Feedback org.apache.calcite.rel.logical.LogicalValues |
|
|
|
Sample 210. Code Sample / Example / Snippet of org.apache.calcite.rel.logical.LogicalCalc | |
|
public RelNode convert(RelNode rel) {
final LogicalCalc calc = (LogicalCalc) rel;
if (RexMultisetUtil.containsMultiset(calc.getProgram())) {
return null;
}
return new MongoCalcRel(
rel.getCluster(),
rel.getTraitSet().replace(out),
convert(
calc.getChild(),
calc.getTraitSet().replace(out)),
calc.getProgram(),
Project.Flags.Boxed);
}
|
|
Like Feedback org.apache.calcite.rel.logical.LogicalCalc |
|
|
Sample 211. Code Sample / Example / Snippet of org.apache.calcite.adapter.jdbc.JdbcImplementor | |
|
private String generateSql(SqlDialect dialect) {
final JdbcImplementor jdbcImplementor =
new JdbcImplementor(dialect,
(JavaTypeFactory) getCluster().getTypeFactory());
final JdbcImplementor.Result result =
jdbcImplementor.visitChild(0, getInput());
return result.asQuery().toSqlString(dialect).getSql();
}
|
|
Like Feedback org.apache.calcite.adapter.jdbc.JdbcImplementor |
|
|
Sample 212. Code Sample / Example / Snippet of org.apache.calcite.rex.RexInputRef | |
|
private String compareFieldWithLiteral(RexNode left, RexNode right, List<String> fieldNames) {
if (left.isA(SqlKind.CAST)) {
left = ((RexCall) left).getOperands().get(0);
}
if (left.isA(SqlKind.INPUT_REF) && right.isA(SqlKind.LITERAL)) {
final RexInputRef left1 = (RexInputRef) left;
String name = fieldNames.get(left1.getIndex());
return name;
} else {
return null;
}
}
|
|
Like Feedback org.apache.calcite.rex.RexInputRef |
|
|
Sample 213. Code Sample / Example / Snippet of org.apache.calcite.adapter.enumerable.EnumerableLimit | |
|
public void onMatch(RelOptRuleCall call) {
final EnumerableLimit limit = call.rel(0);
final RelNode converted = convert(limit);
if (converted != null) {
call.transformTo(converted);
}
}
|
|
Like Feedback org.apache.calcite.adapter.enumerable.EnumerableLimit |
|
|
Sample 214. Code Sample / Example / Snippet of org.apache.calcite.sql.type.SqlTypeName | |
|
private String translateOp2(String op, String name, RexLiteral right) {
if (op.equals("=")) {
partitionKeys.remove(name);
if (clusteringKeys.contains(name)) {
restrictedClusteringKeys++;
}
}
Object value = literalValue(right);
String valueString = value.toString();
if (value instanceof String) {
SqlTypeName typeName = rowType.getField(name, true, false).getType().getSqlTypeName();
if (typeName != SqlTypeName.CHAR) {
valueString = "'" + valueString + "'";
}
}
return name + " " + op + " " + valueString;
}
|
|
Like Feedback org.apache.calcite.sql.type.SqlTypeName |
|
|
|
Sample 215. Code Sample / Example / Snippet of org.apache.calcite.rex.RexLiteral | |
|
private String translateBinary2(String op, RexNode left, RexNode right) {
switch (right.getKind()) {
case LITERAL:
break;
default:
return null;
}
final RexLiteral rightLiteral = (RexLiteral) right;
switch (left.getKind()) {
case INPUT_REF:
final RexInputRef left1 = (RexInputRef) left;
String name = fieldNames.get(left1.getIndex());
return translateOp2(op, name, rightLiteral);
case CAST:
return translateBinary2(op, ((RexCall) left).operands.get(0), right);
default:
return null;
}
}
|
|
Like Feedback org.apache.calcite.rex.RexLiteral |
|
|
Sample 216. Code Sample / Example / Snippet of com.datastax.driver.core.DataType | |
|
public Void apply(RelNode node) {
CassandraSchema.this.addMaterializedViews();
return null;
}
});
}
RelProtoDataType getRelDataType(String columnFamily, boolean view) {
List<ColumnMetadata> columns;
if (view) {
columns = getKeyspace().getMaterializedView(columnFamily).getColumns();
} else {
columns = getKeyspace().getTable(columnFamily).getColumns();
}
final RelDataTypeFactory typeFactory =
new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
final RelDataTypeFactory.FieldInfoBuilder fieldInfo = typeFactory.builder();
for (ColumnMetadata column : columns) {
final String columnName = column.getName();
final DataType type = column.getType();
|
|
Like Feedback com.datastax.driver.core.DataType |
|
|
Sample 217. Code Sample / Example / Snippet of com.datastax.driver.core.Cluster | |
|
public CassandraSchema(String host, String keyspace, SchemaPlus parentSchema, String name) {
super();
this.keyspace = keyspace;
try {
Cluster cluster = Cluster.builder().addContactPoint(host).build();
this.session = cluster.connect(keyspace);
} catch (Exception e) {
throw new RuntimeException(e);
}
this.parentSchema = parentSchema;
this.name = name;
Hook.TRIMMED.add(new Function<RelNode, Void>() {
public Void apply(RelNode node) {
CassandraSchema.this.addMaterializedViews();
return null;
}
});
}
|
|
Like Feedback com.datastax.driver.core.Cluster |
|
|
Sample 218. Code Sample / Example / Snippet of org.apache.calcite.rel.type.RelDataTypeFactory | |
|
public Void apply(RelNode node) {
CassandraSchema.this.addMaterializedViews();
return null;
}
});
}
RelProtoDataType getRelDataType(String columnFamily, boolean view) {
List<ColumnMetadata> columns;
if (view) {
columns = getKeyspace().getMaterializedView(columnFamily).getColumns();
} else {
columns = getKeyspace().getTable(columnFamily).getColumns();
}
final RelDataTypeFactory typeFactory =
new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
final RelDataTypeFactory.FieldInfoBuilder fieldInfo = typeFactory.builder();
for (ColumnMetadata column : columns) {
|
|
Like Feedback org.apache.calcite.rel.type.RelDataTypeFactory |
|
|
Sample 219. Code Sample / Example / Snippet of com.datastax.driver.core.ResultSet | |
|
public String prepareBindExecute(HrConnection state) throws SQLException {
Connection con = state.con;
Statement st = null;
ResultSet rs = null;
String ename = null;
try {
final PreparedStatement ps =
con.prepareStatement("select name from emps where empid = ?");
st = ps;
ps.setInt(1, state.id);
rs = ps.executeQuery();
rs.next();
ename = rs.getString(1);
} finally {
close(rs, st);
}
return ename;
}
|
|
Like Feedback com.datastax.driver.core.ResultSet |
|
|
|
Sample 220. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptCost | |
|
public CassandraSort(RelOptCluster cluster, RelTraitSet traitSet,
RelNode child, RelCollation collation) {
super(cluster, traitSet, child, collation, null, null);
assert getConvention() == CassandraRel.CONVENTION;
assert getConvention() == child.getConvention();
}
@Override public RelOptCost computeSelfCost(RelOptPlanner planner,
RelMetadataQuery mq) {
RelOptCost cost = super.computeSelfCost(planner, mq);
if (!collation.getFieldCollations().isEmpty()) {
return cost.multiplyBy(0.05);
} else {
return cost;
}
}
|
|
Like Feedback org.apache.calcite.plan.RelOptCost |
|
|
Sample 221. Code Sample / Example / Snippet of java.sql.Array | |
|
private void dumpColumn(ResultSet resultSet, int i) throws SQLException {
final int t = resultSet.getMetaData().getColumnType(i);
switch (t) {
case Types.ARRAY:
final Array array = resultSet.getArray(i);
writer.print("{");
dump(array.getResultSet(), false);
writer.print("}");
return;
case Types.REAL:
writer.print(resultSet.getString(i));
writer.print("F");
return;
default:
writer.print(resultSet.getString(i));
}
}
|
|
Like Feedback java.sql.Array |
|
|
Sample 222. Code Sample / Example / Snippet of org.apache.calcite.tools.PigRelBuilder | |
|
public Fluent explainContains(String expected) throws ParseException {
final Ast.Program program = parseProgram(pig);
final PigRelBuilder builder =
PigRelBuilder.create(PigRelBuilderTest.config().build());
new Handler(builder).handle(program);
assertThat(Util.toLinux(RelOptUtil.toString(builder.peek())), is(expected));
return this;
}
|
|
Like Feedback org.apache.calcite.tools.PigRelBuilder |
|
|
Sample 223. Code Sample / Example / Snippet of java.io.StringWriter | |
|
public Fluent returns(Function<String, Void> checker) throws ParseException {
final Ast.Program program = parseProgram(pig);
final PigRelBuilder builder =
PigRelBuilder.create(PigRelBuilderTest.config().build());
final StringWriter sw = new StringWriter();
new CalciteHandler(builder, sw).handle(program);
checker.apply(Util.toLinux(sw.toString()));
return this;
}
|
|
Like Feedback java.io.StringWriter |
|
|
Sample 224. Code Sample / Example / Snippet of org.apache.calcite.rex.RexBuilder | |
|
private RexLiteral item(Ast.Node node, RelDataType type) {
final RexBuilder rexBuilder = builder.getRexBuilder();
switch (node.op) {
case LITERAL:
final Ast.Literal literal = (Ast.Literal) node;
return (RexLiteral) rexBuilder.makeLiteral(literal.value, type, false);
case TUPLE:
final Ast.Call tuple = (Ast.Call) node;
final ImmutableList<RexLiteral> list = tuple(tuple.operands, type);
return (RexLiteral) rexBuilder.makeLiteral(list, type, false);
case BAG:
final Ast.Call bag = (Ast.Call) node;
final ImmutableList<RexLiteral> list2 = bag(bag.operands, type);
return (RexLiteral) rexBuilder.makeLiteral(list2, type, false);
default:
throw new IllegalArgumentException("not a literal: " + node);
}
}
|
|
Like Feedback org.apache.calcite.rex.RexBuilder |
|
|
|
Sample 225. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Spacer | |
|
public MapType(SqlParserPos pos) {
super(pos, Op.MAP_TYPE);
this.keyType = new ScalarType(pos, "int");
this.valueType = new ScalarType(pos, "int");
}
}
static class UnParser {
final StringBuilder buf = new StringBuilder();
final Spacer spacer = new Spacer(0);
|
|
Like Feedback org.apache.calcite.avatica.util.Spacer |
|
|
Sample 226. Code Sample / Example / Snippet of org.apache.calcite.rel.externalize.RelJsonReader | |
|
public String apply(RelOptCluster cluster,
RelOptSchema relOptSchema, SchemaPlus rootSchema) {
SchemaPlus schema =
rootSchema.add("hr",
new ReflectiveSchema(new JdbcTest.HrSchema()));
final RelJsonReader reader =
new RelJsonReader(cluster, relOptSchema, schema);
RelNode node;
try {
node = reader.read(XX);
} catch (IOException e) {
throw new RuntimeException(e);
}
return RelOptUtil.dumpPlan(
"",
node,
false,
SqlExplainLevel.EXPPLAN_ATTRIBUTES);
}
|
|
Like Feedback org.apache.calcite.rel.externalize.RelJsonReader |
|
|
Sample 227. Code Sample / Example / Snippet of org.apache.calcite.plan.RelTrait | |
|
public void registerConverterRule(
RelOptPlanner planner,
ConverterRule converterRule) {
if (!converterRule.isGuaranteed()) {
return;
}
RelTrait fromTrait = converterRule.getInTrait();
RelTrait toTrait = converterRule.getOutTrait();
conversionMap.put(fromTrait, Pair.of(toTrait, converterRule));
}
|
|
Like Feedback org.apache.calcite.plan.RelTrait |
|
|
Sample 228. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptAbstractTable | |
|
public RelDataType getRowType(RelDataTypeFactory typeFactory) {
return typeFactory.builder()
.add("s", stringType)
.add("i", integerType).build();
}
@Override public Statistic getStatistic() {
return Statistics.of(100d, ImmutableList.<ImmutableBitSet>of(),
ImmutableList.of(COLLATION));
}
};
final RelOptAbstractTable t1 = new RelOptAbstractTable(relOptSchema,
"t1", table.getRowType(typeFactory)) {
|
|
Like Feedback org.apache.calcite.plan.RelOptAbstractTable |
|
|
Sample 229. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlMonotonicity | |
|
public void checkMonotonic(String query,
SqlMonotonicity expectedMonotonicity) {
SqlValidator validator = getValidator();
SqlNode n = parseAndValidate(validator, query);
final RelDataType rowType = validator.getValidatedNodeType(n);
final SqlValidatorNamespace selectNamespace = validator.getNamespace(n);
final String field0 = rowType.getFieldList().get(0).getName();
final SqlMonotonicity monotonicity =
selectNamespace.getMonotonicity(field0);
assertThat(monotonicity, equalTo(expectedMonotonicity));
}
|
|
Like Feedback org.apache.calcite.sql.validate.SqlMonotonicity |
|
|
|
Sample 230. Code Sample / Example / Snippet of org.apache.calcite.sql.parser.SqlParserPos | |
|
public int compare(SqlNode o1, SqlNode o2) {
final SqlParserPos pos0 = o1.getParserPosition();
final SqlParserPos pos1 = o2.getParserPosition();
int c = -Utilities.compare(
pos0.getLineNum(), pos1.getLineNum());
if (c != 0) {
return c;
}
return -Utilities.compare(
pos0.getColumnNum(), pos1.getColumnNum());
}
|
|
Like Feedback org.apache.calcite.sql.parser.SqlParserPos |
|
|
Sample 231. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorNamespace | |
|
public void checkMonotonic(String query,
SqlMonotonicity expectedMonotonicity) {
SqlValidator validator = getValidator();
SqlNode n = parseAndValidate(validator, query);
final RelDataType rowType = validator.getValidatedNodeType(n);
final SqlValidatorNamespace selectNamespace = validator.getNamespace(n);
final String field0 = rowType.getFieldList().get(0).getName();
final SqlMonotonicity monotonicity =
selectNamespace.getMonotonicity(field0);
assertThat(monotonicity, equalTo(expectedMonotonicity));
}
|
|
Like Feedback org.apache.calcite.sql.validate.SqlValidatorNamespace |
|
|
Sample 232. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlSelect | |
|
public SqlMonotonicity getMonotonicity(String sql) {
final SqlValidator validator = getValidator();
final SqlNode node = parseAndValidate(validator, sql);
final SqlSelect select = (SqlSelect) node;
final SqlNode selectItem0 = select.getSelectList().get(0);
final SqlValidatorScope scope = validator.getSelectScope(select);
return selectItem0.getMonotonicity(scope);
}
|
|
Like Feedback org.apache.calcite.sql.SqlSelect |
|
|
Sample 233. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidator | |
|
public void checkFieldOrigin(String sql, String fieldOriginList) {
SqlValidator validator = getValidator();
SqlNode n = parseAndValidate(validator, sql);
final List<List<String>> list = validator.getFieldOrigins(n);
final StringBuilder buf = new StringBuilder("{");
int i = 0;
for (List<String> strings : list) {
if (i++ > 0) {
buf.append(", ");
}
if (strings == null) {
buf.append("null");
} else {
int j = 0;
for (String s : strings) {
if (j++ > 0) {
buf.append('.');
}
buf.append(s);
}
}
}
buf.append("}");
assertEquals(fieldOriginList, buf.toString());
}
|
|
Like Feedback org.apache.calcite.sql.validate.SqlValidator |
|
|
Sample 234. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlNode | |
|
public RelDataType getResultType(String sql) {
SqlValidator validator = getValidator();
SqlNode n = parseAndValidate(validator, sql);
return validator.getValidatedNodeType(n);
}
|
|
Like Feedback org.apache.calcite.sql.SqlNode |
|
|
|
Sample 235. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorScope | |
|
public SqlMonotonicity getMonotonicity(String sql) {
final SqlValidator validator = getValidator();
final SqlNode node = parseAndValidate(validator, sql);
final SqlSelect select = (SqlSelect) node;
final SqlNode selectItem0 = select.getSelectList().get(0);
final SqlValidatorScope scope = validator.getSelectScope(select);
return selectItem0.getMonotonicity(scope);
}
|
|
Like Feedback org.apache.calcite.sql.validate.SqlValidatorScope |
|
|
Sample 236. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlCall | |
|
public void checkIntervalConv(String sql, String expected) {
SqlValidator validator = getValidator();
final SqlCall n = (SqlCall) parseAndValidate(validator, sql);
SqlNode node = null;
for (int i = 0; i < n.operandCount(); i++) {
node = stripAs(n.operand(i));
if (node instanceof SqlCall) {
node = ((SqlCall) node).operand(0);
break;
}
}
assertNotNull(node);
SqlIntervalLiteral intervalLiteral = (SqlIntervalLiteral) node;
SqlIntervalLiteral.IntervalValue interval =
(SqlIntervalLiteral.IntervalValue) intervalLiteral.getValue();
long l =
interval.getIntervalQualifier().isYearMonth()
? SqlParserUtil.intervalToMonths(interval)
: SqlParserUtil.intervalToMillis(interval);
String actual = l + "";
assertEquals(expected, actual);
}
|
|
Like Feedback org.apache.calcite.sql.SqlCall |
|
|
Sample 237. Code Sample / Example / Snippet of org.apache.calcite.sql.pretty.SqlPrettyWriter | |
|
protected void assertPrintsTo(
boolean newlines,
final String sql,
String expected) {
final SqlNode node = parseQuery(sql);
final SqlPrettyWriter prettyWriter =
new SqlPrettyWriter(SqlDialect.DUMMY);
prettyWriter.setAlwaysUseParentheses(false);
if (newlines) {
prettyWriter.setCaseClausesOnNewLines(true);
}
String actual = prettyWriter.format(node);
getDiffRepos().assertEquals("formatted", expected, actual);
final String actual2 = actual.replaceAll("`", """);
final SqlNode node2 = parseQuery(actual2);
assertTrue(node.equalsDeep(node2, Litmus.THROW));
}
|
|
Like Feedback org.apache.calcite.sql.pretty.SqlPrettyWriter |
|
|
Sample 238. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlConformance | |
|
public AdvisorTesterFactory() {
super(DefaultSqlTestFactory.INSTANCE);
}
@Override public SqlValidator getValidator(SqlTestFactory factory) {
final RelDataTypeFactory typeFactory =
new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
final SqlConformance conformance = (SqlConformance) get("conformance");
final boolean caseSensitive = (Boolean) factory.get("caseSensitive");
return new SqlAdvisorValidator(
SqlStdOperatorTable.instance(),
new MockCatalogReader(typeFactory, caseSensitive).init(),
typeFactory,
conformance);
}
|
|
Like Feedback org.apache.calcite.sql.validate.SqlConformance |
|
|
Sample 239. Code Sample / Example / Snippet of org.apache.calcite.sql.advise.SqlAdvisor | |
|
protected void assertHint(
String sql,
String expectedResults) throws Exception {
SqlValidatorWithHints validator =
(SqlValidatorWithHints) tester.getValidator();
SqlAdvisor advisor = tester.getFactory().createAdvisor(validator);
SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql);
List<SqlMoniker> results =
advisor.getCompletionHints(
sap.sql,
sap.pos);
Assert.assertEquals(
expectedResults, convertCompletionHints(results));
}
|
|
Like Feedback org.apache.calcite.sql.advise.SqlAdvisor |
|
|
|
Sample 240. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlOperatorTable | |
|
public SqlOperatorTable createOperatorTable(SqlTestFactory factory) {
final SqlOperatorTable opTab0 =
(SqlOperatorTable) factory.get("operatorTable");
MockSqlOperatorTable opTab = new MockSqlOperatorTable(opTab0);
MockSqlOperatorTable.addRamp(opTab);
return opTab;
}
|
|
Like Feedback org.apache.calcite.sql.SqlOperatorTable |
|
|
Sample 241. Code Sample / Example / Snippet of static org.apache.calcite.sql.test.SqlTester.TypeChecker | |
|
public void checkScalarExact(
String expression,
String expectedType,
String result) {
for (String sql : buildQueries(expression)) {
TypeChecker typeChecker =
new SqlTests.StringTypeChecker(expectedType);
check(sql, typeChecker, result, 0);
}
}
|
|
Like Feedback static org.apache.calcite.sql.test.SqlTester.TypeChecker |
|
|
Sample 242. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Quoting | |
|
private static final ThreadLocal<boolean[]> LINUXIFY =
new ThreadLocal<boolean[]>() {
@Override protected boolean[] initialValue() {
return new boolean[] {true};
}
};
Quoting quoting = Quoting.DOUBLE_QUOTE;
|
|
Like Feedback org.apache.calcite.avatica.util.Quoting |
|
|
Sample 243. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Casing | |
|
private static final ThreadLocal<boolean[]> LINUXIFY =
new ThreadLocal<boolean[]>() {
@Override protected boolean[] initialValue() {
return new boolean[] {true};
}
};
Quoting quoting = Quoting.DOUBLE_QUOTE;
Casing unquotedCasing = Casing.TO_UPPER;
|
|
Like Feedback org.apache.calcite.avatica.util.Casing |
|
|
Sample 244. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlSetOption | |
|
private static void checkSqlSetOptionSame(SqlNode node) {
SqlSetOption opt = (SqlSetOption) node;
SqlNode[] sqlNodes = new SqlNode[opt.getOperandList().size()];
SqlCall returned = opt.getOperator().createCall(
opt.getFunctionQuantifier(),
opt.getParserPosition(),
opt.getOperandList().toArray(sqlNodes));
assertThat((Class) opt.getClass(), equalTo((Class) returned.getClass()));
SqlSetOption optRet = (SqlSetOption) returned;
assertThat(optRet.getScope(), is(opt.getScope()));
assertThat(optRet.getName(), is(opt.getName()));
assertThat(optRet.getFunctionQuantifier(), is(opt.getFunctionQuantifier()));
assertThat(optRet.getParserPosition(), is(opt.getParserPosition()));
assertThat(optRet.getValue(), is(opt.getValue()));
assertThat(optRet.toString(), is(opt.toString()));
}
|
|
Like Feedback org.apache.calcite.sql.SqlSetOption |
|
|
|
Sample 245. Code Sample / Example / Snippet of org.apache.calcite.tools.FrameworkConfig | |
|
public Object get(String name) {
return null;
}
}
@Before public void setUp() {
rootSchema = Frameworks.createRootSchema(true);
final FrameworkConfig config = Frameworks.newConfigBuilder()
|
|
Like Feedback org.apache.calcite.tools.FrameworkConfig |
|
|
Sample 246. Code Sample / Example / Snippet of sqlline.SqlLine | |
|
private static Pair<SqlLine.Status, String> run(String... args)
throws Throwable {
SqlLine sqlline = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = new PrintStream(os);
sqlline.setOutputStream(sqllineOutputStream);
sqlline.setErrorStream(sqllineOutputStream);
SqlLine.Status status = SqlLine.Status.OK;
Bug.upgrade("[sqlline-35] Make Sqlline.begin public");
return Pair.of(status, os.toString("UTF8"));
}
|
|
Like Feedback sqlline.SqlLine |
|
|
Sample 247. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream | |
|
private static Pair<SqlLine.Status, String> run(String... args)
throws Throwable {
SqlLine sqlline = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = new PrintStream(os);
sqlline.setOutputStream(sqllineOutputStream);
sqlline.setErrorStream(sqllineOutputStream);
SqlLine.Status status = SqlLine.Status.OK;
Bug.upgrade("[sqlline-35] Make Sqlline.begin public");
return Pair.of(status, os.toString("UTF8"));
}
|
|
Like Feedback java.io.ByteArrayOutputStream |
|
|
Sample 248. Code Sample / Example / Snippet of org.apache.calcite.sql.type.SqlTypeFactoryImpl | |
|
public void testLeastRestrictiveWithAny() {
SqlTypeFactoryImpl typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
final RelDataType sqlBigInt = typeFactory.createSqlType(SqlTypeName.BIGINT);
final RelDataType sqlAny = typeFactory.createSqlType(SqlTypeName.ANY);
RelDataType leastRestrictive =
typeFactory.leastRestrictive(Lists.newArrayList(sqlBigInt, sqlAny));
assertEquals(leastRestrictive.getSqlTypeName(), SqlTypeName.ANY);
}
|
|
Like Feedback org.apache.calcite.sql.type.SqlTypeFactoryImpl |
|
|
Sample 249. Code Sample / Example / Snippet of org.apache.calcite.plan.RelOptTable | |
|
public RelOptTable getTableForMember(
List<String> names,
final String datasetName,
boolean[] usedDataset) {
final RelOptTable table = getTableForMember(names);
RelOptTable datasetTable =
new DelegatingRelOptTable(table) {
public List<String> getQualifiedName() {
final List<String> list =
new ArrayList<>(super.getQualifiedName());
list.set(
list.size() - 1,
list.get(list.size() - 1) + ":" + datasetName);
return ImmutableList.copyOf(list);
}
};
if (usedDataset != null) {
assert usedDataset.length == 1;
usedDataset[0] = true;
}
return datasetTable;
}
|
|
Like Feedback org.apache.calcite.plan.RelOptTable |
|
|
|
Sample 250. Code Sample / Example / Snippet of org.apache.calcite.sql2rel.RelFieldTrimmer | |
|
public void assertConvertsTo(
String sql,
String plan,
boolean trim) {
String sql2 = getDiffRepos().expand("sql", sql);
RelNode rel = convertSqlToRel(sql2).project();
assertTrue(rel != null);
assertValid(rel);
if (trim) {
final RelBuilder relBuilder =
RelFactories.LOGICAL_BUILDER.create(rel.getCluster(), null);
final RelFieldTrimmer trimmer = createFieldTrimmer(relBuilder);
rel = trimmer.trim(rel);
assertTrue(rel != null);
assertValid(rel);
}
String actual = NL + RelOptUtil.toString(rel);
diffRepos.assertEquals("plan", plan, actual);
}
|
|
Like Feedback org.apache.calcite.sql2rel.RelFieldTrimmer |
|
|
Sample 251. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorTable | |
|
public RelOptTable getTableForMember(List<String> names) {
final SqlValidatorTable table = catalogReader.getTable(names);
final RelDataType rowType = table.getRowType();
final List<RelCollation> collationList = deduceMonotonicity(table);
if (names.size() < 3) {
String[] newNames2 = {"CATALOG", "SALES", ""};
List<String> newNames = new ArrayList<>();
int i = 0;
while (newNames.size() < newNames2.length) {
newNames.add(i, newNames2[i]);
++i;
}
names = newNames;
}
return createColumnSet(table, names, rowType, collationList);
}
|
|
Like Feedback org.apache.calcite.sql.validate.SqlValidatorTable |
|
|
Sample 252. Code Sample / Example / Snippet of org.apache.calcite.tools.RelBuilder | |
|
public void assertConvertsTo(
String sql,
String plan,
boolean trim) {
String sql2 = getDiffRepos().expand("sql", sql);
RelNode rel = convertSqlToRel(sql2).project();
assertTrue(rel != null);
assertValid(rel);
if (trim) {
final RelBuilder relBuilder =
RelFactories.LOGICAL_BUILDER.create(rel.getCluster(), null);
final RelFieldTrimmer trimmer = createFieldTrimmer(relBuilder);
rel = trimmer.trim(rel);
assertTrue(rel != null);
assertValid(rel);
}
String actual = NL + RelOptUtil.toString(rel);
diffRepos.assertEquals("plan", plan, actual);
}
|
|
Like Feedback org.apache.calcite.tools.RelBuilder |
|
|
Sample 253. Code Sample / Example / Snippet of java.io.BufferedWriter | |
|
private void addThreadWriters(Integer threadId) {
StringWriter w = new StringWriter();
BufferedWriter bw = new BufferedWriter(w);
threadStringWriters.put(threadId, w);
threadBufferedWriters.put(threadId, bw);
threadResultsReaders.put(threadId, new ResultsReader(bw));
}
|
|
Like Feedback java.io.BufferedWriter |
|
|
Sample 254. Code Sample / Example / Snippet of java.util.regex.Matcher | |
|
private void defineVariables(String line) {
Matcher varDefn = matchesVarDefn.matcher(line);
if (varDefn.lookingAt()) {
String var = varDefn.group(1);
String val = varDefn.group(2);
vars.define(var, val);
} else {
String[] words = splitWords.split(line);
for (String var : words) {
String value = System.getenv(var);
vars.define(var, value);
}
}
}
|
|
Like Feedback java.util.regex.Matcher |
|
|
|
Sample 255. Code Sample / Example / Snippet of java.util.StringTokenizer | |
|
private List<String> tokenize(String s) {
List<String> result = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(s);
while (tokenizer.hasMoreTokens()) {
result.add(tokenizer.nextToken());
}
return result;
}
|
|
Like Feedback java.util.StringTokenizer |
|
|
Sample 256. Code Sample / Example / Snippet of org.hamcrest.Matcher | |
|
private void defineVariables(String line) {
Matcher varDefn = matchesVarDefn.matcher(line);
if (varDefn.lookingAt()) {
String var = varDefn.group(1);
String val = varDefn.group(2);
vars.define(var, val);
} else {
String[] words = splitWords.split(line);
for (String var : words) {
String value = System.getenv(var);
vars.define(var, value);
}
}
}
|
|
Like Feedback org.hamcrest.Matcher |
|
|
Sample 257. Code Sample / Example / Snippet of org.apache.calcite.rel.metadata.RelColumnOrigin | |
|
private void checkSingleColumnOrigin(
String sql,
String expectedTableName,
String expectedColumnName,
boolean expectedDerived) {
Set<RelColumnOrigin> result = checkColumnOrigin(sql);
assertTrue(result != null);
assertEquals(
1,
result.size());
RelColumnOrigin rco = result.iterator().next();
checkColumnOrigin(
rco, expectedTableName, expectedColumnName, expectedDerived);
}
|
|
Like Feedback org.apache.calcite.rel.metadata.RelColumnOrigin |
|
|
Sample 258. Code Sample / Example / Snippet of org.apache.calcite.util.JsonBuilder | |
|
public final AssertThat withMaterializations(String model,
Function<JsonBuilder, List<Object>> materializations) {
final JsonBuilder builder = new JsonBuilder();
final List<Object> list = materializations.apply(builder);
final String buf =
"materializations: " + builder.toJsonString(list);
final String model2;
if (model.contains("defaultSchema: 'foodmart'")) {
model2 = model.replace("]",
", { name: 'mat', "
+ buf
+ "}
"
+ "]");
} else if (model.contains("type: ")) {
model2 = model.replace("type: ",
buf + ",
"
+ "type: ");
} else {
throw new AssertionError("do not know where to splice");
}
return withModel(model2);
}
|
|
Like Feedback org.apache.calcite.util.JsonBuilder |
|
|
Sample 259. Code Sample / Example / Snippet of org.apache.calcite.schema.SchemaPlus | |
|
public Connection apply(Connection connection) throws SQLException {
if (schema != null) {
CalciteConnection con = connection.unwrap(CalciteConnection.class);
SchemaPlus rootSchema = con.getRootSchema();
rootSchema.add(name, schema);
}
connection.setSchema(name);
return connection;
}
|
|
Like Feedback org.apache.calcite.schema.SchemaPlus |
|
|
|
Sample 260. Code Sample / Example / Snippet of java.util.Collection | |
|
public Void apply(ResultSet resultSet) {
++executeCount;
try {
final Collection result =
CalciteAssert.toStringList(resultSet,
ordered ? new ArrayList<String>() : new TreeSet<String>());
if (executeCount == 1) {
expected = result;
} else {
if (!expected.equals(result)) {
assertThat(newlineList(result), equalTo(newlineList(expected)));
fail("oops");
}
}
return null;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
|
|
Like Feedback java.util.Collection |
|
|
Sample 261. Code Sample / Example / Snippet of org.apache.calcite.jdbc.CalciteConnection | |
|
public Connection apply(Connection connection) throws SQLException {
if (schema != null) {
CalciteConnection con = connection.unwrap(CalciteConnection.class);
SchemaPlus rootSchema = con.getRootSchema();
rootSchema.add(name, schema);
}
connection.setSchema(name);
return connection;
}
|
|
Like Feedback org.apache.calcite.jdbc.CalciteConnection |
|
|
Sample 262. Code Sample / Example / Snippet of org.apache.calcite.DataContext | |
|
public <T> AssertThat doWithDataContext(Function<DataContext, T> fn)
throws Exception {
CalciteConnection connection =
(CalciteConnection) connectionFactory.createConnection();
final DataContext dataContext = CalciteMetaImpl.createDataContext(
connection);
try {
T t = fn.apply(dataContext);
Util.discard(t);
return AssertThat.this;
} finally {
connection.close();
}
}
|
|
Like Feedback org.apache.calcite.DataContext |
|
|
Sample 263. Code Sample / Example / Snippet of org.apache.calcite.plan.hep.HepProgram | |
|
protected DiffRepository getDiffRepos() {
return DiffRepository.lookup(RelOptRulesTest.class);
}
@Test public void testReduceNestedCaseWhen() {
HepProgram preProgram = new HepProgramBuilder()
.build();
HepProgramBuilder builder = new HepProgramBuilder();
builder.addRuleClass(ReduceExpressionsRule.class);
HepPlanner hepPlanner = new HepPlanner(builder.build());
hepPlanner.addRule(ReduceExpressionsRule.FILTER_INSTANCE);
final String sql = "select sal
"
+ "from emp
"
+ "where case when (sal = 1000) then
"
+ "(case when sal = 1000 then null else 1 end is null) else
"
+ "(case when sal = 2000 then null else 1 end is null) end is true";
checkPlanning(tester, preProgram, hepPlanner, sql);
}
|
|
Like Feedback org.apache.calcite.plan.hep.HepProgram |
|
|
Sample 264. Code Sample / Example / Snippet of org.apache.calcite.plan.hep.HepPlanner | |
|
protected DiffRepository getDiffRepos() {
return DiffRepository.lookup(RelOptRulesTest.class);
}
@Test public void testReduceNestedCaseWhen() {
HepProgram preProgram = new HepProgramBuilder()
.build();
HepProgramBuilder builder = new HepProgramBuilder();
builder.addRuleClass(ReduceExpressionsRule.class);
HepPlanner hepPlanner = new HepPlanner(builder.build());
hepPlanner.addRule(ReduceExpressionsRule.FILTER_INSTANCE);
final String sql = "select sal
"
+ "from emp
"
+ "where case when (sal = 1000) then
"
+ "(case when sal = 1000 then null else 1 end is null) else
"
+ "(case when sal = 2000 then null else 1 end is null) end is true";
checkPlanning(tester, preProgram, hepPlanner, sql);
}
|
|
Like Feedback org.apache.calcite.plan.hep.HepPlanner |
|
|
|
Sample 265. Code Sample / Example / Snippet of org.apache.calcite.plan.hep.HepProgramBuilder | |
|
protected DiffRepository getDiffRepos() {
return DiffRepository.lookup(RelOptRulesTest.class);
}
@Test public void testReduceNestedCaseWhen() {
HepProgram preProgram = new HepProgramBuilder()
.build();
HepProgramBuilder builder = new HepProgramBuilder();
builder.addRuleClass(ReduceExpressionsRule.class);
HepPlanner hepPlanner = new HepPlanner(builder.build());
hepPlanner.addRule(ReduceExpressionsRule.FILTER_INSTANCE);
final String sql = "select sal
"
+ "from emp
"
+ "where case when (sal = 1000) then
"
+ "(case when sal = 1000 then null else 1 end is null) else
"
+ "(case when sal = 2000 then null else 1 end is null) end is true";
checkPlanning(tester, preProgram, hepPlanner, sql);
}
|
|
Like Feedback org.apache.calcite.plan.hep.HepProgramBuilder |
|
|
Sample 266. Code Sample / Example / Snippet of java.math.BigDecimal | |
|
public Void apply(ResultSet a0) {
try {
final BigDecimal bigDecimal = a0.getBigDecimal(1);
fail("expected error, got " + bigDecimal);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (NoSuchElementException e) {
}
try {
assertTrue(a0.next());
final BigDecimal bigDecimal = a0.getBigDecimal(1);
assertThat(bigDecimal, equalTo(BigDecimal.valueOf(2008)));
} catch (SQLException e) {
throw new RuntimeException(e);
}
return null;
}
|
|
Like Feedback java.math.BigDecimal |
|
|
Sample 267. Code Sample / Example / Snippet of static org.hamcrest.CoreMatchers.is | |
|
public static final List<Pair<String, String>> FOODMART_QUERIES =
querify(QUERIES);
@Test public void testJanino169() {
CalciteAssert.that()
.with(CalciteAssert.Config.JDBC_FOODMART)
.query(
"select "time_id" from "foodmart"."time_by_day" as "t"
")
.returnsCount(730);
}
|
|
Like Feedback static org.hamcrest.CoreMatchers.is |
|
|
Sample 268. Code Sample / Example / Snippet of java.sql.DatabaseMetaData | |
|
private String mm(int majorVersion, int minorVersion) {
return majorVersion + "." + minorVersion;
}
@Test public void testMetaDataColumns()
throws ClassNotFoundException, SQLException {
Connection connection = CalciteAssert
.that(CalciteAssert.Config.REGULAR).connect();
DatabaseMetaData metaData = connection.getMetaData();
ResultSet resultSet = metaData.getColumns(null, null, null, null);
assertTrue(resultSet.next()); // there's something
String name = resultSet.getString(4);
int type = resultSet.getInt(5);
String typeName = resultSet.getString(6);
int columnSize = resultSet.getInt(7);
int decimalDigits = resultSet.getInt(9);
int numPrecRadix = resultSet.getInt(10);
int charOctetLength = resultSet.getInt(16);
String isNullable = resultSet.getString(18);
resultSet.close();
connection.close();
}
|
|
Like Feedback java.sql.DatabaseMetaData |
|
|
Sample 269. Code Sample / Example / Snippet of org.apache.calcite.schema.TableFunction | |
|
private Connection getConnectionWithMultiplyFunction()
throws ClassNotFoundException, SQLException {
Connection connection =
DriverManager.getConnection("jdbc:calcite:");
CalciteConnection calciteConnection =
connection.unwrap(CalciteConnection.class);
SchemaPlus rootSchema = calciteConnection.getRootSchema();
SchemaPlus schema = rootSchema.add("s", new AbstractSchema());
final TableFunction table =
TableFunctionImpl.create(Smalls.MULTIPLICATION_TABLE_METHOD);
schema.add("multiplication", table);
return connection;
}
|
|
Like Feedback org.apache.calcite.schema.TableFunction |
|
|
|
Sample 270. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.TimeUnitRange | |
|
private void checkTimestampString(String s, long d) {
assertThat(unixTimestampToString(d), equalTo(s));
assertThat(timestampStringToUnixDate(s), equalTo(d));
}
@Test public void testIntervalYearMonthToString() {
TimeUnitRange range = TimeUnitRange.YEAR_TO_MONTH;
assertEquals("+0-00", intervalYearMonthToString(0, range));
assertEquals("+1-00", intervalYearMonthToString(12, range));
assertEquals("+1-01", intervalYearMonthToString(13, range));
assertEquals("-1-01", intervalYearMonthToString(-13, range));
}
|
|
Like Feedback org.apache.calcite.avatica.util.TimeUnitRange |
|
|
Sample 271. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.ByteString | |
|
private void thereAndBack(byte[] bytes) {
final ByteString byteString = new ByteString(bytes);
final byte[] bytes2 = byteString.getBytes();
assertThat(bytes, equalTo(bytes2));
final String base64String = byteString.toBase64String();
final ByteString byteString1 = ByteString.ofBase64(base64String);
assertThat(byteString, equalTo(byteString1));
}
|
|
Like Feedback org.apache.calcite.avatica.util.ByteString |
|
|
Sample 272. Code Sample / Example / Snippet of org.apache.hc.core5.http.bootstrap.io.HttpServer | |
|
public ListenerEndpoint getListenerEndpoint() {
final HttpServer local = this.server;
if (local != null) {
return this.server.getEndpoint();
}
throw new IllegalStateException("Server not running");
}
|
|
Like Feedback org.apache.hc.core5.http.bootstrap.io.HttpServer |
|
|
Sample 273. Code Sample / Example / Snippet of org.apache.hc.core5.http.impl.io.HttpService | |
|
public void testBasicProtocolDowngrade() throws Exception {
final HttpProcessor httprocessor = Mockito.mock(HttpProcessor.class);
final ConnectionReuseStrategy connReuseStrategy = Mockito.mock(ConnectionReuseStrategy.class);
final HttpResponseFactory responseFactory = Mockito.mock(HttpResponseFactory.class);
final HttpRequestHandlerMapper handlerResolver = Mockito.mock(HttpRequestHandlerMapper.class);
final HttpService httpservice = new HttpService(
httprocessor,
connReuseStrategy,
responseFactory,
handlerResolver);
final HttpCoreContext context = HttpCoreContext.create();
final HttpServerConnection conn = Mockito.mock(HttpServerConnection.class);
final HttpRequest request = new BasicHttpRequest("GET", "/", new HttpVersion(20, 45));
Mockito.when(conn.receiveRequestHeader()).thenReturn(request);
final HttpResponse response = new BasicHttpResponse(200, "OK");
Mockito.when(responseFactory.newHttpResponse(200, context)).thenReturn(response);
Mockito.when(connReuseStrategy.keepAlive(request, response, context)).thenReturn(Boolean.FALSE);
httpservice.handleRequest(conn, context);
Mockito.verify(responseFactory).newHttpResponse(200, context);
}
|
|
Like Feedback org.apache.hc.core5.http.impl.io.HttpService |
|
|
Sample 274. Code Sample / Example / Snippet of org.apache.hc.core5.http.impl.nio.UriHttpAsyncRequestHandlerMapper | |
|
public void testRegisterUnregister() throws Exception {
final HttpAsyncRequestHandler<?> h = Mockito.mock(HttpAsyncRequestHandler.class);
final UriPatternMatcher<HttpAsyncRequestHandler<?>> matcher = Mockito.spy(
new UriPatternMatcher<HttpAsyncRequestHandler<?>>());
final UriHttpAsyncRequestHandlerMapper registry = new UriHttpAsyncRequestHandlerMapper(matcher);
registry.register("/h1", h);
registry.unregister("/h1");
Mockito.verify(matcher).register("/h1", h);
Mockito.verify(matcher).unregister("/h1");
}
|
|
Like Feedback org.apache.hc.core5.http.impl.nio.UriHttpAsyncRequestHandlerMapper |
|
|
|
Sample 275. Code Sample / Example / Snippet of javax.net.ssl.TrustManager | |
|
public SSLContextBuilder loadTrustMaterial(
final KeyStore truststore,
final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(truststore);
final TrustManager[] tms = tmfactory.getTrustManagers();
if (tms != null) {
if (trustStrategy != null) {
for (int i = 0; i < tms.length; i++) {
final TrustManager tm = tms[i];
if (tm instanceof X509TrustManager) {
tms[i] = new TrustManagerDelegate(
(X509TrustManager) tm, trustStrategy);
}
}
}
for (final TrustManager tm : tms) {
this.trustmanagers.add(tm);
}
}
return this;
}
|
|
Like Feedback javax.net.ssl.TrustManager |
|
|
Sample 276. Code Sample / Example / Snippet of javax.net.ssl.KeyManagerFactory | |
|
public SSLContextBuilder loadKeyMaterial(
final KeyStore keystore,
final char[] keyPassword,
final PrivateKeyStrategy aliasStrategy)
throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, keyPassword);
final KeyManager[] kms = kmfactory.getKeyManagers();
if (kms != null) {
if (aliasStrategy != null) {
for (int i = 0; i < kms.length; i++) {
final KeyManager km = kms[i];
if (km instanceof X509ExtendedKeyManager) {
kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy);
}
}
}
for (final KeyManager km : kms) {
keymanagers.add(km);
}
}
return this;
}
|
|
Like Feedback javax.net.ssl.KeyManagerFactory |
|
|
Sample 277. Code Sample / Example / Snippet of javax.net.ssl.KeyManager | |
|
public SSLContextBuilder loadKeyMaterial(
final KeyStore keystore,
final char[] keyPassword,
final PrivateKeyStrategy aliasStrategy)
throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, keyPassword);
final KeyManager[] kms = kmfactory.getKeyManagers();
if (kms != null) {
if (aliasStrategy != null) {
for (int i = 0; i < kms.length; i++) {
final KeyManager km = kms[i];
if (km instanceof X509ExtendedKeyManager) {
kms[i] = new KeyManagerDelegate((X509ExtendedKeyManager) km, aliasStrategy);
}
}
}
for (final KeyManager km : kms) {
keymanagers.add(km);
}
}
return this;
}
|
|
Like Feedback javax.net.ssl.KeyManager |
|
|
Sample 278. Code Sample / Example / Snippet of javax.net.ssl.TrustManagerFactory | |
|
public SSLContextBuilder loadTrustMaterial(
final KeyStore truststore,
final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(truststore);
final TrustManager[] tms = tmfactory.getTrustManagers();
if (tms != null) {
if (trustStrategy != null) {
for (int i = 0; i < tms.length; i++) {
final TrustManager tm = tms[i];
if (tm instanceof X509TrustManager) {
tms[i] = new TrustManagerDelegate(
(X509TrustManager) tm, trustStrategy);
}
}
}
for (final TrustManager tm : tms) {
this.trustmanagers.add(tm);
}
}
return this;
}
|
|
Like Feedback javax.net.ssl.TrustManagerFactory |
|
|
Sample 279. Code Sample / Example / Snippet of org.apache.hc.core5.http.protocol.BasicHttpContext | |
|
public void run() {
try {
final BasicHttpContext localContext = new BasicHttpContext();
final HttpCoreContext context = HttpCoreContext.adapt(localContext);
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
localContext.clear();
}
this.conn.close();
} catch (final Exception ex) {
this.exceptionLogger.log(ex);
} finally {
try {
this.conn.shutdown();
} catch (final IOException ex) {
this.exceptionLogger.log(ex);
}
}
}
|
|
Like Feedback org.apache.hc.core5.http.protocol.BasicHttpContext |
|
|
|
Sample 280. Code Sample / Example / Snippet of org.apache.hc.core5.http.message.BufferedHeader | |
|
public void testBasicConstructor() throws Exception {
final CharArrayBuffer buf = new CharArrayBuffer(32);
buf.append("name: value");
final BufferedHeader header = new BufferedHeader(buf, false);
Assert.assertEquals("name", header.getName());
Assert.assertEquals("value", header.getValue());
Assert.assertSame(buf, header.getBuffer());
Assert.assertEquals(5, header.getValuePos());
}
|
|
Like Feedback org.apache.hc.core5.http.message.BufferedHeader |
|
|
Sample 281. Code Sample / Example / Snippet of org.apache.hc.core5.util.ByteArrayBuffer | |
|
public void testConstructor() throws Exception {
final ByteArrayBuffer buffer = new ByteArrayBuffer(16);
Assert.assertEquals(16, buffer.capacity());
Assert.assertEquals(0, buffer.length());
Assert.assertNotNull(buffer.buffer());
Assert.assertEquals(16, buffer.buffer().length);
try {
new ByteArrayBuffer(-1);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
}
}
|
|
Like Feedback org.apache.hc.core5.util.ByteArrayBuffer |
|
|
Sample 282. Code Sample / Example / Snippet of org.apache.hc.core5.http.message.ParserCursor | |
|
public void testParamByName() throws Exception {
final String s = "name = value; param1 = value1; param2 = value2";
final CharArrayBuffer buf = new CharArrayBuffer(64);
buf.append(s);
final ParserCursor cursor = new ParserCursor(0, buf.length());
final HeaderElement element = BasicHeaderValueParser.INSTANCE.parseHeaderElement(buf, cursor);
Assert.assertEquals("value1", element.getParameterByName("param1").getValue());
Assert.assertEquals("value2", element.getParameterByName("param2").getValue());
Assert.assertNull(element.getParameterByName("param3"));
try {
element.getParameterByName(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
}
}
|
|
Like Feedback org.apache.hc.core5.http.message.ParserCursor |
|
|
Sample 283. Code Sample / Example / Snippet of java.util.BitSet | |
|
public static BitSet INIT_BITSET(final int ... b) {
final BitSet bitset = new BitSet();
for (final int aB : b) {
bitset.set(aB);
}
return bitset;
}
|
|
Like Feedback java.util.BitSet |
|
|
Sample 284. Code Sample / Example / Snippet of org.apache.hc.core5.http.message.BasicStatusLine | |
|
public void testSerialization() throws Exception {
final BasicStatusLine orig = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream();
final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer);
outstream.writeObject(orig);
outstream.close();
final byte[] raw = outbuffer.toByteArray();
final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw);
final ObjectInputStream instream = new ObjectInputStream(inbuffer);
final BasicStatusLine clone = (BasicStatusLine) instream.readObject();
Assert.assertEquals(orig.getReasonPhrase(), clone.getReasonPhrase());
Assert.assertEquals(orig.getStatusCode(), clone.getStatusCode());
Assert.assertEquals(orig.getProtocolVersion(), clone.getProtocolVersion());
}
|
|
Like Feedback org.apache.hc.core5.http.message.BasicStatusLine |
|
|
|
Sample 285. Code Sample / Example / Snippet of java.net.SocketAddress | |
|
public String toString() {
final SocketAddress remoteAddress = this.session.getRemoteAddress();
final SocketAddress localAddress = this.session.getLocalAddress();
if (remoteAddress != null && localAddress != null) {
final StringBuilder buffer = new StringBuilder();
NetUtils.formatAddress(buffer, localAddress);
buffer.append("<->");
NetUtils.formatAddress(buffer, remoteAddress);
return buffer.toString();
}
return "[Not bound]";
}
|
|
Like Feedback java.net.SocketAddress |
|
|
Sample 286. Code Sample / Example / Snippet of org.apache.hc.core5.http.nio.HttpAsyncResponseProducer | |
|
public void outputReady(
final NHttpServerConnection conn,
final ContentEncoder encoder) throws HttpException, IOException {
final State state = getState(conn);
Asserts.notNull(state, "Connection state");
Asserts.check(state.getResponseState() == MessageState.BODY_STREAM,
"Unexpected response state %s", state.getResponseState());
final Outgoing outgoing = state.getOutgoing();
Asserts.notNull(outgoing, "Outgoing response");
final HttpAsyncResponseProducer responseProducer = outgoing.getProducer();
responseProducer.produceContent(encoder, conn);
if (encoder.isCompleted()) {
completeResponse(outgoing, conn, state);
}
}
|
|
Like Feedback org.apache.hc.core5.http.nio.HttpAsyncResponseProducer |
|
|
Sample 287. Code Sample / Example / Snippet of javax.servlet.ServletOutputStream | |
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
ServletOutputStream output = null;
try {
output = response.getOutputStream();
output.println(request.getQueryString());
}
catch (IOException e) {
} finally {
if (output != null) {
try {
output.close();
}
catch (IOException e) {
}
}
}
}
|
|
Like Feedback javax.servlet.ServletOutputStream |
|
|
Sample 288. Code Sample / Example / Snippet of org.osgi.service.useradmin.User | |
|
private boolean authenticate(HttpServletRequest request) {
if (m_useAuth) {
User user = m_authService.authenticate(request);
if (user == null) {
m_logger.log(LogService.LOG_INFO, "Authentication failure!");
}
return (user != null);
}
return true;
}
|
|
Like Feedback org.osgi.service.useradmin.User |
|
|
Sample 289. Code Sample / Example / Snippet of org.apache.felix.service.command.CommandSession | |
|
private void executeScript(Dictionary<String, String> scriptDefinition) throws Exception {
String script = scriptDefinition.get(SCRIPT_KEY);
if (script == null) {
throw new IllegalArgumentException("Script definition *must* define at least a 'script' property!");
}
CommandSession session = m_processor.createSession(System.in, System.out, System.err);
try {
Object scriptResult = session.execute(script);
m_logger.log(LogService.LOG_DEBUG, "Script output:
" + scriptResult);
}
finally {
session.close();
}
}
|
|
Like Feedback org.apache.felix.service.command.CommandSession |
|
|
|
Sample 290. Code Sample / Example / Snippet of com.google.gson.JsonArray | |
|
private void listRepositoryObjects(Workspace workspace, String entityType, HttpServletResponse resp) throws IOException {
List<RepositoryObject> objects = workspace.getRepositoryObjects(entityType);
JsonArray result = new JsonArray();
for (RepositoryObject ro : objects) {
String identity = ro.getDefinition();
if (identity != null) {
result.add(new JsonPrimitive(urlEncode(identity)));
}
}
resp.getWriter().println(m_gson.toJson(result));
}
|
|
Like Feedback com.google.gson.JsonArray |
|
|
Sample 291. Code Sample / Example / Snippet of java.util.List | |
|
private static List convertArrayToList(Object array)
{
int len = Array.getLength(array);
List list = new ArrayList(len);
for (int i = 0; i < len; i++)
{
list.add(Array.get(array, i));
}
return list;
}
|
|
Like Feedback java.util.List |
|
|
Sample 292. Code Sample / Example / Snippet of org.osgi.framework.wiring.BundleCapability | |
|
private static Set<BundleCapability> matchMandatory(
Set<BundleCapability> caps, SimpleFilter sf)
{
for (Iterator<BundleCapability> it = caps.iterator(); it.hasNext(); )
{
BundleCapability cap = it.next();
if (!matchMandatory(cap, sf))
{
it.remove();
}
}
return caps;
}
|
|
Like Feedback org.osgi.framework.wiring.BundleCapability |
|
|
Sample 293. Code Sample / Example / Snippet of org.osgi.service.http.HttpService | |
|
public synchronized void addServlet(ServiceReference<Servlet> ref) {
String endpoint = (String) ref.getProperty(HttpConstants.ENDPOINT);
m_servlets.put(ref, endpoint);
Servlet servlet = m_context.getService(ref);
Dictionary<String, Object> initParams = getInitParams(ref);
for (ServiceReference<HttpService> reference : m_httpServices) {
HttpService httpService = m_context.getService(reference);
try {
if ((httpService != null) && (endpoint != null) && (servlet != null)) {
httpService.registerServlet(endpoint, servlet, initParams, null);
}
else {
m_log.log(LogService.LOG_WARNING, "Unable to register servlet with endpoint '" + endpoint + "'");
}
}
catch (Exception e) {
m_log.log(LogService.LOG_WARNING, "Already registered under existing endpoint", e);
}
}
}
|
|
Like Feedback org.osgi.service.http.HttpService |
|
|
Sample 294. Code Sample / Example / Snippet of javax.servlet.Servlet | |
|
public synchronized void addServlet(ServiceReference<Servlet> ref) {
String endpoint = (String) ref.getProperty(HttpConstants.ENDPOINT);
m_servlets.put(ref, endpoint);
Servlet servlet = m_context.getService(ref);
Dictionary<String, Object> initParams = getInitParams(ref);
for (ServiceReference<HttpService> reference : m_httpServices) {
HttpService httpService = m_context.getService(reference);
try {
if ((httpService != null) && (endpoint != null) && (servlet != null)) {
httpService.registerServlet(endpoint, servlet, initParams, null);
}
else {
m_log.log(LogService.LOG_WARNING, "Unable to register servlet with endpoint '" + endpoint + "'");
}
}
catch (Exception e) {
m_log.log(LogService.LOG_WARNING, "Already registered under existing endpoint", e);
}
}
}
|
|
Like Feedback javax.servlet.Servlet |
|
|
|
Sample 295. Code Sample / Example / Snippet of com.vaadin.ui.TextField | |
|
private TextField makeTextField(final String colType) {
TextField t = new TextField(colType);
t.addListener(new TextChangeListener() {
SimpleStringFilter filter = null;
public void textChange(TextChangeEvent event) {
Filterable f = (Filterable) m_table.getContainerDataSource();
if (filter != null) {
f.removeContainerFilter(filter);
}
filter = new SimpleStringFilter(colType, event.getText(), true /* ignoreCase */, false /* onlyMatchPrefix */);
f.addContainerFilter(filter);
}
});
return t;
}
|
|
Like Feedback com.vaadin.ui.TextField |
|
|
Sample 296. Code Sample / Example / Snippet of javax.net.ssl.TrustManagerFactory | |
|
private TrustManager[] getTrustManagerFactory(String truststoreFile, String storePass) throws IOException, GeneralSecurityException {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
InputStream is = null;
try {
is = new FileInputStream(truststoreFile);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(is, storePass.toCharArray());
tmf.init(ks);
return tmf.getTrustManagers();
}
finally {
try {
if (is != null) {
is.close();
}
}
catch (IOException e) {
}
}
}
|
|
Like Feedback javax.net.ssl.TrustManagerFactory |
|
|
Sample 297. Code Sample / Example / Snippet of java.util.regex.Pattern | |
|
private long getStoreId(File storeFile) {
Pattern p = Pattern.compile(m_name + "-(\d+)");
Matcher m = p.matcher(storeFile.getName());
if (m.find()) {
return Long.parseLong(m.group(1));
}
throw new RuntimeException("Invalid store file name: " + storeFile.getName());
}
|
|
Like Feedback java.util.regex.Pattern |
|
|
Sample 298. Code Sample / Example / Snippet of javax.net.ssl.KeyManagerFactory | |
|
private KeyManager[] getKeyManagerFactory(String keystoreFile, String storePass) throws IOException, GeneralSecurityException {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
InputStream is = null;
try {
is = new FileInputStream(keystoreFile);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(is, storePass.toCharArray());
kmf.init(ks, storePass.toCharArray());
return kmf.getKeyManagers();
}
finally {
try {
if (is != null) {
is.close();
}
}
catch (IOException e) {
}
}
}
|
|
Like Feedback javax.net.ssl.KeyManagerFactory |
|
|
Sample 299. Code Sample / Example / Snippet of org.apache.ace.agent.EventsHandler | |
|
protected void onStop() throws Exception {
EventsHandler eventsHandler = getEventsHandler();
if (eventsHandler != null) {
eventsHandler.removeListener(this);
}
if (m_updateInstaller != null) {
m_updateInstaller.reset();
m_updateInstaller = null;
}
}
|
|
Like Feedback org.apache.ace.agent.EventsHandler |
|
|
|
Sample 300. Code Sample / Example / Snippet of java.util.concurrent.ScheduledExecutorService | |
|
public void postEvent(final String topic, Map<String, String> payload) {
final Map<String, String> eventPayload = new HashMap<>(payload);
for (final EventListener listener : m_listeners) {
ScheduledExecutorService executor = getExecutorService();
if (executor.isShutdown()) {
logWarning("Cannot post event, executor is shut down!");
return;
}
executor.submit(new Runnable() {
@Override
public void run() {
try {
listener.handle(topic, eventPayload);
}
catch (Exception e) {
logWarning("Exception while posting event", e);
}
}
});
}
}
|
|
Like Feedback java.util.concurrent.ScheduledExecutorService |
|
|
Sample 301. Code Sample / Example / Snippet of org.osgi.framework.FrameworkEvent | |
|
public void testWriteEvent() throws Exception {
FrameworkEvent event = new FrameworkEvent(32, new Object());
m_eventLogger.frameworkEvent(event);
FeedbackHandler feedbackHandler = m_agentContext.getHandler(FeedbackHandler.class);
TestFeedbackChannel channel = (TestFeedbackChannel) feedbackHandler.getChannel("auditlog");
assertEquals(channel.getLastTtype(), 1001);
}
|
|
Like Feedback org.osgi.framework.FrameworkEvent |
|
|
Sample 302. Code Sample / Example / Snippet of org.apache.ace.agent.DeploymentHandler | |
|
public void testAvailableVersions() throws Exception {
DeploymentHandler deploymentHandler = m_agentContext.getHandler(DeploymentHandler.class);
SortedSet<Version> expected = new TreeSet<>();
expected.add(m_version1);
expected.add(m_version2);
expected.add(m_version3);
SortedSet<Version> available = deploymentHandler.getAvailableVersions();
assertNotNull(available);
assertFalse(available.isEmpty());
assertEquals(available, expected);
}
|
|
Like Feedback org.apache.ace.agent.DeploymentHandler |
|
|
Sample 303. Code Sample / Example / Snippet of java.security.DigestOutputStream | |
|
public void setUpTestCase() throws Exception {
File file = File.createTempFile("test", ".bin", new File("generated"));
file.deleteOnExit();
DigestOutputStream dos = null;
try {
dos = new DigestOutputStream(new FileOutputStream(file), MessageDigest.getInstance("MD5"));
for (int i = 0; i < 10000; i++) {
dos.write(String.valueOf(System.currentTimeMillis()).getBytes());
dos.write(" Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum
".getBytes());
}
dos.flush();
}
finally {
if (dos != null) {
dos.close();
}
}
m_testContentURL = file.toURI().toURL();
m_contentLength = file.length();
m_digest = new String(dos.getMessageDigest().digest());
}
|
|
Like Feedback java.security.DigestOutputStream |
|
|
Sample 304. Code Sample / Example / Snippet of org.apache.ace.agent.DiscoveryHandler | |
|
public void testAvailableURL() throws Exception {
ConfigurationHandler configurationHandler = m_agentContext.getHandler(ConfigurationHandler.class);
configureAgent(configurationHandler,
AgentConstants.CONFIG_DISCOVERY_SERVERURLS, concat(m_availableURL1, m_availableURL2),
AgentConstants.CONFIG_DISCOVERY_CHECKING, "true");
DiscoveryHandler discoveryHandler = m_agentContext.getHandler(DiscoveryHandler.class);
assertEquals(discoveryHandler.getServerUrl(), m_availableURL1);
}
|
|
Like Feedback org.apache.ace.agent.DiscoveryHandler |
|
|
|
Sample 305. Code Sample / Example / Snippet of org.apache.ace.agent.ConnectionHandler | |
|
public void testDoubleClosedStreamOk() throws Exception {
ConnectionHandler handler = new TestConnectionHandler(new CompleteContentConnection(m_content, true));
ContentRangeInputStream is = new ContentRangeInputStream(handler, m_testURL);
is.close(); // simulate an early close...
is.close(); // not a problem...
}
|
|
Like Feedback org.apache.ace.agent.ConnectionHandler |
|
|
Sample 306. Code Sample / Example / Snippet of org.apache.ace.agent.DownloadHandle | |
|
public void testFailed404_noresume_result() throws Exception {
DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
DownloadHandle handle = downloadHandler.getHandle(m_404url);
Future<DownloadResult> future = handle.start(null);
assertIOException(future);
}
|
|
Like Feedback org.apache.ace.agent.DownloadHandle |
|
|
Sample 307. Code Sample / Example / Snippet of org.apache.ace.agent.ConfigurationHandler | |
|
public void testSingleFeedbackChannelConfig() throws Exception {
ConfigurationHandler configurationHandler = m_agentContextImpl.getHandler(ConfigurationHandler.class);
configureAgent(configurationHandler, CONFIG_FEEDBACK_CHANNELS, AUDITLOG);
FeedbackHandler feedbackHandler = m_agentContextImpl.getHandler(FeedbackHandler.class);
assertFeedbackChannelNames(feedbackHandler, AUDITLOG);
assertFeedbackChannelsPresent(feedbackHandler, AUDITLOG);
}
|
|
Like Feedback org.apache.ace.agent.ConfigurationHandler |
|
|
Sample 308. Code Sample / Example / Snippet of org.apache.ace.agent.DownloadHandler | |
|
public void testFailed404_noresume_result() throws Exception {
DownloadHandler downloadHandler = m_agentContext.getHandler(DownloadHandler.class);
DownloadHandle handle = downloadHandler.getHandle(m_404url);
Future<DownloadResult> future = handle.start(null);
assertIOException(future);
}
|
|
Like Feedback org.apache.ace.agent.DownloadHandler |
|
|
Sample 309. Code Sample / Example / Snippet of java.security.DigestInputStream | |
|
private String getDigest(InputStream is) throws Exception {
DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance("MD5"));
while (dis.read() != -1) {
}
dis.close();
return new String(dis.getMessageDigest().digest());
}
|
|
Like Feedback java.security.DigestInputStream |
|
|
|
Sample 310. Code Sample / Example / Snippet of org.apache.ace.agent.IdentificationHandler | |
|
public void testAvailableIdentification() throws Exception {
ConfigurationHandler configurationHandler = m_agentContext.getHandler(ConfigurationHandler.class);
reset(configurationHandler);
expect(configurationHandler.get(eq(AgentConstants.CONFIG_IDENTIFICATION_AGENTID), anyObject(String.class)))
.andReturn("qqq").once();
replay(configurationHandler);
IdentificationHandler identificationHandler = m_agentContext.getHandler(IdentificationHandler.class);
assertEquals(identificationHandler.getAgentId(), "qqq");
}
|
|
Like Feedback org.apache.ace.agent.IdentificationHandler |
|
|
Sample 311. Code Sample / Example / Snippet of org.eclipse.jetty.servlet.ServletHolder | |
|
public TestWebServer(int port, String contextPath, String basePath) throws Exception {
m_server = new Server(port);
m_contextHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);
m_contextHandler.setContextPath("/");
ServletHolder holder = new ServletHolder(new DefaultServlet());
holder.setInitParameter("resourceBase", basePath);
holder.setInitParameter("pathInfoOnly", "true");
holder.setInitParameter("acceptRanges", "true");
holder.setInitParameter("dirAllowed", "true");
m_contextHandler.addFilter(new FilterHolder(new HttpDumpFilter()), "/*", null);
m_contextHandler.addServlet(holder, contextPath.concat(contextPath.endsWith("/") ? "*" : "/*"));
m_server.setHandler(m_contextHandler);
}
|
|
Like Feedback org.eclipse.jetty.servlet.ServletHolder |
|
|
Sample 312. Code Sample / Example / Snippet of static org.easymock.EasyMock.expect | |
|
public void testAuthenticateKnownUserWithExpiredCertificateYieldsNull() {
X509Certificate[] certificateChain = createExpiredCertificateChain("bob");
PublicKey publickey = certificateChain[0].getPublicKey();
when(m_servletRequest.getAttribute(ATTRIBUTE_X509_CERTIFICATE)).thenReturn(certificateChain);
User user = mock(User.class);
when(user.getName()).thenReturn("bob");
when(user.hasCredential(eq("publickey"), eq(publickey.getEncoded()))).thenReturn(Boolean.TRUE);
when(m_userAdmin.getUser(eq("username"), eq("bob"))).thenReturn(user);
User result = createAuthorizationProcessor().authenticate(m_userAdmin, m_servletRequest);
assert result == null : "Did not expect a valid user to be returned!";
}
|
|
Like Feedback static org.easymock.EasyMock.expect |
|
|
Sample 313. Code Sample / Example / Snippet of org.apache.ace.agent.impl.AgentContextImpl | |
|
protected AgentContextImpl mockAgentContext(String subDir) throws Exception {
if (m_contextDir != null) {
cleanDir(m_contextDir);
m_contextDir.delete();
}
m_contextDir = new File(getWorkDir(), subDir);
m_contextDir.mkdirs();
cleanDir(m_contextDir);
AgentContextImpl context = new AgentContextImpl(m_contextDir);
for (Class<?> handlerClass : AgentContextImpl.KNOWN_HANDLERS) {
if (ScheduledExecutorService.class.equals(handlerClass)) {
context.setHandler(ScheduledExecutorService.class, new SynchronousExecutorService());
}
else {
setMockedHandler(context, handlerClass);
}
}
return context;
}
|
|
Like Feedback org.apache.ace.agent.impl.AgentContextImpl |
|
|
Sample 314. Code Sample / Example / Snippet of org.apache.ace.client.repository.helper.ArtifactHelper | |
|
public List<ArtifactObject> get() {
try {
return super.get(createFilter("(!(" + RepositoryUtil.escapeFilterValue(BundleHelper.KEY_RESOURCE_PROCESSOR_PID) + "=*))"));
}
catch (InvalidSyntaxException e) {
m_log.log(LogService.LOG_ERROR, "get's filter returned an InvalidSyntaxException.", e);
}
return new ArrayList<>();
}
@Override
ArtifactObjectImpl createNewInhabitant(Map<String, String> attributes, Map<String, String> tags) {
ArtifactHelper helper = getHelper(attributes.get(ArtifactObject.KEY_MIMETYPE));
ArtifactObjectImpl ao = new ArtifactObjectImpl(helper.checkAttributes(attributes), helper.getMandatoryAttributes(), tags, this, this);
return ao;
}
|
|
Like Feedback org.apache.ace.client.repository.helper.ArtifactHelper |
|
|
|
Sample 315. Code Sample / Example / Snippet of org.apache.ace.client.repository.helper.ArtifactPreprocessor | |
|
public String preprocessArtifact(ArtifactObject artifact, TargetObject target, String targetID, String version) throws IOException {
ArtifactPreprocessor preprocessor = getHelper(artifact.getMimetype()).getPreprocessor();
if (preprocessor == null) {
return artifact.getURL();
}
else {
return preprocessor.preprocess(artifact.getURL(), new TargetPropertyResolver(target), targetID, version, getObrBase());
}
}
|
|
Like Feedback org.apache.ace.client.repository.helper.ArtifactPreprocessor |
|
|
Sample 316. Code Sample / Example / Snippet of org.osgi.service.prefs.Preferences | |
|
private Preferences getRepositoryPrefs(Preferences userPrefs, URL location, String customer, String name) {
Preferences repoPref = userPrefs.node(location.getAuthority() + location.getPath());
Preferences customerPref = repoPref.node(customer);
return customerPref.node(name);
}
|
|
Like Feedback org.osgi.service.prefs.Preferences |
|
|
Sample 317. Code Sample / Example / Snippet of org.apache.ace.client.repository.RepositoryObject.WorkingState | |
|
public WorkingState getWorkingState(RepositoryObject object) {
WorkingState result = null;
synchronized(m_lock) {
for (RepositorySet set: m_repositorySets) {
result = set.getWorkingState(object);
if (result != null) {
break;
}
}
}
return (result == null) ? WorkingState.Unchanged : result;
}
|
|
Like Feedback org.apache.ace.client.repository.RepositoryObject.WorkingState synchronized |
|
|
Sample 318. Code Sample / Example / Snippet of static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_OBR_LOCATION | |
|
public interface RepositoryConstants {
String KEY_SHOW_UNREGISTERED_TARGETS = "showunregisteredtargets";
String KEY_DEPLOYMENT_VERSION_LIMITS = "deploymentversionlimit";
String KEY_OBR_LOCATION = "obrlocation";
}
|
|
Like Feedback static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_OBR_LOCATION |
|
|
Sample 319. Code Sample / Example / Snippet of static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_DEPLOYMENT_VERSION_LIMITS | |
|
public interface RepositoryConstants {
String KEY_SHOW_UNREGISTERED_TARGETS = "showunregisteredtargets";
String KEY_DEPLOYMENT_VERSION_LIMITS = "deploymentversionlimit";
String KEY_OBR_LOCATION = "obrlocation";
}
|
|
Like Feedback static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_DEPLOYMENT_VERSION_LIMITS |
|
|
|
Sample 320. Code Sample / Example / Snippet of java.util.concurrent.locks.Lock | |
|
public int getDeploymentVersionLimit() {
Lock lock = m_lock.readLock();
lock.lock();
try {
return m_deploymentVersionLimit;
}
finally {
lock.unlock();
}
}
|
|
Like Feedback java.util.concurrent.locks.Lock |
|
|
Sample 321. Code Sample / Example / Snippet of static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_SHOW_UNREGISTERED_TARGETS | |
|
public interface RepositoryConstants {
String KEY_SHOW_UNREGISTERED_TARGETS = "showunregisteredtargets";
String KEY_DEPLOYMENT_VERSION_LIMITS = "deploymentversionlimit";
String KEY_OBR_LOCATION = "obrlocation";
}
|
|
Like Feedback static org.apache.ace.client.repository.repository.RepositoryConstants.KEY_SHOW_UNREGISTERED_TARGETS |
|
|
Sample 322. Code Sample / Example / Snippet of org.apache.velocity.VelocityContext | |
|
private byte[] process(byte[] input, PropertyResolver props) throws IOException {
VelocityContext context = new VelocityContext();
context.put("context", props);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(baos);
Velocity.evaluate(context, writer, "", new InputStreamReader(new ByteArrayInputStream(input)));
writer.flush();
return baos.toByteArray();
}
catch (IOException ioe) {
throw new IOException("Error processing the artifact: " + ioe.getMessage());
}
}
|
|
Like Feedback org.apache.velocity.VelocityContext |
|
|
Sample 323. Code Sample / Example / Snippet of org.xml.sax.Attributes | |
|
public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {
List<ArtifactData> data = m_provider.getBundleData(id, version);
Manifest manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("DeploymentPackage-SymbolicName", id);
main.putValue("DeploymentPackage-Version", version);
for (ArtifactData bd : data) {
manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));
}
return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);
}
|
|
Like Feedback org.xml.sax.Attributes |
|
|
Sample 324. Code Sample / Example / Snippet of org.apache.ace.client.repository.helper.base.VelocityArtifactPreprocessor | |
|
public void testNeedsNewVersionChangedTemplateOk() throws Exception {
final VelocityArtifactPreprocessor vap = createProcessor();
String url = createArtifact("Message: [$context.msg]");
vap.preprocess(url, m_resolver, TARGET, VERSION1, m_obrUrl);
boolean result = vap.needsNewVersion(url, m_resolver, TARGET, VERSION1);
assertFalse(result); // no new version is needed...
updateArtifact(url, "Another message: [$context.msg2]");
result = vap.needsNewVersion(url, m_resolver, TARGET, VERSION1);
assertFalse(result); // no new version is needed; original artifact is cached indefinitely...
}
|
|
Like Feedback org.apache.ace.client.repository.helper.base.VelocityArtifactPreprocessor |
|
|
|
Sample 325. Code Sample / Example / Snippet of org.apache.ace.repository.ext.BackupRepository | |
|
public void testInitialCheckout() throws IllegalArgumentException, IOException {
Repository m_repository = new MockRepository();
byte[] testContent = new byte[] {'i', 'n', 'i', 't', 'i', 'a', 'l'};
m_repository.commit(new ByteArrayInputStream(testContent), 0);
BackupRepository m_backupRepository = new MockBackupRepository();
CachedRepository m_cachedRepository = new CachedRepositoryImpl(m_repository, m_backupRepository, 0);
InputStream input = m_cachedRepository.checkout(1);
byte[] inputBytes = AdminTestUtil.copy(input);
assert AdminTestUtil.byteArraysEqual(inputBytes, testContent) : "We got something different than 'initial' from checkout: " + new String(inputBytes);
input = m_cachedRepository.getLocal(false);
inputBytes = AdminTestUtil.copy(input);
assert AdminTestUtil.byteArraysEqual(inputBytes, testContent) : "We got something different than 'initial' from getLocal: " + new String(inputBytes);
input = m_backupRepository.read();
inputBytes = AdminTestUtil.copy(input);
assert AdminTestUtil.byteArraysEqual(inputBytes, testContent) : "We got something different than 'initial' from the backup repository: " + new String(inputBytes);
}
|
|
Like Feedback org.apache.ace.repository.ext.BackupRepository |
|
|
Sample 326. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.TargetObject | |
|
public void testDistribution2TargetAssociations() {
initializeRepositoryAdmin();
DistributionObject d1 = createBasicDistributionObject("distribution1");
TargetObject t1 = createBasicTargetObject("target1");
m_distribution2TargetRepository.create(d1, t1);
assert d1.getFeatures().size() == 0 : "Distribution 1 should not be associated with any features; it is associated with " + d1.getFeatures().size() + ".";
assert d1.getTargets().size() == 1 : "Distribution 1 should be associated with exactly one target; it is associated with " + d1.getTargets().size() + ".";
assert t1.getDistributions().size() == 1 : "Target 1 should be associated with exactly one distribution; it is associated with " + t1.getDistributions().size() + ".";
}
|
|
Like Feedback org.apache.ace.client.repository.object.TargetObject |
|
|
Sample 327. Code Sample / Example / Snippet of org.osgi.framework.BundleContext | |
|
public void init() {
BundleContext bc = TestUtils.createMockObjectAdapter(BundleContext.class, new Object() {
@SuppressWarnings("unused")
public Filter createFilter(String filter) throws InvalidSyntaxException {
return FrameworkUtil.createFilter(filter);
}
});
m_artifactRepository = new ArtifactRepositoryImpl(TestUtils.createNullObject(ChangeNotifier.class), new RepositoryConfigurationImpl());
TestUtils.configureObject(m_artifactRepository, LogService.class);
TestUtils.configureObject(m_artifactRepository, BundleContext.class, bc);
}
|
|
Like Feedback org.osgi.framework.BundleContext |
|
|
Sample 328. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.Feature2DistributionAssociation | |
|
public void TestFeature2DistributionAssociations() {
initializeRepositoryAdmin();
FeatureObject f1 = createBasicFeatureObject("feature1");
DistributionObject d1 = createBasicDistributionObject("distribution1");
Feature2DistributionAssociation f2d1 = m_feature2DistributionRepository.create(f1, d1);
assert (f2d1.getLeft().size() == 1) && f2d1.getLeft().contains(f1) : "Left side of the association should be our feature.";
assert (f2d1.getRight().size() == 1) && f2d1.getRight().contains(d1) : "Right side of the association should be our distribution.";
assert f1.getArtifacts().size() == 0 : "Feature 1 should not be associated with any artifacts; it is associated with " + f1.getArtifacts().size() + ".";
assert f1.getDistributions().size() == 1 : "Feature 1 should be associated with exactly one distribution; it is associated with " + f1.getDistributions().size() + ".";
assert d1.getFeatures().size() == 1 : "Distribution 1 should be associated with exactly one feature; it is associated with " + d1.getFeatures().size() + ".";
assert d1.getTargets().size() == 0 : "Distribution 1 should not be associated with any targets; it is associated with " + d1.getTargets().size() + ".";
}
|
|
Like Feedback org.apache.ace.client.repository.object.Feature2DistributionAssociation |
|
|
Sample 329. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.DeploymentVersionObject | |
|
public void testDeploymentRepository() {
DeploymentVersionObject version11 = createBasicDeploymentVersionObject("target1", "1", new String[] { "artifact1", "artifact2" });
DeploymentVersionObject version12 = createBasicDeploymentVersionObject("target1", "2", new String[] { "artifact3", "artifact4" });
DeploymentVersionObject version22 = createBasicDeploymentVersionObject("target2", "2", new String[] { "artifactC", "artifactD" });
DeploymentVersionObject version21 = createBasicDeploymentVersionObject("target2", "1", new String[] { "artifactA", "artifactB" });
assert m_deploymentVersionRepository.getDeploymentVersions("NotMyTarget").size() == 0 : "The deployment repository should not return" +
"any versions when we ask for a target that does not exist, but it returns " + m_deploymentVersionRepository.getDeploymentVersions("NotMyTarget").size();
List<DeploymentVersionObject> for1 = m_deploymentVersionRepository.getDeploymentVersions("target1");
assert for1.size() == 2 : "We expect two versions for target1, but we find " + for1.size();
assert for1.get(0) == version11 : "The first version for target1 should be version11";
assert for1.get(1) == version12 : "The second version for target1 should be version12";
List<DeploymentVersionObject> for2 = m_deploymentVersionRepository.getDeploymentVersions("target2");
assert for2.size() == 2 : "We expect two versions for target2, but we find " + for2.size();
assert for2.get(0) == version21 : "The first version for target2 should be version21";
assert for2.get(1) == version22 : "The second version for target2 should be version22";
assert m_deploymentVersionRepository.getMostRecentDeploymentVersion("NotMyTarget") == null : "The most recent version for a non-existent target should not exist.";
assert m_deploymentVersionRepository.getMostRecentDeploymentVersion("target1") == version12 : "The most recent version for target1 should be version12";
assert m_deploymentVersionRepository.getMostRecentDeploymentVersion("target2") == version22 : "The most recent version for target2 should be version22";
}
|
|
Like Feedback org.apache.ace.client.repository.object.DeploymentVersionObject |
|
|
|
Sample 330. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.Artifact2FeatureAssociation | |
|
public void testGetAssociationsWith() {
initializeRepositoryAdmin();
ArtifactObject a1 = createBasicArtifactObject("artifact1");
FeatureObject f1 = createBasicFeatureObject("feature1");
Artifact2FeatureAssociation a2f1 = m_artifact2FeatureRepository.create(a1, f1);
List<Artifact2FeatureAssociation> b1Associations = a1.getAssociationsWith(f1);
List<Artifact2FeatureAssociation> g1Associations = f1.getAssociationsWith(a1);
assert b1Associations.size() == 1 : "The artifact has exactly one association to the feature, but it shows " + b1Associations.size() + ".";
assert b1Associations.get(0) == a2f1 : "The artifact's association should be the one we created.";
assert g1Associations.size() == 1 : "The feature has exactly one association to the artifact.";
assert g1Associations.get(0) == a2f1 : "The feature's association should be the one we created.";
}
|
|
Like Feedback org.apache.ace.client.repository.object.Artifact2FeatureAssociation |
|
|
Sample 331. Code Sample / Example / Snippet of java.io.FileWriter | |
|
private String createArtifact(String string) throws IOException {
File tmpFile = File.createTempFile("vap", "vm");
tmpFile.delete();
tmpFile.deleteOnExit();
FileWriter writer = new FileWriter(tmpFile);
writer.write(string);
writer.flush();
writer.close();
return tmpFile.toURI().toURL().toExternalForm();
}
|
|
Like Feedback java.io.FileWriter |
|
|
Sample 332. Code Sample / Example / Snippet of java.util.Iterator | |
|
public void validateRangeIterators() {
SortedRangeSet srs1 = new SortedRangeSet("1-10");
Iterator i1 = srs1.rangeIterator();
assert i1.hasNext() : "We should have one Range instance in our iterator.";
assert ((Range) i1.next()).toRepresentation().equals("1-10");
assert !i1.hasNext() : "There should be only one instance in our iterator.";
SortedRangeSet srs2 = new SortedRangeSet("1-5,8,10-15");
Iterator i2 = srs2.rangeIterator();
assert i2.hasNext() && i2.next() instanceof Range
&& i2.hasNext() && i2.next() instanceof Range
&& i2.hasNext() && i2.next() instanceof Range
&& !i2.hasNext() : "There should be exactly three Range instances in our iterator.";
SortedRangeSet srs3 = new SortedRangeSet("");
assert !srs3.iterator().hasNext() : "Iterator should be empty.";
}
|
|
Like Feedback java.util.Iterator |
|
|
Sample 333. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream | |
|
public int compare(ResourceImpl r1, ResourceImpl r2) {
String s1 = getName(r1);
String s2 = getName(r2);
return s1.compareTo(s2);
}
});
Tag tag = doIndex(sorted);
if (repositoryFileName != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
|
Like Feedback java.io.ByteArrayOutputStream |
|
|
Sample 334. Code Sample / Example / Snippet of java.util.Set | |
|
public Set getExtendList() {
Set set = new HashSet();
for (Iterator i = requirements.iterator(); i.hasNext();) {
RequirementImpl impl = (RequirementImpl) i.next();
if (impl.isExtend())
set.add(impl);
}
return set;
}
|
|
Like Feedback java.util.Set |
|
|
|
Sample 335. Code Sample / Example / Snippet of org.osgi.impl.bundle.obr.resource.ResourceImpl | |
|
public boolean equals(Object o) {
try {
ResourceImpl other = (ResourceImpl) o;
return symbolicName.equals(other.symbolicName)
&& version.equals(other.version);
}
catch (ClassCastException e) {
return false;
}
}
|
|
Like Feedback org.osgi.impl.bundle.obr.resource.ResourceImpl |
|
|
Sample 336. Code Sample / Example / Snippet of org.osgi.impl.bundle.obr.resource.RepositoryImpl | |
|
public void testCheckoutAndCommitWithChangeDoesChangeVersion() throws Exception {
SortedRangeSet range;
RepositoryImpl repo = new RepositoryImpl(new File(m_baseDir, "data"), new File(m_baseDir, "tmp"), true);
InputStream data = new ByteArrayInputStream("abc".getBytes());
assertTrue(repo.put(data, 1), "Put should have succeeded");
range = repo.getRange();
assertEquals(1, range.getHigh(), "Version 1 should be the most recent one");
InputStream is = repo.checkout(1);
assertNotNull(is, "Nothing checked out?!");
data = new ByteArrayInputStream("def".getBytes());
assertTrue(repo.commit(data, 1), "Commit should NOT be ignored");
range = repo.getRange();
assertEquals(2, range.getHigh());
}
|
|
Like Feedback org.osgi.impl.bundle.obr.resource.RepositoryImpl |
|
|
Sample 337. Code Sample / Example / Snippet of org.apache.ace.obr.metadata.MetadataGenerator | |
|
public void generateMetaData() throws Exception {
File dir = File.createTempFile("meta", "");
dir.delete();
dir.mkdir();
generateBundle(File.createTempFile("bundle", ".jar", dir), "bundle.symbolicname.1", "1.0.0");
generateBundle(File.createTempFile("bundle", ".jar", dir), "bundle.symbolicname.2", "1.0.0");
generateBundle(File.createTempFile("bundle", ".jar", dir), "bundle.symbolicname.3", "1.0.0");
MetadataGenerator meta = new BIndexMetadataGenerator();
meta.generateMetadata(dir);
File index = new File(dir, "repository.xml");
assert index.exists() : "No repository index was generated";
assert index.length() > 0 : "Repository index can not be size 0";
int count = 0;
String line;
BufferedReader in = new BufferedReader(new FileReader(index));
while ((line = in.readLine()) != null) {
if (line.contains("<resource")) {
count++;
}
}
in.close();
assert count == 3 : "Expected 3 resources in the repository index, found " + count + ".";
}
|
|
Like Feedback org.apache.ace.obr.metadata.MetadataGenerator |
|
|
Sample 338. Code Sample / Example / Snippet of java.util.Random | |
|
private File createRandomFileWithContent() throws IOException {
OutputStream fileOut = null;
File file = null;
try {
file = FileUtils.createTempFile(null);
fileOut = new FileOutputStream(file);
byte[] byteArray = new byte[12345];
Random randomContentCreator = new Random();
randomContentCreator.nextBytes(byteArray);
fileOut.write(byteArray);
return file;
}
finally {
try {
if (fileOut != null) {
fileOut.close();
}
}
catch (IOException e) {
throw e;
}
}
}
|
|
Like Feedback java.util.Random |
|
|
Sample 339. Code Sample / Example / Snippet of java.util.StringTokenizer | |
|
public LowestID(String representation) {
try {
StringTokenizer st = new StringTokenizer(representation, ",");
m_targetID = Codec.decode(st.nextToken());
m_storeID = Long.parseLong(st.nextToken());
m_lowestID = Long.parseLong(st.nextToken());
}
catch (NoSuchElementException e) {
throw new IllegalArgumentException("Could not create lowest ID object from: " + representation);
}
}
|
|
Like Feedback java.util.StringTokenizer |
|
|
|
Sample 340. Code Sample / Example / Snippet of org.apache.ace.feedback.Descriptor | |
|
public synchronized void getRange() throws Exception {
final Descriptor range = new Descriptor(TARGET_ID, 1, new SortedRangeSet("1-10"));
m_task.getDescriptor(new InputStream() {
int m_count = 0;
byte[] m_bytes = (range.toRepresentation() + "
").getBytes();
@Override
public int read() throws IOException {
if (m_count < m_bytes.length) {
byte b = m_bytes[m_count];
m_count++;
return b;
} else {
return -1;
}
}
});
}
|
|
Like Feedback org.apache.ace.feedback.Descriptor |
|
|
Sample 341. Code Sample / Example / Snippet of org.apache.ace.log.target.store.impl.LogStoreImpl | |
|
public void testTimedWrite() throws Exception {
File storeFile = File.createTempFile("feedback", ".store");
storeFile.deleteOnExit();
final int recordCount = 10000;
final LogStoreImpl store = createLogStore();
long start = System.nanoTime();
for (int i = 0; i < recordCount; i++) {
store.put(Arrays.asList(new Event("1,2,3,4,5")));
}
long end = System.nanoTime();
System.out.printf("Writing %d records took %.3f ms.%n", recordCount, (end - start) / 1.0e6);
}
|
|
Like Feedback org.apache.ace.log.target.store.impl.LogStoreImpl |
|
|
Sample 342. Code Sample / Example / Snippet of org.apache.ace.range.SortedRangeSet | |
|
private void verifyStoreContents(final LogStoreImpl store, final int count, Writer... writers) throws IOException {
List<Descriptor> descriptors = store.getDescriptors();
long expectedID = 0;
for (Descriptor desc : descriptors) {
SortedRangeSet rangeSet = desc.getRangeSet();
RangeIterator rangeIter = rangeSet.iterator();
while (rangeIter.hasNext()) {
long id = rangeIter.next();
Event expectedEntry = null;
for (int i = 0; (expectedEntry == null) && i < writers.length; i++) {
expectedEntry = writers[i].m_written.remove(id);
}
assertNotNull(expectedEntry, "Event ID #" + id + " never written?!");
assertEquals(expectedEntry.getID(), expectedID++, "Entry ID mismatch?!");
}
}
}
|
|
Like Feedback org.apache.ace.range.SortedRangeSet |
|
|
Sample 343. Code Sample / Example / Snippet of static org.apache.ace.test.utils.TestUtils.UNIT | |
|
public class WorkspaceManagerImplTest {
@SuppressWarnings("serial")
@Test(groups = { UNIT })
public void testPropertyGetter() {
WorkspaceManagerImpl s = new WorkspaceManagerImpl();
Assert.assertEquals(s.getProperty(new Properties() {{ put("key", "value"); }}, "key", "notused"), "value");
Assert.assertEquals(s.getProperty(new Properties() {{ put("unusedkey", "value"); }}, "key", "default"), "default");
Assert.assertEquals(s.getProperty(null, "key", "default"), "default");
}
}
|
|
Like Feedback static org.apache.ace.test.utils.TestUtils.UNIT |
|
|
Sample 344. Code Sample / Example / Snippet of org.apache.ace.range.RangeIterator | |
|
private void verifyStoreContents(final LogStoreImpl store, final int count, Writer... writers) throws IOException {
List<Descriptor> descriptors = store.getDescriptors();
long expectedID = 0;
for (Descriptor desc : descriptors) {
SortedRangeSet rangeSet = desc.getRangeSet();
RangeIterator rangeIter = rangeSet.iterator();
while (rangeIter.hasNext()) {
long id = rangeIter.next();
Event expectedEntry = null;
for (int i = 0; (expectedEntry == null) && i < writers.length; i++) {
expectedEntry = writers[i].m_written.remove(id);
}
assertNotNull(expectedEntry, "Event ID #" + id + " never written?!");
assertEquals(expectedEntry.getID(), expectedID++, "Entry ID mismatch?!");
}
}
}
|
|
Like Feedback org.apache.ace.range.RangeIterator |
|
|
|
Sample 345. Code Sample / Example / Snippet of org.osgi.service.useradmin.UserAdmin | |
|
protected final User createUser(String name) {
UserAdmin useradmin = getService(UserAdmin.class);
User user = (User) useradmin.createRole(name, Role.USER);
if (user == null) {
user = useradmin.getUser("username", name);
}
else {
user.getProperties().put("username", name);
}
return user;
}
|
|
Like Feedback org.osgi.service.useradmin.UserAdmin |
|
|
Sample 346. Code Sample / Example / Snippet of java.io.ByteArrayInputStream | |
|
protected final void importSingleUser(Repository userRepository, String userName, String password) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream((
"<roles>" +
"<user name="" + userName + "">" +
"<properties><username>" + userName + "</username></properties>" +
"<credentials><password type="String">" + password + "</password></credentials>" +
"</user>" +
"</roles>").getBytes());
Assert.assertTrue("Committing test user data failed!", userRepository.commit(bis, userRepository.getRange().getHigh()));
}
|
|
Like Feedback java.io.ByteArrayInputStream |
|
|
Sample 347. Code Sample / Example / Snippet of java.io.Writer | |
|
private File createFileWithContents(String name, String extension, String contents) throws IOException {
File file = File.createTempFile(name, extension);
file.deleteOnExit();
Writer w = new OutputStreamWriter(new FileOutputStream(file));
w.write(contents);
w.close();
return file;
}
|
|
Like Feedback java.io.Writer |
|
|
Sample 348. Code Sample / Example / Snippet of org.apache.ace.feedback.Event | |
|
private Event createEvent(String version, URL dataURL) {
Dictionary<String, Object> properties = new Hashtable<>();
properties.put("deploymentpackage.url", dataURL.toString());
properties.put("deploymentpackage.version", version);
Event event = new Event(TOPIC_DEPLOYMENTPACKAGE_INSTALL, properties);
return event;
}
|
|
Like Feedback org.apache.ace.feedback.Event |
|
|
Sample 349. Code Sample / Example / Snippet of java.util.concurrent.CountDownLatch | |
|
public void testTooLongTask() throws Exception {
final CountDownLatch latch = new CountDownLatch(5);
Executer executer = new Executer(new Runnable() {
public void run() {
try {
Thread.sleep(20);
latch.countDown();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
executer.start(10);
assert latch.await(1, TimeUnit.SECONDS);
}
|
|
Like Feedback java.util.concurrent.CountDownLatch |
|
|
|
Sample 350. Code Sample / Example / Snippet of org.osgi.service.useradmin.Authorization | |
|
public Group getGroup(User user) {
Authorization auth = m_useradmin.getAuthorization(user);
String[] roles = auth.getRoles();
if (roles != null) {
for (String role : roles) {
Role result = m_useradmin.getRole(role);
if (result.getType() == Role.GROUP) {
Group group = (Group) result;
Role[] members = group.getMembers();
if (members != null) {
for (Role r : members) {
if (r.getType() == Role.USER && r.getName().equals(user.getName())) {
return group;
}
}
}
}
}
}
return null;
}
|
|
Like Feedback org.osgi.service.useradmin.Authorization |
|
|
Sample 351. Code Sample / Example / Snippet of javax.naming.ldap.LdapName | |
|
private String getName(X509Certificate certificate) {
try {
String dn = certificate.getSubjectX500Principal().getName();
if ("dn".equalsIgnoreCase(m_nameMatchPolicy)) {
return dn;
}
LdapName ldapDN = new LdapName(dn);
for (Rdn rdn : ldapDN.getRdns()) {
if (m_nameMatchPolicy.equalsIgnoreCase(rdn.getType())) {
return (String) rdn.getValue();
}
}
}
catch (InvalidNameException e) {
}
return null;
}
|
|
Like Feedback javax.naming.ldap.LdapName |
|
|
Sample 352. Code Sample / Example / Snippet of java.math.BigInteger | |
|
private X509Certificate generateRootCertificate(String commonName, Date notBefore, Date notAfter) throws Exception {
X500Name issuer = new X500Name(commonName);
BigInteger serial = BigInteger.probablePrime(16, new Random());
SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(m_caKey.getPublic());
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, pubKeyInfo);
builder.addExtension(new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(true))));
X509CertificateHolder certHolder = builder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(m_caKey.getPrivate()));
return new JcaX509CertificateConverter().getCertificate(certHolder);
}
|
|
Like Feedback java.math.BigInteger |
|
|
Sample 353. Code Sample / Example / Snippet of org.bouncycastle.cert.X509v3CertificateBuilder | |
|
public X509Certificate createCertificate(X500Principal issuerDN, PrivateKey issuerKey, String name, Date notBefore, Date notAfter, PublicKey key) throws IllegalArgumentException {
try {
X500Name issuer = new X500Name(issuerDN.getName());
X500Name commonName = new X500Name(name);
BigInteger serial = BigInteger.valueOf(++m_serial);
SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(key);
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, commonName, pubKeyInfo);
X509CertificateHolder certHolder = builder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(issuerKey));
return new JcaX509CertificateConverter().getCertificate(certHolder);
}
catch (IllegalArgumentException e) {
throw e;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
|
|
Like Feedback org.bouncycastle.cert.X509v3CertificateBuilder |
|
|
Sample 354. Code Sample / Example / Snippet of org.bouncycastle.cert.X509CertificateHolder | |
|
private X509Certificate generateRootCertificate(String commonName, Date notBefore, Date notAfter) throws Exception {
X500Name issuer = new X500Name(commonName);
BigInteger serial = BigInteger.probablePrime(16, new Random());
SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(m_caKey.getPublic());
X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, pubKeyInfo);
builder.addExtension(new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(true))));
X509CertificateHolder certHolder = builder.build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(m_caKey.getPrivate()));
return new JcaX509CertificateConverter().getCertificate(certHolder);
}
|
|
Like Feedback org.bouncycastle.cert.X509CertificateHolder |
|
|
|
Sample 355. Code Sample / Example / Snippet of java.util.Calendar | |
|
private static Calendar getToday() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
|
|
Like Feedback java.util.Calendar |
|
|
Sample 356. Code Sample / Example / Snippet of javax.security.auth.x500.X500Principal | |
|
private X509Certificate[] createValidCertificateChainWithDN(String... dns) {
X509Certificate[] result = new X509Certificate[dns.length];
X500Principal signerDN = m_keystore.getCA_DN();
KeyPair signerKeyPair = m_keystore.getCA_KeyPair();
for (int i = 0; i < result.length; i++) {
KeyPair certKeyPair = m_keystore.generateKeyPair();
String dn = dns[i];
int idx = result.length - i - 1;
result[idx] = m_keystore.createCertificate(signerDN, signerKeyPair.getPrivate(), dn, yesterday(), tomorrow(), certKeyPair.getPublic());
signerDN = result[idx].getSubjectX500Principal();
signerKeyPair = certKeyPair;
}
return result;
}
|
|
Like Feedback javax.security.auth.x500.X500Principal |
|
|
Sample 357. Code Sample / Example / Snippet of java.security.KeyPair | |
|
private X509Certificate[] createValidCertificateChainWithDN(String... dns) {
X509Certificate[] result = new X509Certificate[dns.length];
X500Principal signerDN = m_keystore.getCA_DN();
KeyPair signerKeyPair = m_keystore.getCA_KeyPair();
for (int i = 0; i < result.length; i++) {
KeyPair certKeyPair = m_keystore.generateKeyPair();
String dn = dns[i];
int idx = result.length - i - 1;
result[idx] = m_keystore.createCertificate(signerDN, signerKeyPair.getPrivate(), dn, yesterday(), tomorrow(), certKeyPair.getPublic());
signerDN = result[idx].getSubjectX500Principal();
signerKeyPair = certKeyPair;
}
return result;
}
|
|
Like Feedback java.security.KeyPair |
|
|
Sample 358. Code Sample / Example / Snippet of static org.mockito.Mockito.mock | |
|
public void setUp() throws Exception {
String range = "1-100000";
Repository mock = new MockDeploymentRepository(range, generateHugeTestXml(), null);
m_backend = new RepositoryBasedProvider();
TestUtils.configureObject(m_backend, Repository.class, mock);
TestUtils.configureObject(m_backend, LogService.class);
}
|
|
Like Feedback static org.mockito.Mockito.mock |
|
|
Sample 359. Code Sample / Example / Snippet of org.osgi.service.cm.Configuration | |
|
protected void deleteConfig(String pid, String factoryPid) {
try {
Configuration config = getConfiguration(pid, factoryPid);
config.delete();
m_log.log(LogService.LOG_DEBUG, "Removed configuration for pid '" + pid + "'");
}
catch (Exception e) {
m_log.log(LogService.LOG_ERROR, "Unable to remove configuration for pid '" + pid + "'", e);
}
}
|
|
Like Feedback org.osgi.service.cm.Configuration |
|
|
|
Sample 360. Code Sample / Example / Snippet of org.apache.felix.dm.DependencyManager | |
|
protected synchronized void enableEventLogging() {
DependencyManager dm = m_dependencyManager;
m_eventLoggingComponent = dm.createComponent()
.setInterface(EventHandler.class.getName(), new Properties() {
{
put(EventConstants.EVENT_TOPIC, "*");
}
})
.setImplementation(new EventHandler() {
@Override
public void handleEvent(Event event) {
System.out.print("[EVENT] " + event.getTopic());
for (String key : event.getPropertyNames()) {
System.out.print(" " + key + "=" + event.getProperty(key));
}
System.out.println();
}
});
dm.add(m_eventLoggingComponent);
}
|
|
Like Feedback org.apache.felix.dm.DependencyManager |
|
|
Sample 361. Code Sample / Example / Snippet of static org.apache.ace.test.utils.Util.dictionary | |
|
protected void configureProvisionedServices() throws Exception {
m_echoServlet = new EchoServlet();
Dictionary<String, String> dictionary = new Hashtable<>();
dictionary.put(HttpConstants.ENDPOINT, "/echoServlet");
m_echoServletService = m_dependencyManager.createComponent()
.setImplementation(m_echoServlet)
.setInterface(Servlet.class.getName(), dictionary);
m_mockHttp = new MockHttpService();
m_mockHttpService = m_dependencyManager.createComponent()
.setImplementation(m_mockHttp)
.setInterface(HttpService.class.getName(), null);
}
|
|
Like Feedback static org.apache.ace.test.utils.Util.dictionary |
|
|
Sample 362. Code Sample / Example / Snippet of java.nio.channels.FileChannel | |
|
public static void copy(File input, File output) throws IOException {
FileInputStream fis = new FileInputStream(input);
FileOutputStream fos = new FileOutputStream(output);
try {
FileChannel ic = fis.getChannel();
FileChannel oc = fos.getChannel();
try {
oc.transferFrom(ic, 0, ic.size());
}
finally {
oc.close();
ic.close();
}
}
finally {
fis.close();
fos.close();
}
}
|
|
Like Feedback java.nio.channels.FileChannel |
|
|
Sample 363. Code Sample / Example / Snippet of java.io.FileInputStream | |
|
public static void copy(File input, File output) throws IOException {
FileInputStream fis = new FileInputStream(input);
FileOutputStream fos = new FileOutputStream(output);
try {
FileChannel ic = fis.getChannel();
FileChannel oc = fos.getChannel();
try {
oc.transferFrom(ic, 0, ic.size());
}
finally {
oc.close();
ic.close();
}
}
finally {
fis.close();
fos.close();
}
}
|
|
Like Feedback java.io.FileInputStream |
|
|
Sample 364. Code Sample / Example / Snippet of java.lang.reflect.Method | |
|
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Method bridge = handler.getClass().getMethod(method.getName(), method.getParameterTypes());
bridge.setAccessible(true);
return bridge.invoke(handler, args);
}
catch (NoSuchMethodException ex) {
return super.invoke(proxy, method, args);
}
catch (InvocationTargetException ex) {
throw ex.getCause();
}
}
|
|
Like Feedback java.lang.reflect.Method |
|
|
|
Sample 365. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_TARGETID | |
|
public interface Constants {
String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"
+ "<user name="d"><properties><username>d</username></properties><credentials>"
+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";
String TEST_CUSTOMER = "apache";
int TEST_HTTP_PORT = TestConstants.PORT;
String TEST_TARGETID = "test-target";
}
|
|
Like Feedback static org.apache.ace.it.deployment.Constants.TEST_TARGETID |
|
|
Sample 366. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_CUSTOMER | |
|
public interface Constants {
String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"
+ "<user name="d"><properties><username>d</username></properties><credentials>"
+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";
String TEST_CUSTOMER = "apache";
int TEST_HTTP_PORT = TestConstants.PORT;
String TEST_TARGETID = "test-target";
}
|
|
Like Feedback static org.apache.ace.it.deployment.Constants.TEST_CUSTOMER |
|
|
Sample 367. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_HTTP_PORT | |
|
public interface Constants {
String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"
+ "<user name="d"><properties><username>d</username></properties><credentials>"
+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";
String TEST_CUSTOMER = "apache";
int TEST_HTTP_PORT = TestConstants.PORT;
String TEST_TARGETID = "test-target";
}
|
|
Like Feedback static org.apache.ace.it.deployment.Constants.TEST_HTTP_PORT |
|
|
Sample 368. Code Sample / Example / Snippet of static org.apache.ace.it.deployment.Constants.TEST_AUTH_SCHEME | |
|
public interface Constants {
String TEST_AUTH_SCHEME = "<roles><group name="TestGroup"><properties><type>userGroup</type></properties></group>"
+ "<user name="d"><properties><username>d</username></properties><credentials>"
+ "<password>f</password></credentials><memberof>TestGroup</memberof></user></roles>";
String TEST_CUSTOMER = "apache";
int TEST_HTTP_PORT = TestConstants.PORT;
String TEST_TARGETID = "test-target";
}
|
|
Like Feedback static org.apache.ace.it.deployment.Constants.TEST_AUTH_SCHEME |
|
|
Sample 369. Code Sample / Example / Snippet of static org.apache.ace.it.repository.Utils.get | |
|
public void testEmptyRepository() throws Exception {
Repository mock = new MockDeploymentRepository("", null, null);
TestUtils.configureObject(m_backend, Repository.class, mock);
List<String> versions = m_backend.getVersions(TARGET);
assert versions.size() == 0 : "From an empty repository, we should get 0 versions, but we get "
+ versions.size();
}
|
|
Like Feedback static org.apache.ace.it.repository.Utils.get |
|
|
|
Sample 370. Code Sample / Example / Snippet of org.apache.ace.deployment.provider.impl.ArtifactDataImpl | |
|
public boolean equals(Object other) {
if (!(other instanceof ArtifactDataImpl)) {
return false;
}
ArtifactDataImpl jarFile2 = (ArtifactDataImpl) other;
if (getSymbolicName() != null) {
return getSymbolicName().equals(jarFile2.getSymbolicName()) &&
getVersion().equals(jarFile2.getVersion());
}
else {
return m_url.equals(jarFile2.getUrl());
}
}
|
|
Like Feedback org.apache.ace.deployment.provider.impl.ArtifactDataImpl |
|
|
Sample 371. Code Sample / Example / Snippet of java.util.concurrent.Semaphore | |
|
private void removeRepository(String instanceName) throws IOException, InterruptedException, InvalidSyntaxException {
Configuration[] configs = listConfigurations("(factory.instance.pid=" + instanceName + ")");
if ((configs != null) && (configs.length > 0)) {
final Semaphore sem = new Semaphore(0);
ServiceTracker<Object, Object> tracker = new ServiceTracker<Object, Object>(m_bundleContext, m_bundleContext.createFilter("(factory.instance.pid=" + instanceName + ")"), null) {
@Override
public void removedService(ServiceReference<Object> reference, Object service) {
super.removedService(reference, service);
sem.release();
}
};
tracker.open();
try {
configs[0].delete();
if (!sem.tryAcquire(1, TimeUnit.SECONDS)) {
throw new IOException("Instance did not get removed in time.");
}
}
finally {
tracker.close();
}
}
}
|
|
Like Feedback java.util.concurrent.Semaphore |
|
|
Sample 372. Code Sample / Example / Snippet of org.osgi.service.useradmin.Group | |
|
protected void configureAdditionalServices() throws Exception {
Group group = (Group) m_userAdmin.createRole(TEST_GROUP, Role.GROUP);
group.getProperties().put("type", "userGroup");
User user = (User) m_userAdmin.createRole("TestUser", Role.USER);
user.getProperties().put("email", "testUser@apache.org");
user.getCredentials().put("password", "swordfish");
user.getCredentials().put("certificate", "42".getBytes());
group.addMember(user);
}
|
|
Like Feedback org.osgi.service.useradmin.Group |
|
|
Sample 373. Code Sample / Example / Snippet of org.osgi.service.useradmin.Role | |
|
public void GetUserBroken() {
User newUser = null;
Role newRole = m_userAdmin.createRole((String) "Testuser", Role.USER);
Group group = (Group) m_userAdmin.getRole(TEST_GROUP);
if (newRole != null && group != null) {
newUser = (User) newRole;
newUser.getProperties().put("username", "u");
newUser.getCredentials().put("password", "p");
group.addMember(newUser);
}
assertEquals("Testuser", m_userEditor.getUser("u").getName());
}
|
|
Like Feedback org.osgi.service.useradmin.Role |
|
|
Sample 374. Code Sample / Example / Snippet of java.io.OutputStream | |
|
public static void generateBundle(ArtifactData data, Map<String, String> additionalHeaders) throws IOException {
OutputStream bundleStream = null;
try {
File dataFile = new File(data.getUrl().toURI());
OutputStream fileStream = new FileOutputStream(dataFile);
bundleStream = new JarOutputStream(fileStream, getBundleManifest(data.getSymbolicName(), data.getVersion(), additionalHeaders));
bundleStream.flush();
} catch (URISyntaxException e) {
throw new IOException();
} finally {
if (bundleStream != null) {
bundleStream.close();
}
}
}
|
|
Like Feedback java.io.OutputStream |
|
|
|
Sample 375. Code Sample / Example / Snippet of java.util.jar.Manifest | |
|
public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {
List<ArtifactData> data = m_provider.getBundleData(id, version);
Manifest manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("DeploymentPackage-SymbolicName", id);
main.putValue("DeploymentPackage-Version", version);
for (ArtifactData bd : data) {
manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));
}
return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);
}
|
|
Like Feedback java.util.jar.Manifest |
|
|
Sample 376. Code Sample / Example / Snippet of java.util.jar.Attributes | |
|
public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {
List<ArtifactData> data = m_provider.getBundleData(id, version);
Manifest manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("DeploymentPackage-SymbolicName", id);
main.putValue("DeploymentPackage-Version", version);
for (ArtifactData bd : data) {
manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));
}
return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);
}
|
|
Like Feedback java.util.jar.Attributes |
|
|
Sample 377. Code Sample / Example / Snippet of org.apache.ace.deployment.processor.DeploymentProcessor | |
|
private DeploymentProcessor getDeploymentProcessor(HttpServletRequest request) throws AceRestException {
String processor = request.getParameter(PROCESSOR);
if (processor != null) {
DeploymentProcessor deploymentProcessor = m_processors.get(processor);
if (deploymentProcessor == null) {
throw new AceRestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find a deployment processor called: " + processor);
}
m_log.log(LogService.LOG_DEBUG, "Using deployment processor " + processor);
return deploymentProcessor;
}
m_log.log(LogService.LOG_DEBUG, "Using default deployment processor...");
return new DefaultDeploymentProcessor();
}
|
|
Like Feedback org.apache.ace.deployment.processor.DeploymentProcessor |
|
|
Sample 378. Code Sample / Example / Snippet of org.osgi.service.event.Event | |
|
private Event createEvent(String version, URL dataURL) {
Dictionary<String, Object> properties = new Hashtable<>();
properties.put("deploymentpackage.url", dataURL.toString());
properties.put("deploymentpackage.version", version);
Event event = new Event(TOPIC_DEPLOYMENTPACKAGE_INSTALL, properties);
return event;
}
|
|
Like Feedback org.osgi.service.event.Event |
|
|
Sample 379. Code Sample / Example / Snippet of org.apache.ace.repository.ext.CachedRepository | |
|
private boolean isCacheUpToDate() {
CachedRepository cachedRepository = m_cachedRepository;
try {
return (cachedRepository != null && cachedRepository.isCurrent());
}
catch (IOException ioe) {
m_log.log(LogService.LOG_WARNING, "Failed to check if cache is current. Assuming it's not.", ioe);
return false;
}
}
|
|
Like Feedback org.apache.ace.repository.ext.CachedRepository |
|
|
|
Sample 380. Code Sample / Example / Snippet of java.util.Properties | |
|
public void init(BundleContext context, DependencyManager manager) throws Exception {
manager.add(createComponent()
.setInterface(Servlet.class.getName(), null)
.setImplementation(DeploymentServlet.class)
.add(createConfigurationDependency().setPropagate(true).setPid(DEPLOYMENT_PID))
.add(createServiceDependency().setService(StreamGenerator.class).setRequired(true))
.add(createServiceDependency().setService(DeploymentProvider.class).setRequired(true))
.add(createServiceDependency().setService(DeploymentProcessor.class).setRequired(false).setCallbacks("addProcessor", "removeProcessor"))
.add(createServiceDependency().setService(LogService.class).setRequired(false))
);
manager.add(createComponent()
.setInterface(Servlet.class.getName(), null)
.setImplementation(AgentDeploymentServlet.class)
.add(createConfigurationDependency().setPropagate(true).setPid(AGENT_PID))
.add(createServiceDependency().setService(ConnectionFactory.class).setRequired(true))
.add(createServiceDependency().setService(LogService.class).setRequired(false))
);
Properties props = new Properties();
props.put("pattern", "/*");
manager.add(createComponent()
.setInterface(Filter.class.getName(), null)
.setImplementation(OverloadedFilter.class)
);
}
|
|
Like Feedback java.util.Properties |
|
|
Sample 381. Code Sample / Example / Snippet of javax.servlet.Filter | |
|
public List<ArtifactObject> lrp(String filter) throws Exception {
Filter f = m_context.createFilter(filter);
List<ArtifactObject> rps = m_artifactRepository.getResourceProcessors();
List<ArtifactObject> res = new LinkedList<>();
for (ArtifactObject rp : rps) {
if (f.matchCase(rp.getDictionary())) {
res.add(rp);
}
}
return res;
}
|
|
Like Feedback javax.servlet.Filter |
|
|
Sample 382. Code Sample / Example / Snippet of javax.servlet.http.HttpServletResponse | |
|
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
try {
filterChain.doFilter(request, response);
}
catch (OverloadedException oe) {
OverloadedException overloadedException = (OverloadedException) oe;
httpResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
httpResponse.setHeader(HTTP_RETRY_AFTER, "" + overloadedException.getBackoffTime());
}
}
|
|
Like Feedback javax.servlet.http.HttpServletResponse |
|
|
Sample 383. Code Sample / Example / Snippet of org.w3c.dom.Node | |
|
private static String getNamedItemText(NamedNodeMap map, String name) {
Node namedItem = map.getNamedItem(name);
if (namedItem == null) {
return null;
}
else {
return namedItem.getTextContent();
}
}
|
|
Like Feedback org.w3c.dom.Node |
|
|
Sample 384. Code Sample / Example / Snippet of java.util.concurrent.ExecutorService | |
|
public void hundredStreamsConcurrently() throws Exception {
ExecutorService e = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
e.execute(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
try {
isJarInputStreamReadable();
}
catch (Exception e) {
m_failure = e;
}
}
}
});
}
e.shutdown();
e.awaitTermination(10, TimeUnit.SECONDS);
assert m_failure == null : "Test failed: " + m_failure.getLocalizedMessage();
}
|
|
Like Feedback java.util.concurrent.ExecutorService |
|
|
|
Sample 385. Code Sample / Example / Snippet of org.apache.ace.deployment.provider.repositorybased.BaseRepositoryHandler.XmlDeploymentArtifact | |
|
public void testGatherSingleArtifactOk() throws Exception {
DeploymentArtifactCollector handler = new DeploymentArtifactCollector(TARGET, VERSION1);
m_parser.parse(m_inputStream, handler);
List<XmlDeploymentArtifact>[] artifacts = handler.getArtifacts();
assert artifacts.length == 1 : "Expected a single artifact to be found!";
assert artifacts[0].size() == 1 : "Expected a single artifact to be found!";
XmlDeploymentArtifact artifact1 = artifacts[0].get(0);
assert new URL("file:///bundle1").equals(artifact1.getUrl()) : "Expected 'file:///bundle1' URL to be found!";
assert artifact1.getDirective().size() == 2 : "Expected two directives to be found!";
assert "bundle1".equals(artifact1.getDirective().get(KEY_SYMBOLICNAME)) : "Expected correct symbolic name to be found!";
assert "1.0.0".equals(artifact1.getDirective().get(KEY_VERSION)) : "Expected correct bundle version to be found!";
}
|
|
Like Feedback org.apache.ace.deployment.provider.repositorybased.BaseRepositoryHandler.XmlDeploymentArtifact |
|
|
Sample 386. Code Sample / Example / Snippet of javax.xml.parsers.SAXParserFactory | |
|
protected void setUp() throws Exception {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
m_parser = saxParserFactory.newSAXParser();
String xml = generateValidTestXml();
m_inputStream = new ByteArrayInputStream(xml.getBytes());
}
|
|
Like Feedback javax.xml.parsers.SAXParserFactory |
|
|
Sample 387. Code Sample / Example / Snippet of org.apache.ace.deployment.provider.ArtifactData | |
|
public void testSingleUnchangedBundleMultipleVersions() throws Exception {
Collection<ArtifactData> bundleData = m_backend.getBundleData(TARGET, VERSION1, VERSION1);
assert bundleData.size() == 1 : "Expect one bundle, got " + bundleData.size();
Iterator<ArtifactData> it = bundleData.iterator();
while (it.hasNext()) {
ArtifactData data = it.next();
assert data.getSize() == 100 : "Bundle has no sensible size?! " + data.getSize();
assert !data.hasChanged() : "The data should not have been changed.";
}
}
|
|
Like Feedback org.apache.ace.deployment.provider.ArtifactData |
|
|
Sample 388. Code Sample / Example / Snippet of java.io.BufferedReader | |
|
public Object install(InputStream inputStream) throws Exception {
m_installCalled = true;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream));
String versionString = bufReader.readLine();
if (m_expectedInstallVersion.equals(new Version(versionString))) {
m_correctVersionInstalled = true;
}
return new Version(versionString);
}
|
|
Like Feedback java.io.BufferedReader |
|
|
Sample 389. Code Sample / Example / Snippet of org.apache.ace.repository.Repository | |
|
public void testEmptyRepository() throws Exception {
Repository mock = new MockDeploymentRepository("", null, null);
TestUtils.configureObject(m_backend, Repository.class, mock);
List<String> versions = m_backend.getVersions(TARGET);
assert versions.size() == 0 : "From an empty repository, we should get 0 versions, but we get "
+ versions.size();
}
|
|
Like Feedback org.apache.ace.repository.Repository |
|
|
|
Sample 390. Code Sample / Example / Snippet of javax.xml.parsers.DocumentBuilderFactory | |
|
private Document getDocument(InputStream input) throws IOException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
return builder.parse(input);
}
catch (ParserConfigurationException e) {
throw new IOException("Error instantiation XML parser:" + e.getMessage());
}
catch (SAXException e) {
throw new IOException("Error parsing user data:" + e.getMessage());
}
}
|
|
Like Feedback javax.xml.parsers.DocumentBuilderFactory |
|
|
Sample 391. Code Sample / Example / Snippet of org.apache.ace.builder.DeploymentPackageBuilder | |
|
protected static File createPackage(String name, Version version, File... bundles) throws Exception {
DeploymentPackageBuilder builder = DeploymentPackageBuilder.createDeploymentPackage(name, version.toString());
OutputStream fos = null;
try {
for (File bundle : bundles) {
builder.addBundle(bundle.toURI().toURL());
}
File file = File.createTempFile("testpackage", ".jar");
file.deleteOnExit();
fos = new FileOutputStream(file);
builder.generate(fos);
return file;
}
finally {
if (fos != null) {
fos.close();
}
}
}
|
|
Like Feedback org.apache.ace.builder.DeploymentPackageBuilder |
|
|
Sample 392. Code Sample / Example / Snippet of javax.swing.JScrollPane | |
|
private static final String DEFAULT_PROPERTIES_FILE = "QueueMonitor.properties";
String propertiesFile = DEFAULT_PROPERTIES_FILE;
String broker = "tcp://localhost:61616";
String connectID = "QueueMonitor";
String username = "QueueMonitor";
String password = "QueueMonitor";
String browseQueues = "Q1,Q2,Q3";
String textFontName = "Dialog";
String textFontStyle = "PLAIN";
String textFontSize = "12";
String title = "QueueMonitor";
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
|
|
Like Feedback javax.swing.JScrollPane |
|
|
Sample 393. Code Sample / Example / Snippet of org.osgi.framework.Bundle | |
|
protected void configureProvisionedServices() throws Exception {
final String agentActivatorName = "org.apache.ace.agent.impl.Activator";
Bundle bundle = FrameworkUtil.getBundle(getClass());
Class<?> activatorClass = bundle.loadClass(agentActivatorName);
assertNotNull("Failed to load agent activator class (" + agentActivatorName + ")!", activatorClass);
m_agentActivator = (BundleActivator) activatorClass.newInstance();
}
|
|
Like Feedback org.osgi.framework.Bundle |
|
|
Sample 394. Code Sample / Example / Snippet of org.apache.ace.agent.FeedbackHandler | |
|
private void sendFeedbackToServer() {
try {
FeedbackHandler feedbackHandler = m_agentContext.getHandler(FeedbackHandler.class);
Set<String> channelNames = feedbackHandler.getChannelNames();
for (String channelName : channelNames) {
FeedbackChannel channel = feedbackHandler.getChannel(channelName);
logInfo("Synchronizing feedback of %s with server...", channelName);
channel.sendFeedback();
}
}
catch (Exception exception) {
logWarning("Feedback synchronization failed with %s.", exception, exception.getMessage());
}
}
|
|
Like Feedback org.apache.ace.agent.FeedbackHandler |
|
|
|
Sample 395. Code Sample / Example / Snippet of org.apache.ace.agent.FeedbackChannel | |
|
private void sendFeedbackToServer() {
try {
FeedbackHandler feedbackHandler = m_agentContext.getHandler(FeedbackHandler.class);
Set<String> channelNames = feedbackHandler.getChannelNames();
for (String channelName : channelNames) {
FeedbackChannel channel = feedbackHandler.getChannel(channelName);
logInfo("Synchronizing feedback of %s with server...", channelName);
channel.sendFeedback();
}
}
catch (Exception exception) {
logWarning("Feedback synchronization failed with %s.", exception, exception.getMessage());
}
}
|
|
Like Feedback org.apache.ace.agent.FeedbackChannel |
|
|
Sample 396. Code Sample / Example / Snippet of org.apache.ace.bnd.repository.AceObrRepository | |
|
public static AceObrRepository createRepository(String type, String location) throws Exception {
Map<String, String> properties = new HashMap<>();
properties.put(AceObrRepository.PROP_REPO_TYPE, type);
properties.put(AceObrRepository.PROP_LOCATIONS, location);
AceObrRepository repository = new AceObrRepository();
repository.setProperties(properties);
return repository;
}
|
|
Like Feedback org.apache.ace.bnd.repository.AceObrRepository |
|
|
Sample 397. Code Sample / Example / Snippet of java.net.URI | |
|
public static String getUrl(Resource resource) {
Map<String, Object> attrs = getNamespaceAttributes(resource, "osgi.content");
if (attrs == null)
return null;
URI url = (URI) attrs.get("url");
return url == null ? null : url.toString();
}
|
|
Like Feedback java.net.URI |
|
|
Sample 398. Code Sample / Example / Snippet of org.osgi.framework.Version | |
|
private Version getReleasedBaseVersion(Resource resource) throws Exception {
List<Resource> resources = findResources(m_releaseRepo, getIdentity(resource));
Version resourceVersion = getVersion(resource);
Version baseVersion = Version.emptyVersion;
for (Resource candidate : resources) {
Version candidateVersion = getVersion(candidate);
if (candidateVersion.compareTo(resourceVersion) < 0) {
if (candidateVersion.compareTo(baseVersion) > 0) {
baseVersion = candidateVersion;
}
}
}
return baseVersion;
}
|
|
Like Feedback org.osgi.framework.Version |
|
|
Sample 399. Code Sample / Example / Snippet of java.io.InputStream | |
|
public static boolean filesDiffer(File first, File second) throws Exception {
if (first.length() != second.length()) {
return true;
}
InputStream firstStream = new FileInputStream(first);
InputStream secondStream = new FileInputStream(second);
try {
for (int i = 0; i < first.length(); i++) {
if (firstStream.read() != secondStream.read()) {
return false;
}
}
return true;
}
finally {
try {
firstStream.close();
}
finally {
secondStream.close();
}
}
}
|
|
Like Feedback java.io.InputStream |
|
|
|
Sample 400. Code Sample / Example / Snippet of aQute.bnd.deployer.repository.FixedIndexedRepo | |
|
public static void ls(CommandRepo repo, String filter) throws Exception {
FixedIndexedRepo sourceRepo = repo.repo();
sourceRepo.reset();
Requirement requirement = getRequirement(filter);
List<Resource> resources = findResources(sourceRepo, requirement);
for (Resource resource : resources) {
String location = getUrl(resources.get(0));
System.out.println(resource + " => " + location);
}
}
|
|
Like Feedback aQute.bnd.deployer.repository.FixedIndexedRepo |
|
|
Sample 401. Code Sample / Example / Snippet of java.net.HttpURLConnection | |
|
private HttpURLConnection openConnection() throws IOException {
URL url = m_uri.toURL();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(m_client.isFollowRedirects());
conn.setAllowUserInteraction(false);
conn.setDefaultUseCaches(false);
conn.setUseCaches(false);
conn.setConnectTimeout(1000);
conn.setReadTimeout(1000);
return conn;
}
|
|
Like Feedback java.net.HttpURLConnection |
|
|
Sample 402. Code Sample / Example / Snippet of java.util.Timer | |
|
public void shutdown(long delay) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
m_context.getBundle(0).stop();
}
catch (BundleException e) {
e.printStackTrace();
}
}
}, delay);
}
|
|
Like Feedback java.util.Timer |
|
|
Sample 403. Code Sample / Example / Snippet of java.io.BufferedWriter | |
|
public static File createTmpConfigOnDisk(String config) throws Exception {
File file = File.createTempFile("template", ".xml");
file.deleteOnExit();
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
try {
bw.write(config);
return file;
}
finally {
bw.close();
}
}
|
|
Like Feedback java.io.BufferedWriter |
|
|
Sample 404. Code Sample / Example / Snippet of org.apache.ace.client.rest.util.WebResource | |
|
public static WebResource createEntity(Client c, WebResource work, String type, String data) throws IOException {
WebResource entity = work.path(type);
try {
entity.post(data);
throw new IOException("Could not create " + type + " with data " + data);
}
catch (WebResourceException e2) {
return c.resource(e2.getResponse().getLocation());
}
}
|
|
Like Feedback org.apache.ace.client.rest.util.WebResource |
|
|
|
Sample 405. Code Sample / Example / Snippet of java.net.URL | |
|
public void importDeploymentPackage(String dpURL, boolean autoCommit) throws Exception {
URL url = URI.create(dpURL).toURL();
InputStream is = null;
JarInputStream jis = null;
try {
is = url.openStream();
jis = new JarInputStream(is);
importDeploymentPackage(jis, autoCommit);
}
finally {
closeSilently(is);
closeSilently(jis);
}
}
|
|
Like Feedback java.net.URL |
|
|
Sample 406. Code Sample / Example / Snippet of java.io.File | |
|
private ArtifactObject createArtifact(String name, Attributes attrs, InputStream is) throws Exception {
ArtifactObject artifact = findArtifact(name, attrs);
if (artifact != null) {
return artifact;
}
else if (Boolean.parseBoolean(attrs.getValue(DEPLOYMENT_PACKAGE_MISSING))) {
m_log.log(LogService.LOG_WARNING, String.format("Unable to create artifact '%s' as it is missing...", name));
return null;
}
else {
m_log.log(LogService.LOG_INFO, String.format("Creating artifact '%s'...", name));
File file = storeArtifactContents(name, is);
try {
return m_workspace.createArtifact(file.toURI().toURL().toExternalForm(), true /* upload */);
}
finally {
file.delete();
}
}
}
|
|
Like Feedback java.io.File |
|
|
Sample 407. Code Sample / Example / Snippet of org.apache.ace.client.repository.object.ArtifactObject | |
|
private ArtifactObject createArtifact(String name, Attributes attrs, InputStream is) throws Exception {
ArtifactObject artifact = findArtifact(name, attrs);
if (artifact != null) {
return artifact;
}
else if (Boolean.parseBoolean(attrs.getValue(DEPLOYMENT_PACKAGE_MISSING))) {
m_log.log(LogService.LOG_WARNING, String.format("Unable to create artifact '%s' as it is missing...", name));
return null;
}
else {
m_log.log(LogService.LOG_INFO, String.format("Creating artifact '%s'...", name));
File file = storeArtifactContents(name, is);
try {
return m_workspace.createArtifact(file.toURI().toURL().toExternalForm(), true /* upload */);
}
finally {
file.delete();
}
}
}
|
|
Like Feedback org.apache.ace.client.repository.object.ArtifactObject |
|
|
Sample 408. Code Sample / Example / Snippet of org.osgi.framework.Filter | |
|
public List<ArtifactObject> lrp(String filter) throws Exception {
Filter f = m_context.createFilter(filter);
List<ArtifactObject> rps = m_artifactRepository.getResourceProcessors();
List<ArtifactObject> res = new LinkedList<>();
for (ArtifactObject rp : rps) {
if (f.matchCase(rp.getDictionary())) {
res.add(rp);
}
}
return res;
}
|
|
Like Feedback org.osgi.framework.Filter |
|
|
Sample 409. Code Sample / Example / Snippet of org.apache.ace.client.repository.ObjectRepository | |
|
public void deleteRepositoryObject(String entityType, String entityId) {
ObjectRepository objectRepository = getGenericObjectRepository(entityType);
RepositoryObject repositoryObject = objectRepository.get(entityId);
if (repositoryObject == null) {
throw new IllegalArgumentException("Could not find repository object!");
}
objectRepository.remove(repositoryObject);
}
|
|
Like Feedback org.apache.ace.client.repository.ObjectRepository |
|
|
|
Sample 410. Code Sample / Example / Snippet of org.apache.ace.client.repository.stateful.StatefulTargetRepository | |
|
public RepositoryObject createRepositoryObject(String entityType, Map<String, String> attributes,
Map<String, String> tags) throws IllegalArgumentException {
if (TARGET.equals(entityType)) {
ObjectRepository<StatefulTargetObject> repo = getGenericObjectRepository(TARGET);
StatefulTargetRepository statefulRepo = (StatefulTargetRepository) repo;
return statefulRepo.preregister(attributes, tags);
}
else {
prepareAssociationAttributes(entityType, attributes);
ObjectRepository<?> repo = getGenericObjectRepository(entityType);
return repo.create(attributes, tags);
}
}
|
|
Like Feedback org.apache.ace.client.repository.stateful.StatefulTargetRepository |
|
|
Sample 411. Code Sample / Example / Snippet of com.google.gson.JsonObject | |
|
public JsonElement serialize(Event e, Type typeOfSrc, JsonSerializationContext context) {
DateFormat format = SimpleDateFormat.getDateTimeInstance();
JsonObject event = new JsonObject();
event.addProperty("logId", e.getStoreID());
event.addProperty("id", e.getID());
event.addProperty("time", format.format(new Date(e.getTime())));
event.addProperty("type", toAuditEventType(e.getType()));
JsonObject eventProperties = new JsonObject();
Map<String, String> p = e.getProperties();
for (String key : p.keySet()) {
eventProperties.addProperty(key, p.get(key));
}
event.add("properties", eventProperties);
return event;
}
|
|
Like Feedback com.google.gson.JsonObject |
|
|
Sample 412. Code Sample / Example / Snippet of org.apache.ace.client.repository.RepositoryObject | |
|
private void createRepositoryObject(Workspace workspace, String entityType, RepositoryValueObject data, HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
RepositoryObject object = workspace.createRepositoryObject(entityType, data.attributes, data.tags);
resp.sendRedirect(req.getServletPath() + "/" + buildPathFromElements(WORK_FOLDER, workspace.getSessionID(), entityType, object.getDefinition()));
}
catch (IllegalArgumentException e) {
m_logger.log(LogService.LOG_WARNING, "Failed to add entity of type: " + entityType + " with data: " + data);
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not add entity of type " + entityType + " with data: " + data);
}
}
|
|
Like Feedback org.apache.ace.client.repository.RepositoryObject |
|
|
Sample 413. Code Sample / Example / Snippet of org.apache.felix.framework.util.VersionRange | |
|
private boolean checkOSVersions(String currentOSVersion, String[] osversions)
throws BundleException
{
for (int i = 0; (osversions != null) && (i < osversions.length); i++)
{
try
{
VersionRange range = VersionRange.parse(osversions[i]);
if (range.isInRange(new Version(currentOSVersion)))
{
return true;
}
}
catch (Exception ex)
{
throw new BundleException(
"Error evaluating osversion: " + osversions[i], ex);
}
}
return false;
}
|
|
Like Feedback org.apache.felix.framework.util.VersionRange |
|
|
Sample 414. Code Sample / Example / Snippet of org.apache.felix.framework.capabilityset.SimpleFilter | |
|
private static boolean matchMandatoryAttrbute(String attrName, SimpleFilter sf)
{
if ((sf.getName() != null) && sf.getName().equals(attrName))
{
return true;
}
else if (sf.getOperation() == SimpleFilter.AND)
{
List list = (List) sf.getValue();
for (int i = 0; i < list.size(); i++)
{
SimpleFilter sf2 = (SimpleFilter) list.get(i);
if ((sf2.getName() != null)
&& sf2.getName().equals(attrName))
{
return true;
}
}
}
return false;
}
|
|
Like Feedback org.apache.felix.framework.capabilityset.SimpleFilter |
|
|
|
Sample 415. Code Sample / Example / Snippet of org.apache.ace.connectionfactory.impl.UrlCredentials.AuthType | |
|
private void supplyCredentials(URLConnection conn, UrlCredentials urlCreds) throws IOException {
final AuthType type = urlCreds.getType();
final Object[] creds = urlCreds.getCredentials();
if (AuthType.BASIC.equals(type)) {
applyBasicAuthentication(conn, creds);
}
else if (AuthType.CLIENT_CERT.equals(type)) {
applyClientCertificate(conn, creds);
}
else if (!AuthType.NONE.equals(type)) {
throw new IllegalArgumentException("Unknown authentication type: " + type);
}
}
|
|
Like Feedback org.apache.ace.connectionfactory.impl.UrlCredentials.AuthType |
|
|
Sample 416. Code Sample / Example / Snippet of javax.swing.JButton | |
|
private static final String DEFAULT_PROPERTIES_FILE = "QueueMonitor.properties";
String propertiesFile = DEFAULT_PROPERTIES_FILE;
String broker = "tcp://localhost:61616";
String connectID = "QueueMonitor";
String username = "QueueMonitor";
String password = "QueueMonitor";
String browseQueues = "Q1,Q2,Q3";
String textFontName = "Dialog";
String textFontStyle = "PLAIN";
String textFontSize = "12";
String title = "QueueMonitor";
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JButton browseButton = new JButton("Browse Queues");
|
|
Like Feedback javax.swing.JButton |
|
|
Sample 417. Code Sample / Example / Snippet of java.util.Vector | |
|
private static final String DEFAULT_PROPERTIES_FILE = "QueueMonitor.properties";
String propertiesFile = DEFAULT_PROPERTIES_FILE;
String broker = "tcp://localhost:61616";
String connectID = "QueueMonitor";
String username = "QueueMonitor";
String password = "QueueMonitor";
String browseQueues = "Q1,Q2,Q3";
String textFontName = "Dialog";
String textFontStyle = "PLAIN";
String textFontSize = "12";
String title = "QueueMonitor";
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JButton browseButton = new JButton("Browse Queues");
Vector theQueues = new Vector();
|
|
Like Feedback java.util.Vector |
|
|
Sample 418. Code Sample / Example / Snippet of javax.jms.Session | |
|
private static final String DEFAULT_PROPERTIES_FILE = "MessageMonitor.properties";
String propertiesFile = DEFAULT_PROPERTIES_FILE;
String brokerHostPort = "localhost";
String connectID = "MessageMonitor";
String userID = "Administrator";
String subscriptionTopics = "jms.samples.chat";
String textFontName = "Dialog";
String textFontStyle = "PLAIN";
String textFontSize = "12";
String title = "MessageMonitor";
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JButton clearButton = new JButton("Clear");
Connection connection = null;
Session session = null;
|
|
Like Feedback javax.jms.Session |
|
|
Sample 419. Code Sample / Example / Snippet of javax.jms.Connection | |
|
private static final String DEFAULT_PROPERTIES_FILE = "MessageMonitor.properties";
String propertiesFile = DEFAULT_PROPERTIES_FILE;
String brokerHostPort = "localhost";
String connectID = "MessageMonitor";
String userID = "Administrator";
String subscriptionTopics = "jms.samples.chat";
String textFontName = "Dialog";
String textFontStyle = "PLAIN";
String textFontSize = "12";
String title = "MessageMonitor";
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JButton clearButton = new JButton("Clear");
Connection connection = null;
|
|
Like Feedback javax.jms.Connection |
|
|
|
Sample 420. Code Sample / Example / Snippet of org.apache.activemq.broker.BrokerService | |
|
public static void main(String[] args) throws Exception {
BrokerService broker = new BrokerService();
broker.setUseJmx(true);
broker.addConnector("tcp://localhost:61616");
broker.start();
Object lock = new Object();
synchronized (lock) {
lock.wait();
}
}
|
|
Like Feedback org.apache.activemq.broker.BrokerService |
|
|
Sample 421. Code Sample / Example / Snippet of org.apache.activemq.ActiveMQConnectionFactory | |
|
public void run() throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
connection = factory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic = session.createTopic("topictest.messages");
control = session.createTopic("topictest.control");
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(this);
connection.start();
producer = session.createProducer(control);
System.out.println("Waiting for messages...");
}
|
|
Like Feedback org.apache.activemq.ActiveMQConnectionFactory |
|
|
Sample 422. Code Sample / Example / Snippet of javax.jms.MessageConsumer | |
|
public void run() throws JMSException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(url);
connection = factory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
topic = session.createTopic("topictest.messages");
control = session.createTopic("topictest.control");
MessageConsumer consumer = session.createConsumer(topic);
consumer.setMessageListener(this);
connection.start();
producer = session.createProducer(control);
System.out.println("Waiting for messages...");
}
|
|
Like Feedback javax.jms.MessageConsumer |
|
|
Sample 423. Code Sample / Example / Snippet of org.apache.commons.crypto.cipher.CryptoCipher | |
|
public void testDefaultCipher() throws GeneralSecurityException {
CryptoCipher defaultCipher = CryptoCipherFactory
.getCryptoCipher("AES/CBC/NoPadding");
final String name = defaultCipher.getClass().getName();
if (OpenSsl.getLoadingFailureReason() == null) {
Assert.assertEquals(OpenSslCipher.class.getName(), name);
} else {
Assert.assertEquals(JceCipher.class.getName(), name);
}
}
|
|
Like Feedback org.apache.commons.crypto.cipher.CryptoCipher |
|
|
Sample 424. Code Sample / Example / Snippet of org.apache.commons.crypto.random.CryptoRandom | |
|
protected CryptoRandom getRandom(String className) throws Exception {
Properties props = new Properties();
props.setProperty(CryptoRandomFactory.CLASSES_KEY, className);
final CryptoRandom cryptoRandom = CryptoRandomFactory.getCryptoRandom(props);
Assert.assertEquals(className, cryptoRandom.getClass().getCanonicalName());
return cryptoRandom;
}
|
|
Like Feedback org.apache.commons.crypto.random.CryptoRandom |
|
|
|
Sample 425. Code Sample / Example / Snippet of com.sun.jna.NativeLong | |
|
private void throwOnError(int retVal) {
if (retVal != 1) {
NativeLong err = OpenSslNativeJna.ERR_peek_error();
String errdesc = OpenSslNativeJna.ERR_error_string(err, null);
close();
throw new RuntimeException("return code " + retVal + " from OpenSSL. Err code is " + err + ": " + errdesc);
}
}
|
|
Like Feedback com.sun.jna.NativeLong |
|
|
Sample 426. Code Sample / Example / Snippet of org.apache.bcel.classfile.AnnotationDefault | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.AnnotationDefault |
|
|
Sample 427. Code Sample / Example / Snippet of org.apache.bcel.classfile.Method | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.Method |
|
|
Sample 428. Code Sample / Example / Snippet of org.apache.bcel.classfile.SimpleElementValue | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.SimpleElementValue |
|
|
Sample 429. Code Sample / Example / Snippet of org.apache.bcel.classfile.JavaClass | |
|
public void testMethodAnnotations() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation");
final Method m = getMethod(clazz, "fruit");
final AnnotationDefault a = (AnnotationDefault) findAttribute(
"AnnotationDefault", m.getAttributes());
final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue();
assertTrue("Should be STRING but is " + val.getElementValueType(), val
.getElementValueType() == ElementValue.STRING);
assertTrue("Should have default of bananas but default is "
+ val.getValueString(), val.getValueString().equals("bananas"));
}
|
|
Like Feedback org.apache.bcel.classfile.JavaClass |
|
|
|
Sample 430. Code Sample / Example / Snippet of org.apache.bcel.generic.AnnotationEntryGen | |
|
protected String dumpAnnotationEntries(final AnnotationEntryGen[] as)
{
final StringBuilder result = new StringBuilder();
result.append("[");
for (int i = 0; i < as.length; i++)
{
final AnnotationEntryGen annotation = as[i];
result.append(annotation.toShortString());
if (i + 1 < as.length) {
result.append(",");
}
}
result.append("]");
return result.toString();
}
|
|
Like Feedback org.apache.bcel.generic.AnnotationEntryGen |
|
|
Sample 431. Code Sample / Example / Snippet of org.apache.bcel.generic.ObjectType | |
|
public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp,
final String aFruit, final boolean visibility)
{
final SimpleElementValueGen evg = new SimpleElementValueGen(
ElementValueGen.STRING, cp, aFruit);
final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);
final ObjectType t = new ObjectType("SimpleStringAnnotation");
final List<ElementValuePairGen> elements = new ArrayList<>();
elements.add(nvGen);
return new AnnotationEntryGen(t, elements, visibility, cp);
}
|
|
Like Feedback org.apache.bcel.generic.ObjectType |
|
|
Sample 432. Code Sample / Example / Snippet of org.apache.bcel.generic.ElementValuePairGen | |
|
public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp,
final String aFruit, final boolean visibility)
{
final SimpleElementValueGen evg = new SimpleElementValueGen(
ElementValueGen.STRING, cp, aFruit);
final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);
final ObjectType t = new ObjectType("SimpleStringAnnotation");
final List<ElementValuePairGen> elements = new ArrayList<>();
elements.add(nvGen);
return new AnnotationEntryGen(t, elements, visibility, cp);
}
|
|
Like Feedback org.apache.bcel.generic.ElementValuePairGen |
|
|
Sample 433. Code Sample / Example / Snippet of org.apache.bcel.classfile.Attribute | |
|
protected String dumpAttributes(final Attribute[] as)
{
final StringBuilder result = new StringBuilder();
result.append("AttributeArray:[");
for (int i = 0; i < as.length; i++)
{
final Attribute attr = as[i];
result.append(attr.toString());
if (i + 1 < as.length) {
result.append(",");
}
}
result.append("]");
return result.toString();
}
|
|
Like Feedback org.apache.bcel.classfile.Attribute |
|
|
Sample 434. Code Sample / Example / Snippet of org.apache.bcel.generic.SimpleElementValueGen | |
|
public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp,
final String aFruit, final boolean visibility)
{
final SimpleElementValueGen evg = new SimpleElementValueGen(
ElementValueGen.STRING, cp, aFruit);
final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp);
final ObjectType t = new ObjectType("SimpleStringAnnotation");
final List<ElementValuePairGen> elements = new ArrayList<>();
elements.add(nvGen);
return new AnnotationEntryGen(t, elements, visibility, cp);
}
|
|
Like Feedback org.apache.bcel.generic.SimpleElementValueGen |
|
|
|
Sample 435. Code Sample / Example / Snippet of org.apache.bcel.generic.ClassGen | |
|
public void testCreateIntegerElementValue() throws Exception
{
final ClassGen cg = createClassGen("HelloWorld");
final ConstantPoolGen cp = cg.getConstantPool();
final SimpleElementValueGen evg = new SimpleElementValueGen(
ElementValueGen.PRIMITIVE_INT, cp, 555);
assertTrue("Should have the same index in the constantpool but "
+ evg.getIndex() + "!=" + cp.lookupInteger(555),
evg.getIndex() == cp.lookupInteger(555));
checkSerialize(evg, cp);
}
|
|
Like Feedback org.apache.bcel.generic.ClassGen |
|
|
Sample 436. Code Sample / Example / Snippet of org.apache.bcel.generic.EnumElementValueGen | |
|
public void testCreateEnumElementValue() throws Exception
{
final ClassGen cg = createClassGen("HelloWorld");
final ConstantPoolGen cp = cg.getConstantPool();
final ObjectType enumType = new ObjectType("SimpleEnum"); // Supports rainbow
final EnumElementValueGen evg = new EnumElementValueGen(enumType, "Red", cp);
assertTrue(
"The new ElementValue value index should match the contents of the constantpool but "
+ evg.getValueIndex() + "!=" + cp.lookupUtf8("Red"),
evg.getValueIndex() == cp.lookupUtf8("Red"));
checkSerialize(evg, cp);
}
|
|
Like Feedback org.apache.bcel.generic.EnumElementValueGen |
|
|
Sample 437. Code Sample / Example / Snippet of org.apache.bcel.generic.ClassElementValueGen | |
|
public void testCreateClassElementValue() throws Exception
{
final ClassGen cg = createClassGen("HelloWorld");
final ConstantPoolGen cp = cg.getConstantPool();
final ObjectType classType = new ObjectType("java.lang.Integer");
final ClassElementValueGen evg = new ClassElementValueGen(classType, cp);
assertTrue("Unexpected value for contained class: '"
+ evg.getClassString() + "'", evg.getClassString().contains("Integer"));
checkSerialize(evg, cp);
}
|
|
Like Feedback org.apache.bcel.generic.ClassElementValueGen |
|
|
Sample 438. Code Sample / Example / Snippet of org.apache.bcel.classfile.EnclosingMethod | |
|
public void testCheckMethodLevelNamedInnerClass()
throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");
final ConstantPool pool = clazz.getConstantPool();
final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);
assertTrue("Expected 1 EnclosingMethod attribute but found "
+ encMethodAttrs.length, encMethodAttrs.length == 1);
final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];
final String enclosingClassName = em.getEnclosingClass().getBytes(pool);
final String enclosingMethodName = em.getEnclosingMethod().getName(pool);
assertTrue(
"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "
+ enclosingClassName, enclosingClassName
.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));
assertTrue("Expected method name to be 'main' but was "
+ enclosingMethodName, enclosingMethodName.equals("main"));
}
|
|
Like Feedback org.apache.bcel.classfile.EnclosingMethod |
|
|
Sample 439. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantPool | |
|
public void testCheckMethodLevelNamedInnerClass()
throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S");
final ConstantPool pool = clazz.getConstantPool();
final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz);
assertTrue("Expected 1 EnclosingMethod attribute but found "
+ encMethodAttrs.length, encMethodAttrs.length == 1);
final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0];
final String enclosingClassName = em.getEnclosingClass().getBytes(pool);
final String enclosingMethodName = em.getEnclosingMethod().getName(pool);
assertTrue(
"Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was "
+ enclosingClassName, enclosingClassName
.equals(PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01"));
assertTrue("Expected method name to be 'main' but was "
+ enclosingMethodName, enclosingMethodName.equals("main"));
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantPool |
|
|
|
Sample 440. Code Sample / Example / Snippet of org.apache.bcel.classfile.ArrayElementValue | |
|
private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)
{
final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];
assertEquals("value", elementValuePair.getNameString());
final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();
final ElementValue[] eva = ev.getElementValuesArray();
assertEquals(nExpectedArrayValues, eva.length);
}
|
|
Like Feedback org.apache.bcel.classfile.ArrayElementValue |
|
|
Sample 441. Code Sample / Example / Snippet of org.apache.bcel.util.SyntheticRepository | |
|
private JavaClass getClassFrom(final String where, final String clazzname)
throws ClassNotFoundException
{
final SyntheticRepository repos = createRepos(where);
return repos.loadClass(clazzname);
}
|
|
Like Feedback org.apache.bcel.util.SyntheticRepository |
|
|
Sample 442. Code Sample / Example / Snippet of org.apache.bcel.classfile.ElementValuePair | |
|
private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)
{
final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];
assertEquals("value", elementValuePair.getNameString());
final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();
final ElementValue[] eva = ev.getElementValuesArray();
assertEquals(nExpectedArrayValues, eva.length);
}
|
|
Like Feedback org.apache.bcel.classfile.ElementValuePair |
|
|
Sample 443. Code Sample / Example / Snippet of org.apache.bcel.classfile.ClassParser | |
|
private void testJar(final File file) throws Exception {
System.out.println(file);
try (JarFile jar = new JarFile(file)) {
final Enumeration<JarEntry> en = jar.entries();
while (en.hasMoreElements()) {
final JarEntry e = en.nextElement();
final String name = e.getName();
if (name.endsWith(".class")) {
try (InputStream in = jar.getInputStream(e)) {
final ClassParser parser = new ClassParser(in, name);
final JavaClass jc = parser.parse();
for (final Method m : jc.getMethods()) {
compare(name, m);
}
}
}
}
}
}
|
|
Like Feedback org.apache.bcel.classfile.ClassParser |
|
|
Sample 444. Code Sample / Example / Snippet of org.apache.bcel.classfile.Code | |
|
private void compare(final String name, final Method m) {
final Code c = m.getCode();
if (c == null) {
return; // e.g. abstract method
}
final byte[] src = c.getCode();
final InstructionList il = new InstructionList(src);
final byte[] out = il.getByteCode();
if (src.length == out.length) {
assertArrayEquals(name + ": " + m.toString(), src, out);
} else {
System.out.println(name + ": " + m.toString() + " " + src.length + " " + out.length);
System.out.println(bytesToHex(src));
System.out.println(bytesToHex(out));
for (final InstructionHandle ih : il) {
System.out.println(ih.toString(false));
}
fail("Array comparison failure");
}
}
|
|
Like Feedback org.apache.bcel.classfile.Code |
|
|
|
Sample 445. Code Sample / Example / Snippet of org.apache.bcel.generic.InstructionHandle | |
|
public void testRemoveLocalVariable() throws Exception {
final MethodGen mg = getMethod(Foo.class, "bar");
final LocalVariableGen lv = mg.getLocalVariables()[1];
assertEquals("variable name", "a", lv.getName());
final InstructionHandle start = lv.getStart();
final InstructionHandle end = lv.getEnd();
assertNotNull("scope start", start);
assertNotNull("scope end", end);
assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv));
assertTrue("scope end not targeted by the local variable", Arrays.asList(end.getTargeters()).contains(lv));
mg.removeLocalVariable(lv);
assertFalse("scope start still targeted by the removed variable", Arrays.asList(start.getTargeters()).contains(lv));
assertFalse("scope end still targeted by the removed variable", Arrays.asList(end.getTargeters()).contains(lv));
assertNull("scope start", lv.getStart());
assertNull("scope end", lv.getEnd());
}
|
|
Like Feedback org.apache.bcel.generic.InstructionHandle |
|
|
Sample 446. Code Sample / Example / Snippet of org.apache.bcel.generic.InstructionList | |
|
private void compare(final String name, final Method m) {
final Code c = m.getCode();
if (c == null) {
return; // e.g. abstract method
}
final byte[] src = c.getCode();
final InstructionList il = new InstructionList(src);
final byte[] out = il.getByteCode();
if (src.length == out.length) {
assertArrayEquals(name + ": " + m.toString(), src, out);
} else {
System.out.println(name + ": " + m.toString() + " " + src.length + " " + out.length);
System.out.println(bytesToHex(src));
System.out.println(bytesToHex(out));
for (final InstructionHandle ih : il) {
System.out.println(ih.toString(false));
}
fail("Array comparison failure");
}
}
|
|
Like Feedback org.apache.bcel.generic.InstructionList |
|
|
Sample 447. Code Sample / Example / Snippet of org.apache.bcel.generic.MethodGen | |
|
public void testRemoveLocalVariable() throws Exception {
final MethodGen mg = getMethod(Foo.class, "bar");
final LocalVariableGen lv = mg.getLocalVariables()[1];
assertEquals("variable name", "a", lv.getName());
final InstructionHandle start = lv.getStart();
final InstructionHandle end = lv.getEnd();
assertNotNull("scope start", start);
assertNotNull("scope end", end);
assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv));
assertTrue("scope end not targeted by the local variable", Arrays.asList(end.getTargeters()).contains(lv));
mg.removeLocalVariable(lv);
assertFalse("scope start still targeted by the removed variable", Arrays.asList(start.getTargeters()).contains(lv));
assertFalse("scope end still targeted by the removed variable", Arrays.asList(end.getTargeters()).contains(lv));
assertNull("scope start", lv.getStart());
assertNull("scope end", lv.getEnd());
}
|
|
Like Feedback org.apache.bcel.generic.MethodGen |
|
|
Sample 448. Code Sample / Example / Snippet of org.apache.bcel.generic.InvokeInstruction | |
|
public void testB262() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestEnum");
final ClassGen gen = new ClassGen(clazz);
final ConstantPoolGen pool = gen.getConstantPool();
final Method m = gen.getMethodAt(0);
final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
final InstructionList il = mg.getInstructionList();
final InstructionHandle ih = il.findHandle(3);
final InvokeInstruction ii = (InvokeInstruction)(ih.getInstruction());
final String cn = ii.getClassName(pool);
assertEquals("[Lorg.apache.bcel.data.PLSETestEnum;", cn);
}
|
|
Like Feedback org.apache.bcel.generic.InvokeInstruction |
|
|
Sample 449. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTable | |
|
public void testB79() throws ClassNotFoundException
{
final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass");
final ClassGen gen = new ClassGen(clazz);
final ConstantPoolGen pool = gen.getConstantPool();
final Method m = gen.getMethodAt(2);
final LocalVariableTable lvt = m.getLocalVariableTable();
final MethodGen mg = new MethodGen(m, gen.getClassName(), pool);
final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool());
assertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength());
}
|
|
Like Feedback org.apache.bcel.classfile.LocalVariableTable |
|
|
|
Sample 450. Code Sample / Example / Snippet of org.apache.bcel.generic.FieldGen | |
|
public static void main(String[] argv) throws Exception {
JavaClass clazz;
if ((clazz = Repository.lookupClass(argv[0])) == null) {
clazz = new ClassParser(argv[0]).parse(); // May throw IOException
}
ClassGen cg = new ClassGen(clazz);
for (Method method : clazz.getMethods()) {
MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
cg.replaceMethod(method, mg.getMethod());
}
for (Field field : clazz.getFields()) {
FieldGen fg = new FieldGen(field, cg.getConstantPool());
cg.replaceField(field, fg.getField());
}
cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
}
|
|
Like Feedback org.apache.bcel.generic.FieldGen |
|
|
Sample 451. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantUtf8 | |
|
public static String[] getClassDependencies(ConstantPool pool) {
String[] tempArray = new String[pool.getLength()];
int size = 0;
StringBuilder buf = new StringBuilder();
for (int idx = 0; idx < pool.getLength(); idx++) {
Constant c = pool.getConstant(idx);
if (c != null && c.getTag() == Constants.CONSTANT_Class) {
ConstantUtf8 c1 = (ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex());
buf.setLength(0);
buf.append(c1.getBytes());
for (int n = 0; n < buf.length(); n++) {
if (buf.charAt(n) == '/') {
buf.setCharAt(n, '.');
}
}
tempArray[size++] = buf.toString();
}
}
String[] dependencies = new String[size];
System.arraycopy(tempArray, 0, dependencies, 0, size);
return dependencies;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantUtf8 |
|
|
Sample 452. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantNameAndType | |
|
private void visitRef(ConstantCP ccp, boolean method) {
String class_name = ccp.getClass(cp);
add(class_name);
ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(ccp.getNameAndTypeIndex(),
Constants.CONSTANT_NameAndType);
String signature = cnat.getSignature(cp);
if (method) {
Type type = Type.getReturnType(signature);
checkType(type);
for (Type type1 : Type.getArgumentTypes(signature)) {
checkType(type1);
}
} else {
checkType(Type.getType(signature));
}
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantNameAndType |
|
|
Sample 453. Code Sample / Example / Snippet of org.apache.bcel.generic.LocalVariableGen | |
|
public void testRemoveLocalVariable() throws Exception {
final MethodGen mg = getMethod(Foo.class, "bar");
final LocalVariableGen lv = mg.getLocalVariables()[1];
assertEquals("variable name", "a", lv.getName());
final InstructionHandle start = lv.getStart();
final InstructionHandle end = lv.getEnd();
assertNotNull("scope start", start);
assertNotNull("scope end", end);
assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv));
assertTrue("scope end not targeted by the local variable", Arrays.asList(end.getTargeters()).contains(lv));
mg.removeLocalVariable(lv);
assertFalse("scope start still targeted by the removed variable", Arrays.asList(start.getTargeters()).contains(lv));
assertFalse("scope end still targeted by the removed variable", Arrays.asList(end.getTargeters()).contains(lv));
assertNull("scope start", lv.getStart());
assertNull("scope end", lv.getEnd());
}
|
|
Like Feedback org.apache.bcel.generic.LocalVariableGen |
|
|
Sample 454. Code Sample / Example / Snippet of org.apache.bcel.util.BCELifier | |
|
public void test() throws Exception {
final OutputStream os = new ByteArrayOutputStream();
final JavaClass java_class = BCELifier.getJavaClass("Java8Example");
assertNotNull(java_class);
final BCELifier bcelifier = new BCELifier(java_class, os);
bcelifier.start();
}
|
|
Like Feedback org.apache.bcel.util.BCELifier |
|
|
|
Sample 455. Code Sample / Example / Snippet of org.apache.bcel.util.InstructionFinder | |
|
public void testSearch() {
final InstructionList il = new InstructionList();
il.append(new ILOAD(1));
il.append(new ILOAD(2));
il.append(new IADD());
il.append(new ISTORE(3));
final InstructionFinder finder = new InstructionFinder(il);
final Iterator<?> it = finder.search("ILOAD IADD", il.getInstructionHandles()[0], null );
final InstructionHandle[] ihs = (InstructionHandle[])it.next();
assertEquals(2, ihs.length);
assertEquals(ihs[0].getInstruction(), new ILOAD(2));
assertEquals(ihs[1].getInstruction(), new IADD());
}
|
|
Like Feedback org.apache.bcel.util.InstructionFinder |
|
|
Sample 456. Code Sample / Example / Snippet of org.apache.bcel.util.ClassPath | |
|
public static ClassPath.ClassFile lookupClassFile( final String class_name ) {
try {
final ClassPath path = repository.getClassPath();
if (path == null) {
return null;
}
return path.getClassFile(class_name);
} catch (final IOException e) {
return null;
}
}
|
|
Like Feedback org.apache.bcel.util.ClassPath |
|
|
Sample 457. Code Sample / Example / Snippet of org.apache.bcel.classfile.Constant | |
|
public String getEnumTypeString()
{
return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))
.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.Constant |
|
|
Sample 458. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantInteger | |
|
public int getValueInt()
{
if (super.getElementValueType() != PRIMITIVE_INT) {
throw new RuntimeException(
"Dont call getValueString() on a non STRING ElementValue");
}
final ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx);
return c.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantInteger |
|
|
Sample 459. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantClass | |
|
public String getEnumTypeString()
{
return ((ConstantUtf8) getConstantPool().getConstant(typeIdx))
.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantClass |
|
|
|
Sample 460. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantCP | |
|
public String getClassName( final ConstantPoolGen cpg ) {
final ConstantPool cp = cpg.getConstantPool();
final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class);
if (className.startsWith("[")) {
return "java.lang.Object";
}
return className.replace('/', '.');
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantCP |
|
|
Sample 461. Code Sample / Example / Snippet of org.apache.bcel.classfile.Annotations | |
|
public FieldGen(final Field field, final ConstantPoolGen cp) {
this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);
final Attribute[] attrs = field.getAttributes();
for (final Attribute attr : attrs) {
if (attr instanceof ConstantValue) {
setValue(((ConstantValue) attr).getConstantValueIndex());
} else if (attr instanceof Annotations) {
final Annotations runtimeAnnotations = (Annotations)attr;
final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries();
for (final AnnotationEntry element : annotationEntries) {
addAnnotationEntry(new AnnotationEntryGen(element,cp,false));
}
} else {
addAttribute(attr);
}
}
}
|
|
Like Feedback org.apache.bcel.classfile.Annotations |
|
|
Sample 462. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantFloat | |
|
public int lookupFloat( final float n ) {
final int bits = Float.floatToIntBits(n);
for (int i = 1; i < index; i++) {
if (constants[i] instanceof ConstantFloat) {
final ConstantFloat c = (ConstantFloat) constants[i];
if (Float.floatToIntBits(c.getBytes()) == bits) {
return i;
}
}
}
return -1;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantFloat |
|
|
Sample 463. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantString | |
|
public String stringifyValue()
{
final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(valueIdx);
return cu8.getBytes();
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantString |
|
|
Sample 464. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantLong | |
|
public int lookupLong( final long n ) {
for (int i = 1; i < index; i++) {
if (constants[i] instanceof ConstantLong) {
final ConstantLong c = (ConstantLong) constants[i];
if (c.getBytes() == n) {
return i;
}
}
}
return -1;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantLong |
|
|
|
Sample 465. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantDouble | |
|
public int lookupDouble( final double n ) {
final long bits = Double.doubleToLongBits(n);
for (int i = 1; i < index; i++) {
if (constants[i] instanceof ConstantDouble) {
final ConstantDouble c = (ConstantDouble) constants[i];
if (Double.doubleToLongBits(c.getBytes()) == bits) {
return i;
}
}
}
return -1;
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantDouble |
|
|
Sample 466. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantValue | |
|
public void visitField( final Field field ) {
_out.println();
_out.println(" field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", "
+ printType(field.getSignature()) + ", "" + field.getName() + "", _cp);");
final ConstantValue cv = field.getConstantValue();
if (cv != null) {
final String value = cv.toString();
_out.println(" field.setInitValue(" + value + ")");
}
_out.println(" _cg.addField(field.getField());");
}
|
|
Like Feedback org.apache.bcel.classfile.ConstantValue |
|
|
Sample 467. Code Sample / Example / Snippet of org.apache.bcel.generic.BranchHandle | |
|
private static BranchHandle bh_list = null; // List of reusable handles
static BranchHandle getBranchHandle( final BranchInstruction i ) {
if (bh_list == null) {
return new BranchHandle(i);
}
final BranchHandle bh = bh_list;
bh_list = (BranchHandle) bh.getNext();
bh.setInstruction(i);
return bh;
}
|
|
Like Feedback org.apache.bcel.generic.BranchHandle |
|
|
Sample 468. Code Sample / Example / Snippet of org.apache.bcel.generic.BranchInstruction | |
|
public void redirectBranches(final InstructionHandle old_target, final InstructionHandle new_target) {
for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) {
final Instruction i = ih.getInstruction();
if (i instanceof BranchInstruction) {
final BranchInstruction b = (BranchInstruction) i;
final InstructionHandle target = b.getTarget();
if (target == old_target) {
b.setTarget(new_target);
}
if (b instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH
final InstructionHandle[] targets = ((Select) b).getTargets();
for (int j = 0; j < targets.length; j++) {
if (targets[j] == old_target) {
((Select) b).setTarget(j, new_target);
}
}
}
}
}
}
|
|
Like Feedback org.apache.bcel.generic.BranchInstruction |
|
|
Sample 469. Code Sample / Example / Snippet of org.apache.bcel.generic.Instruction | |
|
public Instruction copy() {
Instruction i = null;
if (InstructionConst.getInstruction(this.getOpcode()) != null) {
i = this;
} else {
try {
i = (Instruction) clone();
} catch (final CloneNotSupportedException e) {
System.err.println(e);
}
}
return i;
}
|
|
Like Feedback org.apache.bcel.generic.Instruction |
|
|
|
Sample 470. Code Sample / Example / Snippet of org.apache.bcel.generic.Select | |
|
protected Object clone() throws CloneNotSupportedException {
final Select copy = (Select) super.clone();
copy.match = match.clone();
copy.indices = indices.clone();
copy.targets = targets.clone();
return copy;
}
|
|
Like Feedback org.apache.bcel.generic.Select |
|
|
Sample 471. Code Sample / Example / Snippet of org.apache.bcel.generic.CPInstruction | |
|
public void replaceConstantPool(final ConstantPoolGen old_cp, final ConstantPoolGen new_cp) {
for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) {
final Instruction i = ih.getInstruction();
if (i instanceof CPInstruction) {
final CPInstruction ci = (CPInstruction) i;
final Constant c = old_cp.getConstant(ci.getIndex());
ci.setIndex(new_cp.addConstant(c, old_cp));
}
}
}
|
|
Like Feedback org.apache.bcel.generic.CPInstruction |
|
|
Sample 472. Code Sample / Example / Snippet of org.apache.bcel.util.ClassQueue | |
|
public JavaClass[] getAllInterfaces() throws ClassNotFoundException {
final ClassQueue queue = new ClassQueue();
final Set<JavaClass> allInterfaces = new TreeSet<>();
queue.enqueue(this);
while (!queue.empty()) {
final JavaClass clazz = queue.dequeue();
final JavaClass souper = clazz.getSuperClass();
final JavaClass[] _interfaces = clazz.getInterfaces();
if (clazz.isInterface()) {
allInterfaces.add(clazz);
} else {
if (souper != null) {
queue.enqueue(souper);
}
}
for (final JavaClass _interface : _interfaces) {
queue.enqueue(_interface);
}
}
return allInterfaces.toArray(new JavaClass[allInterfaces.size()]);
}
|
|
Like Feedback org.apache.bcel.util.ClassQueue |
|
|
Sample 473. Code Sample / Example / Snippet of org.apache.bcel.generic.ReferenceType | |
|
public ObjectType getLoadClassType( final ConstantPoolGen cpg ) {
final ReferenceType rt = getReferenceType(cpg);
if(rt instanceof ObjectType) {
return (ObjectType)rt;
}
throw new ClassGenException(rt.getSignature() + " does not represent an ObjectType");
}
|
|
Like Feedback org.apache.bcel.generic.ReferenceType |
|
|
Sample 474. Code Sample / Example / Snippet of org.apache.bcel.verifier.VerificationResult | |
|
public void testDefaultMethodValidation() {
final String classname = Collection.class.getName();
final Verifier verifier = VerifierFactory.getVerifier(classname);
VerificationResult result = verifier.doPass1();
assertEquals("Pass 1 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,
result.getStatus());
result = verifier.doPass2();
assertEquals("Pass 2 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,
result.getStatus());
}
|
|
Like Feedback org.apache.bcel.verifier.VerificationResult |
|
|
|
Sample 475. Code Sample / Example / Snippet of org.apache.bcel.verifier.Verifier | |
|
public void testDefaultMethodValidation() {
final String classname = Collection.class.getName();
final Verifier verifier = VerifierFactory.getVerifier(classname);
VerificationResult result = verifier.doPass1();
assertEquals("Pass 1 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,
result.getStatus());
result = verifier.doPass2();
assertEquals("Pass 2 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK,
result.getStatus());
}
|
|
Like Feedback org.apache.bcel.verifier.Verifier |
|
|
Sample 476. Code Sample / Example / Snippet of org.apache.bcel.classfile.MethodParameters | |
|
public Attribute copy(final ConstantPool _constant_pool) {
final MethodParameters c = (MethodParameters) clone();
c.parameters = new MethodParameter[parameters.length];
for (int i = 0; i < parameters.length; i++) {
c.parameters[i] = parameters[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.MethodParameters |
|
|
Sample 477. Code Sample / Example / Snippet of org.apache.bcel.classfile.BootstrapMethods | |
|
public BootstrapMethods copy(final ConstantPool _constant_pool) {
final BootstrapMethods c = (BootstrapMethods) clone();
c.bootstrap_methods = new BootstrapMethod[bootstrap_methods.length];
for (int i = 0; i < bootstrap_methods.length; i++) {
c.bootstrap_methods[i] = bootstrap_methods[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.BootstrapMethods |
|
|
Sample 478. Code Sample / Example / Snippet of org.apache.bcel.classfile.InnerClasses | |
|
public Attribute copy(final ConstantPool _constant_pool) {
final InnerClasses c = (InnerClasses) clone();
c.inner_classes = new InnerClass[inner_classes.length];
for (int i = 0; i < inner_classes.length; i++) {
c.inner_classes[i] = inner_classes[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.InnerClasses object initialization using clone |
|
|
Sample 479. Code Sample / Example / Snippet of org.apache.bcel.classfile.Synthetic | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final Synthetic c = (Synthetic) clone();
if (bytes != null) {
c.bytes = new byte[bytes.length];
System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.Synthetic |
|
|
|
Sample 480. Code Sample / Example / Snippet of org.apache.bcel.classfile.LocalVariableTypeTable | |
|
public Attribute copy(final ConstantPool constant_pool) {
final LocalVariableTypeTable c = (LocalVariableTypeTable) clone();
c.local_variable_type_table = new LocalVariable[local_variable_type_table.length];
for (int i = 0; i < local_variable_type_table.length; i++) {
c.local_variable_type_table[i] = local_variable_type_table[i].copy();
}
c.setConstantPool(constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.LocalVariableTypeTable |
|
|
Sample 481. Code Sample / Example / Snippet of org.apache.bcel.classfile.Node | |
|
public void jjtAddChild(Node n, int i) {
if (children == null) {
children = new Node[i + 1];
} else if (i >= children.length) {
Node c[] = new Node[i + 1];
System.arraycopy(children, 0, c, 0, children.length);
children = c;
}
children[i] = n;
}
|
|
Like Feedback org.apache.bcel.classfile.Node |
|
|
Sample 482. Code Sample / Example / Snippet of org.apache.bcel.classfile.ParameterAnnotations | |
|
public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attrs) {
final List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length);
for (final Attribute attribute : attrs) {
if (attribute instanceof ParameterAnnotations) {
final ParameterAnnotations runtimeAnnotations = (ParameterAnnotations)attribute;
Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getParameterAnnotationEntries());
}
}
return accumulatedAnnotations.toArray(new ParameterAnnotationEntry[accumulatedAnnotations.size()]);
}
|
|
Like Feedback org.apache.bcel.classfile.ParameterAnnotations |
|
|
Sample 483. Code Sample / Example / Snippet of org.apache.bcel.classfile.Unknown | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final Unknown c = (Unknown) clone();
if (bytes != null) {
c.bytes = new byte[bytes.length];
System.arraycopy(bytes, 0, c.bytes, 0, bytes.length);
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.Unknown |
|
|
Sample 484. Code Sample / Example / Snippet of org.apache.bcel.classfile.StackMap | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final StackMap c = (StackMap) clone();
c.map = new StackMapEntry[map.length];
for (int i = 0; i < map.length; i++) {
c.map[i] = map[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.StackMap |
|
|
|
Sample 485. Code Sample / Example / Snippet of org.apache.bcel.classfile.LineNumberTable | |
|
public Attribute copy( final ConstantPool _constant_pool ) {
final LineNumberTable c = (LineNumberTable) clone();
c.line_number_table = new LineNumber[line_number_table.length];
for (int i = 0; i < line_number_table.length; i++) {
c.line_number_table[i] = line_number_table[i].copy();
}
c.setConstantPool(_constant_pool);
return c;
}
|
|
Like Feedback org.apache.bcel.classfile.LineNumberTable |
|
|
Sample 486. Code Sample / Example / Snippet of org.apache.bcel.classfile.DescendingVisitor | |
|
private void field_and_method_refs_are_valid() {
try {
final JavaClass jc = Repository.lookupClass(myOwner.getClassName());
final DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc));
v.visit();
} catch (final ClassNotFoundException e) {
throw new AssertionViolatedException("Missing class: " + e, e);
}
}
|
|
Like Feedback org.apache.bcel.classfile.DescendingVisitor |
|
|
Sample 487. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveEntry | |
|
private void addArchiveEntry(final ArchiveOutputStream out, final String filename, final File infile)
throws IOException, FileNotFoundException {
final ArchiveEntry entry = out.createArchiveEntry(infile, filename);
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(infile), out);
out.closeArchiveEntry();
archiveList.add(filename);
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveEntry |
|
|
Sample 488. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveOutputStream | |
|
protected File createEmptyArchive(final String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
archiveList = new ArrayList<String>();
try {
archive = File.createTempFile("empty", "." + archivename);
archive.deleteOnExit();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
out.finish();
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
return archive;
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveOutputStream |
|
|
Sample 489. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveInputStream | |
|
protected void checkArchiveContent(final File archive, final List<String> expected)
throws Exception {
final InputStream is = new FileInputStream(archive);
try {
final BufferedInputStream buf = new BufferedInputStream(is);
final ArchiveInputStream in = factory.createArchiveInputStream(buf);
this.checkArchiveContent(in, expected);
} finally {
is.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveInputStream |
|
|
|
Sample 490. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveEntry | |
|
protected String getExpectedString(final ArchiveEntry entry) {
if (entry instanceof TarArchiveEntry) {
final TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
if (tarEntry.isSymbolicLink()) {
return tarEntry.getName() + " -> " + tarEntry.getLinkName();
}
}
return entry.getName();
}
|
|
Like Feedback org.apache.commons.compress.archivers.tar.TarArchiveEntry |
|
|
Sample 491. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveInputStream | |
|
private void testZipStreamWithImplodeCompression(final String filename, final String entryName) throws IOException {
final ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(new File(filename)));
final ZipArchiveEntry entry = zin.getNextZipEntry();
assertEquals("entry name", entryName, entry.getName());
assertTrue("entry can't be read", zin.canReadEntryData(entry));
assertEquals("method", ZipMethod.IMPLODING.getCode(), entry.getMethod());
final InputStream bio = new BoundedInputStream(zin, entry.getSize());
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final CheckedOutputStream out = new CheckedOutputStream(bout, new CRC32());
IOUtils.copy(bio, out);
out.flush();
assertEquals("CRC32", entry.getCrc(), out.getChecksum().getValue());
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipArchiveInputStream |
|
|
Sample 492. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.arj.ArjArchiveInputStream | |
|
public void testArjUnarchive() throws Exception {
final StringBuilder expected = new StringBuilder();
expected.append("test1.xml<?xml version="1.0"?>
");
expected.append("<empty/>test2.xml<?xml version="1.0"?>
");
expected.append("<empty/>
");
final ArjArchiveInputStream in = new ArjArchiveInputStream(new FileInputStream(getFile("bla.arj")));
ArjArchiveEntry entry;
final StringBuilder result = new StringBuilder();
while ((entry = in.getNextEntry()) != null) {
result.append(entry.getName());
int tmp;
while ((tmp = in.read()) != -1) {
result.append((char) tmp);
}
assertFalse(entry.isDirectory());
}
in.close();
assertEquals(result.toString(), expected.toString());
}
|
|
Like Feedback org.apache.commons.compress.archivers.arj.ArjArchiveInputStream |
|
|
Sample 493. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ar.ArArchiveEntry | |
|
public void testLongFileNamesCauseExceptionByDefault() {
ArArchiveOutputStream os = null;
try {
os = new ArArchiveOutputStream(new ByteArrayOutputStream());
final ArArchiveEntry ae = new ArArchiveEntry("this_is_a_long_name.txt",
0);
os.putArchiveEntry(ae);
fail("Expected an exception");
} catch (final IOException ex) {
assertTrue(ex.getMessage().startsWith("filename too long"));
} finally {
closeQuietly(os);
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.ar.ArArchiveEntry |
|
|
Sample 494. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveEntry | |
|
public void testCompressionMethod() throws Exception {
final ZipArchiveOutputStream zos =
new ZipArchiveOutputStream(new ByteArrayOutputStream());
final ZipArchiveEntry entry = new ZipArchiveEntry("foo");
assertEquals(-1, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.STORED);
assertEquals(ZipEntry.STORED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.DEFLATED);
assertEquals(ZipEntry.DEFLATED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(6);
assertEquals(6, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
zos.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipArchiveEntry |
|
|
|
Sample 495. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipFile | |
|
private void removeEntriesFoundInZipFile(final File result, final Map<String, byte[]> entries) throws IOException {
final ZipFile zf = new ZipFile(result);
final Enumeration<ZipArchiveEntry> entriesInPhysicalOrder = zf.getEntriesInPhysicalOrder();
while (entriesInPhysicalOrder.hasMoreElements()){
final ZipArchiveEntry zipArchiveEntry = entriesInPhysicalOrder.nextElement();
final InputStream inputStream = zf.getInputStream(zipArchiveEntry);
final byte[] actual = IOUtils.toByteArray(inputStream);
final byte[] expected = entries.remove(zipArchiveEntry.getName());
assertArrayEquals( "For " + zipArchiveEntry.getName(), expected, actual);
}
zf.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipFile |
|
|
Sample 496. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZOutputFile | |
|
public void testReadingBackLZMA2DictSize() throws Exception {
final File output = new File(dir, "lzma2-dictsize.7z");
final SevenZOutputFile outArchive = new SevenZOutputFile(output);
try {
outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20)));
final SevenZArchiveEntry entry = new SevenZArchiveEntry();
entry.setName("foo.txt");
outArchive.putArchiveEntry(entry);
outArchive.write(new byte[] { 'A' });
outArchive.closeArchiveEntry();
} finally {
outArchive.close();
}
final SevenZFile archive = new SevenZFile(output);
try {
final SevenZArchiveEntry entry = archive.getNextEntry();
final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next();
assertEquals(SevenZMethod.LZMA2, m.getMethod());
assertEquals(1 << 20, m.getOptions());
} finally {
archive.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.sevenz.SevenZOutputFile |
|
|
Sample 497. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZFile | |
|
public void testAllEmptyFilesArchive() throws Exception {
final SevenZFile archive = new SevenZFile(getFile("7z-empty-mhc-off.7z"));
try {
assertNotNull(archive.getNextEntry());
} finally {
archive.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.sevenz.SevenZFile |
|
|
Sample 498. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry | |
|
public void testReadingBackLZMA2DictSize() throws Exception {
final File output = new File(dir, "lzma2-dictsize.7z");
final SevenZOutputFile outArchive = new SevenZOutputFile(output);
try {
outArchive.setContentMethods(Arrays.asList(new SevenZMethodConfiguration(SevenZMethod.LZMA2, 1 << 20)));
final SevenZArchiveEntry entry = new SevenZArchiveEntry();
entry.setName("foo.txt");
outArchive.putArchiveEntry(entry);
outArchive.write(new byte[] { 'A' });
outArchive.closeArchiveEntry();
} finally {
outArchive.close();
}
final SevenZFile archive = new SevenZFile(output);
try {
final SevenZArchiveEntry entry = archive.getNextEntry();
final SevenZMethodConfiguration m = entry.getContentMethods().iterator().next();
assertEquals(SevenZMethod.LZMA2, m.getMethod());
assertEquals(1 << 20, m.getOptions());
} finally {
archive.close();
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry |
|
|
Sample 499. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream | |
|
public void testCpioUnarchive() throws Exception {
final StringBuilder expected = new StringBuilder();
expected.append("./test1.xml<?xml version="1.0"?>
");
expected.append("<empty/>./test2.xml<?xml version="1.0"?>
");
expected.append("<empty/>
");
final CpioArchiveInputStream in = new CpioArchiveInputStream(new FileInputStream(getFile("bla.cpio")));
CpioArchiveEntry entry;
final StringBuilder result = new StringBuilder();
while ((entry = (CpioArchiveEntry) in.getNextEntry()) != null) {
result.append(entry.getName());
int tmp;
while ((tmp = in.read()) != -1) {
result.append((char) tmp);
}
}
in.close();
assertEquals(result.toString(), expected.toString());
}
|
|
Like Feedback org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream |
|
|
|
Sample 500. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipEncoding | |
|
private static void assertUnicodeName(final ZipArchiveEntry ze,
final String expectedName,
final String encoding)
throws IOException {
if (!expectedName.equals(ze.getName())) {
final UnicodePathExtraField ucpf = findUniCodePath(ze);
assertNotNull(ucpf);
final ZipEncoding enc = ZipEncodingHelper.getZipEncoding(encoding);
final ByteBuffer ne = enc.encode(ze.getName());
final CRC32 crc = new CRC32();
crc.update(ne.array(), ne.arrayOffset(),
ne.limit() - ne.position());
assertEquals(crc.getValue(), ucpf.getNameCRC32());
assertEquals(expectedName, new String(ucpf.getUnicodeName(),
CharsetNames.UTF_8));
}
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipEncoding |
|
|
Sample 501. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveStreamFactory | |
|
public void testEncodingCtor() {
ArchiveStreamFactory fac = new ArchiveStreamFactory();
assertNull(fac.getEntryEncoding());
fac = new ArchiveStreamFactory(null);
assertNull(fac.getEntryEncoding());
fac = new ArchiveStreamFactory("UTF-8");
assertEquals("UTF-8", fac.getEntryEncoding());
}
|
|
Like Feedback org.apache.commons.compress.archivers.ArchiveStreamFactory |
|
|
Sample 502. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorStreamFactory | |
|
public void testOverride() {
CompressorStreamFactory fac = new CompressorStreamFactory();
assertFalse(fac.getDecompressConcatenated());
fac.setDecompressConcatenated(true);
assertTrue(fac.getDecompressConcatenated());
fac = new CompressorStreamFactory(false);
assertFalse(fac.getDecompressConcatenated());
try {
fac.setDecompressConcatenated(true);
fail("Expected IllegalStateException");
} catch (final IllegalStateException ise) {
}
fac = new CompressorStreamFactory(true);
assertTrue(fac.getDecompressConcatenated());
try {
fac.setDecompressConcatenated(true);
fail("Expected IllegalStateException");
} catch (final IllegalStateException ise) {
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.CompressorStreamFactory |
|
|
Sample 503. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorInputStream | |
|
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
final FileOutputStream os = new FileOutputStream(output);
IOUtils.copy(in, os);
is.close();
os.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.CompressorInputStream |
|
|
Sample 504. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.gzip.GzipParameters | |
|
public void testInvalidCompressionLevel() {
final GzipParameters parameters = new GzipParameters();
try {
parameters.setCompressionLevel(10);
fail("IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
}
try {
parameters.setCompressionLevel(-5);
fail("IllegalArgumentException not thrown");
} catch (final IllegalArgumentException e) {
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.gzip.GzipParameters |
|
|
|
Sample 505. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream | |
|
private void testExtraFlags(final int compressionLevel, final int flag) throws Exception {
final FileInputStream fis = new FileInputStream(getFile("test3.xml"));
byte[] content;
try {
content = IOUtils.toByteArray(fis);
} finally {
fis.close();
}
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
final GzipParameters parameters = new GzipParameters();
parameters.setCompressionLevel(compressionLevel);
final GzipCompressorOutputStream out = new GzipCompressorOutputStream(bout, parameters);
IOUtils.copy(new ByteArrayInputStream(content), out);
out.flush();
out.close();
assertEquals("extra flags (XFL)", flag, bout.toByteArray()[8]);
}
|
|
Like Feedback org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream |
|
|
Sample 506. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateParameters | |
|
public void testRawDeflateCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.deflate");
final OutputStream out = new FileOutputStream(output);
try {
final DeflateParameters params = new DeflateParameters();
params.setWithZlibHeader(false);
final CompressorOutputStream cos = new DeflateCompressorOutputStream(out, params);
try {
IOUtils.copy(new FileInputStream(input), cos);
} finally {
cos.close();
}
} finally {
out.close();
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.deflate.DeflateParameters |
|
|
Sample 507. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveInputStream | |
|
public void readSimplePaxHeader() throws Exception {
final InputStream is = new ByteArrayInputStream(new byte[1]);
final TarArchiveInputStream tais = new TarArchiveInputStream(is);
final Map<String, String> headers = tais
.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463
"
.getBytes(CharsetNames.UTF_8)));
assertEquals(1, headers.size());
assertEquals("1321711775.972059463", headers.get("atime"));
tais.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.tar.TarArchiveInputStream |
|
|
Sample 508. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream | |
|
public void readOfLength0ShouldReturn0() throws Exception {
final byte[] rawData = new byte[1048576];
for (int i=0; i < rawData.length; ++i) {
rawData[i] = (byte) Math.floor(Math.random()*256);
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);
bzipOut.write(rawData);
bzipOut.flush();
bzipOut.close();
baos.flush();
baos.close();
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);
final byte[] buffer = new byte[1024];
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
bzipIn.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream |
|
|
Sample 509. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BitInputStream | |
|
public void testClearBitCache() throws IOException {
final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);
assertEquals(0x08, bis.readBits(4));
bis.clearBitCache();
assertEquals(0, bis.readBits(1));
bis.close();
}
|
|
Like Feedback org.apache.commons.compress.utils.BitInputStream |
|
|
|
Sample 510. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BoundedInputStream | |
|
public void writeTo(final ZipArchiveOutputStream target) throws IOException {
backingStore.closeForWriting();
final InputStream data = backingStore.getInputStream();
for (final CompressedEntry compressedEntry : items) {
final BoundedInputStream rawStream = new BoundedInputStream(data, compressedEntry.compressedSize);
target.addRawArchiveEntry(compressedEntry.transferToArchiveEntry(), rawStream);
rawStream.close();
}
data.close();
}
|
|
Like Feedback org.apache.commons.compress.utils.BoundedInputStream |
|
|
Sample 511. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream | |
|
public void testCompressionMethod() throws Exception {
final ZipArchiveOutputStream zos =
new ZipArchiveOutputStream(new ByteArrayOutputStream());
final ZipArchiveEntry entry = new ZipArchiveEntry("foo");
assertEquals(-1, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.STORED);
assertEquals(ZipEntry.STORED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(ZipEntry.DEFLATED);
assertEquals(ZipEntry.DEFLATED, entry.getMethod());
assertTrue(zos.canWriteEntryData(entry));
entry.setMethod(6);
assertEquals(6, entry.getMethod());
assertFalse(zos.canWriteEntryData(entry));
zos.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream |
|
|
Sample 512. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveOutputStream | |
|
public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()
throws Exception {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final String encoding = CharsetNames.UTF_16;
final String name = "1234567890123456789012345678901234567890123456789"
+ "01234567890123456789012345678901234567890123456789"
+ "01234567890u00e4";
final TarArchiveOutputStream tos =
new TarArchiveOutputStream(bos, encoding);
tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
TarArchiveEntry t = new TarArchiveEntry(name);
t.setSize(1);
tos.putArchiveEntry(t);
tos.write(30);
tos.closeArchiveEntry();
tos.close();
final byte[] data = bos.toByteArray();
final ByteArrayInputStream bis = new ByteArrayInputStream(data);
final TarArchiveInputStream tis =
new TarArchiveInputStream(bis, encoding);
t = tis.getNextTarEntry();
assertEquals(name, t.getName());
tis.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.tar.TarArchiveOutputStream |
|
|
Sample 513. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.dump.DumpArchiveInputStream | |
|
public void testConsumesArchiveCompletely() throws Exception {
final InputStream is = DumpArchiveInputStreamTest.class
.getResourceAsStream("/archive_with_trailer.dump");
final DumpArchiveInputStream dump = new DumpArchiveInputStream(is);
while (dump.getNextDumpEntry() != null) {
}
final byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '
'
};
final byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
dump.close();
}
|
|
Like Feedback org.apache.commons.compress.archivers.dump.DumpArchiveInputStream |
|
|
Sample 514. Code Sample / Example / Snippet of org.tukaani.xz.LZMA2Options | |
|
private LZMA2Options getOptions(final Object opts) throws IOException {
if (opts instanceof LZMA2Options) {
return (LZMA2Options) opts;
}
final LZMA2Options options = new LZMA2Options();
options.setDictSize(numberOptionOrDefault(opts));
return options;
}
|
|
Like Feedback org.tukaani.xz.LZMA2Options |
|
|
|
Sample 515. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream | |
|
public void readOfLength0ShouldReturn0() throws Exception {
final byte[] rawData = new byte[1048576];
for (int i=0; i < rawData.length; ++i) {
rawData[i] = (byte) Math.floor(Math.random()*256);
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);
bzipOut.write(rawData);
bzipOut.flush();
bzipOut.close();
baos.flush();
baos.close();
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);
final byte[] buffer = new byte[1024];
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));
Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));
bzipIn.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream |
|
|
Sample 516. Code Sample / Example / Snippet of org.apache.commons.compress.utils.CountingOutputStream | |
|
public void output() throws Exception {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final CountingOutputStream o = new CountingOutputStream(bos);
o.write(1);
assertEquals(1, o.getBytesWritten());
o.write(new byte[] { 2, 3 });
assertEquals(3, o.getBytesWritten());
o.write(new byte[] { 2, 3, 4, 5, }, 2, 1);
assertEquals(4, o.getBytesWritten());
o.count(-1);
assertEquals(4, o.getBytesWritten());
o.count(-2);
assertEquals(2, o.getBytesWritten());
o.close();
assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bos.toByteArray());
}
|
|
Like Feedback org.apache.commons.compress.utils.CountingOutputStream |
|
|
Sample 517. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream | |
|
public void testRemainingChunkTypes() throws Exception {
final FileInputStream isSz = new FileInputStream(getFile("mixed.txt.sz"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
final FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(isSz);
IOUtils.copy(in, out);
out.close();
} finally {
isSz.close();
}
assertArrayEquals(new byte[] { '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9',
'5', '6', '7', '8', '9', 10,
'1', '2', '3', '4',
'1', '2', '3', '4',
}, out.toByteArray());
}
|
|
Like Feedback org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream |
|
|
Sample 518. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream | |
|
public void availableShouldReturnNonZero() throws IOException {
final File input = AbstractTestCase.getFile("bla.tar.deflatez");
final InputStream is = new FileInputStream(input);
try {
final DeflateCompressorInputStream in =
new DeflateCompressorInputStream(is);
Assert.assertTrue(in.available() > 0);
in.close();
} finally {
is.close();
}
}
|
|
Like Feedback org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream |
|
|
Sample 519. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream | |
|
public void canReadASingleByteFlushAndFinish() throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final DeflateCompressorOutputStream cos = new DeflateCompressorOutputStream(bos);
cos.write(99);
cos.flush();
cos.finish();
Assert.assertTrue(bos.toByteArray().length > 0);
cos.close();
}
|
|
Like Feedback org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream |
|
|
|
Sample 520. GunZip file using Apache Commons
| |
|
public void testGzipCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.gz");
final OutputStream out = new FileOutputStream(output);
try {
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
try {
IOUtils.copy(new FileInputStream(input), cos);
} finally {
cos.close();
}
} finally {
out.close();
}
}
|
|
Like Feedback Zip file using Apache Commons Compress file using Apache Commons GunZip file using Apache Commons Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorOutputStream IOUtils.copy |
|
|
Sample 521. Maven - SCM ( Source Code Management ) config in POM file | |
|
<scm>
<connection></connection>
<developerConnection></developerConnection>
<url></url>
</scm>
|
|
Like Feedback maven pom file maven scm configuration |
|
|
Sample 522. Write CSV values to a file using au.com.bytecode.opencsv.CSVWriter | |
|
String[] stringArray1 = new String[5];
String[] stringArray2 = new String[5];
String[] stringArray3 = new String[5];
List listOfStringArrays = new ArrayList();
listOfStringArrays.add(stringArray1);
listOfStringArrays.add(stringArray2);
listOfStringArrays.add(stringArray3);
File file = new File("BuggyBread.txt");
CSVWriter csvWriter = null;
try {
csvWriter = new CSVWriter(new FileWriter(file),CSVWriter.DEFAULT_SEPARATOR);
} catch (Exception ex){
}
csvWriter.writeAll(listOfStringArrays);
|
|
Like Feedback array of Strings csv writer |
|
|
Sample 523. Write a program / method to print first letter of words in a string. | |
|
public void printFirstLetterOfWords(String str){
String[] splittedStringArray = str.split(" ");
for(String word:splittedStringArray){
System.out.println(word.charAt(0));
}
}
|
|
Like Feedback Code Coding String |
|
|
Sample 524. Write a Program to swap 2 variables ( using 3rd variable ) | |
|
int x = 1;
int y = 2;
int z = x;
x = y;
y = z;
System.out.println("x="+x);
System.out.println("y="+y);
|
|
Like Feedback swap 2 variables code coding |
|
|
|
Sample 525. Write a Program to read a file and then count number of words | |
|
public class CountwordsinFile {
public static void main(String[] args) throws IOException{
String line = null;
File file = new File("C:Hello.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int countWords = 0;
do {
line = bufferedReader.readLine();
countWords += line.split(" ").length;
} while(line != null);
}
}
|
|
Like Feedback file handling count number of words code coding file handling |
|
|
Sample 526. Code to get Module name for the class | |
|
Module module = Test.class.getModule();
System.out.println(module.getName());
|
|
Like Feedback java 9 java 9 module |
|
|
Sample 527. Code to get all packages of a Module | |
|
public class Test {
public static void main(String[] args) {
Module module = Test.class.getModule();
System.out.println(module.getPackages());
}
}
|
|
Like Feedback java 9 java 9 module |
|
|
Sample 528. Code to get Module name for List class | |
|
Module module = java.util.List.class.getModule();
System.out.println(module.getName()); // prints java.base
|
|
Like Feedback java 9 java 9 module |
|
|
Sample 529. Code to print all packages of a module | |
|
Module module = java.util.List.class.getModule();
System.out.println(module.getPackages());
|
|
Like Feedback java 9 java 9 modules |
|
|
|
Sample 530. Code to get exports of a particular Module | |
|
Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
System.out.println(moduleDescriptor.exports());
|
|
Like Feedback java 9 java 9 modules get exports for a module |
|
|
Sample 531. Code to get ModuleDescriptor from a particular Module | |
|
Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
|
|
Like Feedback java 9 java 9 modules get ModuleDescriptor for a module |
|
|
Sample 532. Code to get main class in a particular module | |
|
Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
System.out.println(moduleDescriptor.mainClass());
|
|
Like Feedback java 9 java 9 modules get main class for a module get main class for a module in java 9 java module |
|
|
Sample 533. Code Sample for
jdk.jshell.JShell;
jdk.jshell.MethodSnippet;
jdk.jshell.Snippet; | |
|
JShell.Builder builder =
JShell.builder()
.in(System.in)
.out(System.out)
.err(System.out);
JShell jshell = builder.build();
System.out.println(jshell.snippets()
.filter(sn -> sn.kind() == Snippet.Kind.METHOD)
.map(sn -> (MethodSnippet) sn).findFirst().get().signature());
|
|
Like Feedback java 9 java 9 Jshell Jshell |
|
|