gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.observables;
import java.util.Comparator;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Functions;
import rx.math.operators.OperatorMinMax;
import rx.math.operators.OperatorSum;
import rx.math.operators.OperatorAverageDouble;
import rx.math.operators.OperatorAverageFloat;
import rx.math.operators.OperatorAverageInteger;
import rx.math.operators.OperatorAverageLong;
public class MathObservable<T> {
private final Observable<T> o;
private MathObservable(Observable<T> o) {
this.o = o;
}
public static <T> MathObservable<T> from(Observable<T> o) {
return new MathObservable<T>(o);
}
/**
* Returns an Observable that emits the average of the Doubles emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.png" alt="">
*
* @param source
* source Observable to compute the average of
* @return an Observable that emits a single item: the average of all the Doubles emitted by the source
* Observable
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageDouble()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final static Observable<Double> averageDouble(Observable<Double> source) {
return source.lift(new OperatorAverageDouble<Double>(Functions.<Double>identity()));
}
/**
* Returns an Observable that emits the average of the Floats emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.png" alt="">
*
* @param source
* source Observable to compute the average of
* @return an Observable that emits a single item: the average of all the Floats emitted by the source
* Observable
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageFloat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final static Observable<Float> averageFloat(Observable<Float> source) {
return source.lift(new OperatorAverageFloat<Float>(Functions.<Float>identity()));
}
/**
* Returns an Observable that emits the average of the Integers emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.png" alt="">
*
* @param source
* source Observable to compute the average of
* @return an Observable that emits a single item: the average of all the Integers emitted by the source
* Observable
* @throws IllegalArgumentException
* if the source Observable emits no items
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageInteger()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final static Observable<Integer> averageInteger(Observable<Integer> source) {
return source.lift(new OperatorAverageInteger<Integer>(Functions.<Integer>identity()));
}
/**
* Returns an Observable that emits the average of the Longs emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.png" alt="">
*
* @param source
* source Observable to compute the average of
* @return an Observable that emits a single item: the average of all the Longs emitted by the source
* Observable
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageLong()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final static Observable<Long> averageLong(Observable<Long> source) {
return source.lift(new OperatorAverageLong<Long>(Functions.<Long>identity()));
}
/**
* Returns an Observable that emits the single item emitted by the source Observable with the maximum
* numeric value. If there is more than one item with the same maximum value, it emits the last-emitted of
* these.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/max.png" alt="">
*
* @param source
* an Observable to scan for the maximum emitted item
* @return an Observable that emits this maximum item
* @throws IllegalArgumentException
* if the source is empty
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-max">RxJava Wiki: max()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211837.aspx">MSDN: Observable.Max</a>
*/
public final static <T extends Comparable<? super T>> Observable<T> max(Observable<T> source) {
return OperatorMinMax.max(source);
}
/**
* Returns an Observable that emits the single numerically minimum item emitted by the source Observable.
* If there is more than one such item, it returns the last-emitted one.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/min.png" alt="">
*
* @param source
* an Observable to determine the minimum item of
* @return an Observable that emits the minimum item emitted by the source Observable
* @throws IllegalArgumentException
* if the source is empty
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229715.aspx">MSDN: Observable.Min</a>
*/
public final static <T extends Comparable<? super T>> Observable<T> min(Observable<T> source) {
return OperatorMinMax.min(source);
}
/**
* Returns an Observable that emits the sum of all the Doubles emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.png" alt="">
*
* @param source
* the source Observable to compute the sum of
* @return an Observable that emits a single item: the sum of all the Doubles emitted by the source
* Observable
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumDouble()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final static Observable<Double> sumDouble(Observable<Double> source) {
return OperatorSum.sumDoubles(source);
}
/**
* Returns an Observable that emits the sum of all the Floats emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.png" alt="">
*
* @param source
* the source Observable to compute the sum of
* @return an Observable that emits a single item: the sum of all the Floats emitted by the source
* Observable
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumFloat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final static Observable<Float> sumFloat(Observable<Float> source) {
return OperatorSum.sumFloats(source);
}
/**
* Returns an Observable that emits the sum of all the Integers emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.png" alt="">
*
* @param source
* source Observable to compute the sum of
* @return an Observable that emits a single item: the sum of all the Integers emitted by the source
* Observable
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumInteger()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final static Observable<Integer> sumInteger(Observable<Integer> source) {
return OperatorSum.sumIntegers(source);
}
/**
* Returns an Observable that emits the sum of all the Longs emitted by the source Observable.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.png" alt="">
*
* @param source
* source Observable to compute the sum of
* @return an Observable that emits a single item: the sum of all the Longs emitted by the
* source Observable
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumLong()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final static Observable<Long> sumLong(Observable<Long> source) {
return OperatorSum.sumLongs(source);
}
/**
* Returns an Observable that transforms items emitted by the source Observable into Doubles by using a
* function you provide and then emits the Double average of the complete sequence of transformed values.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.f.png" alt="">
*
* @param valueExtractor
* the function to transform an item emitted by the source Observable into a Double
* @return an Observable that emits a single item: the Double average of the complete sequence of items
* emitted by the source Observable when transformed into Doubles by the specified function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageDouble()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final Observable<Double> averageDouble(Func1<? super T, Double> valueExtractor) {
return o.lift(new OperatorAverageDouble<T>(valueExtractor));
}
/**
* Returns an Observable that transforms items emitted by the source Observable into Floats by using a
* function you provide and then emits the Float average of the complete sequence of transformed values.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.f.png" alt="">
*
* @param valueExtractor
* the function to transform an item emitted by the source Observable into a Float
* @return an Observable that emits a single item: the Float average of the complete sequence of items
* emitted by the source Observable when transformed into Floats by the specified function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageFloat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final Observable<Float> averageFloat(Func1<? super T, Float> valueExtractor) {
return o.lift(new OperatorAverageFloat<T>(valueExtractor));
}
/**
* Returns an Observable that transforms items emitted by the source Observable into Integers by using a
* function you provide and then emits the Integer average of the complete sequence of transformed values.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.f.png" alt="">
*
* @param valueExtractor
* the function to transform an item emitted by the source Observable into an Integer
* @return an Observable that emits a single item: the Integer average of the complete sequence of items
* emitted by the source Observable when transformed into Integers by the specified function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageInteger()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final Observable<Integer> averageInteger(Func1<? super T, Integer> valueExtractor) {
return o.lift(new OperatorAverageInteger<T>(valueExtractor));
}
/**
* Returns an Observable that transforms items emitted by the source Observable into Longs by using a
* function you provide and then emits the Long average of the complete sequence of transformed values.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/average.f.png" alt="">
*
* @param valueExtractor
* the function to transform an item emitted by the source Observable into a Long
* @return an Observable that emits a single item: the Long average of the complete sequence of items
* emitted by the source Observable when transformed into Longs by the specified function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-averageinteger-averagelong-averagefloat-and-averagedouble">RxJava Wiki: averageLong()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.average.aspx">MSDN: Observable.Average</a>
*/
public final Observable<Long> averageLong(Func1<? super T, Long> valueExtractor) {
return o.lift(new OperatorAverageLong<T>(valueExtractor));
}
/**
* Returns an Observable that emits the maximum item emitted by the source Observable, according to the
* specified comparator. If there is more than one item with the same maximum value, it emits the
* last-emitted of these.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/max.png" alt="">
*
* @param comparator
* the comparer used to compare items
* @return an Observable that emits the maximum item emitted by the source Observable, according to the
* specified comparator
* @throws IllegalArgumentException
* if the source is empty
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-max">RxJava Wiki: max()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh211635.aspx">MSDN: Observable.Max</a>
*/
public final Observable<T> max(Comparator<? super T> comparator) {
return OperatorMinMax.max(o, comparator);
}
/**
* Returns an Observable that emits the minimum item emitted by the source Observable, according to a
* specified comparator. If there is more than one such item, it returns the last-emitted one.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/min.png" alt="">
*
* @param comparator
* the comparer used to compare elements
* @return an Observable that emits the minimum item emitted by the source Observable according to the
* specified comparator
* @throws IllegalArgumentException
* if the source is empty
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-min">RxJava Wiki: min()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/hh229095.aspx">MSDN: Observable.Min</a>
*/
public final Observable<T> min(Comparator<? super T> comparator) {
return OperatorMinMax.min(o, comparator);
}
/**
* Returns an Observable that extracts a Double from each of the items emitted by the source Observable via
* a function you specify, and then emits the sum of these Doubles.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.f.png" alt="">
*
* @param valueExtractor
* the function to extract a Double from each item emitted by the source Observable
* @return an Observable that emits the Double sum of the Double values corresponding to the items emitted
* by the source Observable as transformed by the provided function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumDouble()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final Observable<Double> sumDouble(Func1<? super T, Double> valueExtractor) {
return OperatorSum.sumAtLeastOneDoubles(o.map(valueExtractor));
}
/**
* Returns an Observable that extracts a Float from each of the items emitted by the source Observable via
* a function you specify, and then emits the sum of these Floats.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.f.png" alt="">
*
* @param valueExtractor
* the function to extract a Float from each item emitted by the source Observable
* @return an Observable that emits the Float sum of the Float values corresponding to the items emitted by
* the source Observable as transformed by the provided function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumFloat()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final Observable<Float> sumFloat(Func1<? super T, Float> valueExtractor) {
return OperatorSum.sumAtLeastOneFloats(o.map(valueExtractor));
}
/**
* Returns an Observable that extracts an Integer from each of the items emitted by the source Observable
* via a function you specify, and then emits the sum of these Integers.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.f.png" alt="">
*
* @param valueExtractor
* the function to extract an Integer from each item emitted by the source Observable
* @return an Observable that emits the Integer sum of the Integer values corresponding to the items emitted
* by the source Observable as transformed by the provided function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumInteger()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final Observable<Integer> sumInteger(Func1<? super T, Integer> valueExtractor) {
return OperatorSum.sumAtLeastOneIntegers(o.map(valueExtractor));
}
/**
* Returns an Observable that extracts a Long from each of the items emitted by the source Observable via a
* function you specify, and then emits the sum of these Longs.
* <p>
* <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sum.f.png" alt="">
*
* @param valueExtractor
* the function to extract a Long from each item emitted by the source Observable
* @return an Observable that emits the Long sum of the Long values corresponding to the items emitted by
* the source Observable as transformed by the provided function
* @see <a href="https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators#wiki-suminteger-sumlong-sumfloat-and-sumdouble">RxJava Wiki: sumLong()</a>
* @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.sum.aspx">MSDN: Observable.Sum</a>
*/
public final Observable<Long> sumLong(Func1<? super T, Long> valueExtractor) {
return OperatorSum.sumAtLeastOneLongs(o.map(valueExtractor));
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db;
import java.io.IOError;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.cassandra.config.*;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.NodeId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
/**
* It represents a Keyspace.
*/
public class Table
{
public static final String SYSTEM_TABLE = "system";
private static final Logger logger = LoggerFactory.getLogger(Table.class);
/**
* accesses to CFS.memtable should acquire this for thread safety.
* CFS.maybeSwitchMemtable should aquire the writeLock; see that method for the full explanation.
*
* (Enabling fairness in the RRWL is observed to decrease throughput, so we leave it off.)
*/
public static final ReentrantReadWriteLock switchLock = new ReentrantReadWriteLock();
// It is possible to call Table.open without a running daemon, so it makes sense to ensure
// proper directories here as well as in CassandraDaemon.
static
{
if (!StorageService.instance.isClientMode())
{
try
{
DatabaseDescriptor.createAllDirectories();
}
catch (IOException ex)
{
throw new IOError(ex);
}
}
}
/* Table name. */
public final String name;
/* ColumnFamilyStore per column family */
private final Map<Integer, ColumnFamilyStore> columnFamilyStores = new ConcurrentHashMap<Integer, ColumnFamilyStore>();
private final Object[] indexLocks;
private volatile AbstractReplicationStrategy replicationStrategy;
public static Table open(String table)
{
return open(table, Schema.instance);
}
public static Table open(String table, Schema schema)
{
Table tableInstance = schema.getTableInstance(table);
if (tableInstance == null)
{
// instantiate the Table. we could use putIfAbsent but it's important to making sure it is only done once
// per keyspace, so we synchronize and re-check before doing it.
synchronized (Table.class)
{
tableInstance = schema.getTableInstance(table);
if (tableInstance == null)
{
// open and store the table
tableInstance = new Table(table);
schema.storeTableInstance(tableInstance);
// table has to be constructed and in the cache before cacheRow can be called
for (ColumnFamilyStore cfs : tableInstance.getColumnFamilyStores())
cfs.initRowCache();
}
}
}
return tableInstance;
}
public static Table clear(String table) throws IOException
{
return clear(table, Schema.instance);
}
public static Table clear(String table, Schema schema) throws IOException
{
synchronized (Table.class)
{
Table t = schema.removeTableInstance(table);
if (t != null)
{
for (ColumnFamilyStore cfs : t.getColumnFamilyStores())
t.unloadCf(cfs);
}
return t;
}
}
public Collection<ColumnFamilyStore> getColumnFamilyStores()
{
return Collections.unmodifiableCollection(columnFamilyStores.values());
}
public ColumnFamilyStore getColumnFamilyStore(String cfName)
{
Integer id = Schema.instance.getId(name, cfName);
if (id == null)
throw new IllegalArgumentException(String.format("Unknown table/cf pair (%s.%s)", name, cfName));
return getColumnFamilyStore(id);
}
public ColumnFamilyStore getColumnFamilyStore(Integer id)
{
ColumnFamilyStore cfs = columnFamilyStores.get(id);
if (cfs == null)
throw new IllegalArgumentException("Unknown CF " + id);
return cfs;
}
/**
* Do a cleanup of keys that do not belong locally.
*/
public void forceCleanup(NodeId.OneShotRenewer renewer) throws IOException, ExecutionException, InterruptedException
{
if (name.equals(SYSTEM_TABLE))
throw new UnsupportedOperationException("Cleanup of the system table is neither necessary nor wise");
// Sort the column families in order of SSTable size, so cleanup of smaller CFs
// can free up space for larger ones
List<ColumnFamilyStore> sortedColumnFamilies = new ArrayList<ColumnFamilyStore>(columnFamilyStores.values());
Collections.sort(sortedColumnFamilies, new Comparator<ColumnFamilyStore>()
{
// Compare first on size and, if equal, sort by name (arbitrary & deterministic).
public int compare(ColumnFamilyStore cf1, ColumnFamilyStore cf2)
{
long diff = (cf1.getTotalDiskSpaceUsed() - cf2.getTotalDiskSpaceUsed());
if (diff > 0)
return 1;
if (diff < 0)
return -1;
return cf1.columnFamily.compareTo(cf2.columnFamily);
}
});
// Cleanup in sorted order to free up space for the larger ones
for (ColumnFamilyStore cfs : sortedColumnFamilies)
cfs.forceCleanup(renewer);
}
/**
* Take a snapshot of the entire set of column families with a given timestamp
*
* @param snapshotName the tag associated with the name of the snapshot. This value may not be null
*/
public void snapshot(String snapshotName)
{
assert snapshotName != null;
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
cfStore.snapshot(snapshotName);
}
/**
* @param clientSuppliedName may be null.
* @return the name of the snapshot
*/
public static String getTimestampedSnapshotName(String clientSuppliedName)
{
String snapshotName = Long.toString(System.currentTimeMillis());
if (clientSuppliedName != null && !clientSuppliedName.equals(""))
{
snapshotName = snapshotName + "-" + clientSuppliedName;
}
return snapshotName;
}
/**
* Check whether snapshots already exists for a given name.
*
* @param snapshotName the user supplied snapshot name
* @return true if the snapshot exists
*/
public boolean snapshotExists(String snapshotName)
{
assert snapshotName != null;
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
{
if (cfStore.snapshotExists(snapshotName))
return true;
}
return false;
}
/**
* Clear all the snapshots for a given table.
*
* @param snapshotName the user supplied snapshot name. It empty or null,
* all the snapshots will be cleaned
*/
public void clearSnapshot(String snapshotName) throws IOException
{
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
{
cfStore.clearSnapshot(snapshotName);
}
}
/**
* @return A list of open SSTableReaders
*/
public List<SSTableReader> getAllSSTables()
{
List<SSTableReader> list = new ArrayList<SSTableReader>();
for (ColumnFamilyStore cfStore : columnFamilyStores.values())
list.addAll(cfStore.getSSTables());
return list;
}
private Table(String table)
{
name = table;
KSMetaData ksm = Schema.instance.getKSMetaData(table);
assert ksm != null : "Unknown keyspace " + table;
try
{
createReplicationStrategy(ksm);
}
catch (ConfigurationException e)
{
throw new RuntimeException(e);
}
indexLocks = new Object[DatabaseDescriptor.getConcurrentWriters() * 128];
for (int i = 0; i < indexLocks.length; i++)
indexLocks[i] = new Object();
for (CFMetaData cfm : new ArrayList<CFMetaData>(Schema.instance.getTableDefinition(table).cfMetaData().values()))
{
logger.debug("Initializing {}.{}", name, cfm.cfName);
initCf(cfm.cfId, cfm.cfName);
}
}
public void createReplicationStrategy(KSMetaData ksm) throws ConfigurationException
{
if (replicationStrategy != null)
StorageService.instance.getTokenMetadata().unregister(replicationStrategy);
replicationStrategy = AbstractReplicationStrategy.createReplicationStrategy(ksm.name,
ksm.strategyClass,
StorageService.instance.getTokenMetadata(),
DatabaseDescriptor.getEndpointSnitch(),
ksm.strategyOptions);
}
// best invoked on the compaction mananger.
public void dropCf(Integer cfId) throws IOException
{
assert columnFamilyStores.containsKey(cfId);
ColumnFamilyStore cfs = columnFamilyStores.remove(cfId);
if (cfs == null)
return;
unloadCf(cfs);
}
// disassociate a cfs from this table instance.
private void unloadCf(ColumnFamilyStore cfs) throws IOException
{
try
{
cfs.forceBlockingFlush();
}
catch (ExecutionException e)
{
throw new IOException(e);
}
catch (InterruptedException e)
{
throw new IOException(e);
}
cfs.invalidate();
}
/** adds a cf to internal structures, ends up creating disk files). */
public void initCf(Integer cfId, String cfName)
{
if (columnFamilyStores.containsKey(cfId))
{
// this is the case when you reset local schema
// just reload metadata
ColumnFamilyStore cfs = columnFamilyStores.get(cfId);
assert cfs.getColumnFamilyName().equals(cfName);
try
{
cfs.metadata.reload();
cfs.reload();
}
catch (IOException e)
{
throw FBUtilities.unchecked(e);
}
}
else
{
columnFamilyStores.put(cfId, ColumnFamilyStore.createColumnFamilyStore(this, cfName));
}
}
public Row getRow(QueryFilter filter) throws IOException
{
ColumnFamilyStore cfStore = getColumnFamilyStore(filter.getColumnFamilyName());
ColumnFamily columnFamily = cfStore.getColumnFamily(filter, ArrayBackedSortedColumns.factory());
return new Row(filter.key, columnFamily);
}
public void apply(RowMutation mutation, boolean writeCommitLog) throws IOException
{
apply(mutation, writeCommitLog, true);
}
/**
* This method adds the row to the Commit Log associated with this table.
* Once this happens the data associated with the individual column families
* is also written to the column family store's memtable.
*/
public void apply(RowMutation mutation, boolean writeCommitLog, boolean updateIndexes) throws IOException
{
if (logger.isDebugEnabled())
logger.debug("applying mutation of row {}", ByteBufferUtil.bytesToHex(mutation.key()));
// write the mutation to the commitlog and memtables
switchLock.readLock().lock();
try
{
if (writeCommitLog)
CommitLog.instance.add(mutation);
DecoratedKey<?> key = StorageService.getPartitioner().decorateKey(mutation.key());
for (ColumnFamily cf : mutation.getColumnFamilies())
{
ColumnFamilyStore cfs = columnFamilyStores.get(cf.id());
if (cfs == null)
{
logger.error("Attempting to mutate non-existant column family " + cf.id());
continue;
}
SortedSet<ByteBuffer> mutatedIndexedColumns = null;
if (updateIndexes)
{
for (ByteBuffer column : cfs.indexManager.getIndexedColumns())
{
if (cf.getColumnNames().contains(column) || cf.isMarkedForDelete())
{
if (mutatedIndexedColumns == null)
mutatedIndexedColumns = new TreeSet<ByteBuffer>();
mutatedIndexedColumns.add(column);
if (logger.isDebugEnabled())
{
// can't actually use validator to print value here, because we overload value
// for deletion timestamp as well (which may not be a well-formed value for the column type)
ByteBuffer value = cf.getColumn(column) == null ? null : cf.getColumn(column).value(); // may be null on row-level deletion
logger.debug(String.format("mutating indexed column %s value %s",
cf.getComparator().getString(column),
value == null ? "null" : ByteBufferUtil.bytesToHex(value)));
}
}
}
}
// Sharding the lock is insufficient to avoid contention when there is a "hot" row, e.g., for
// hint writes when a node is down (keyed by target IP). So it is worth special-casing the
// no-index case to avoid the synchronization.
if (mutatedIndexedColumns == null)
{
cfs.apply(key, cf);
continue;
}
// else mutatedIndexedColumns != null
synchronized (indexLockFor(mutation.key()))
{
// with the raw data CF, we can just apply every update in any order and let
// read-time resolution throw out obsolete versions, thus avoiding read-before-write.
// but for indexed data we need to make sure that we're not creating index entries
// for obsolete writes.
ColumnFamily oldIndexedColumns = readCurrentIndexedColumns(key, cfs, mutatedIndexedColumns);
logger.debug("Pre-mutation index row is {}", oldIndexedColumns);
ignoreObsoleteMutations(cf, mutatedIndexedColumns, oldIndexedColumns);
cfs.apply(key, cf);
// ignore full index memtables -- we flush those when the "master" one is full
cfs.indexManager.applyIndexUpdates(mutation.key(), cf, mutatedIndexedColumns, oldIndexedColumns);
}
}
}
finally
{
switchLock.readLock().unlock();
}
}
private static void ignoreObsoleteMutations(ColumnFamily cf, SortedSet<ByteBuffer> mutatedIndexedColumns, ColumnFamily oldIndexedColumns)
{
// DO NOT modify the cf object here, it can race w/ the CL write (see https://issues.apache.org/jira/browse/CASSANDRA-2604)
if (oldIndexedColumns == null)
return;
for (Iterator<ByteBuffer> iter = mutatedIndexedColumns.iterator(); iter.hasNext(); )
{
ByteBuffer name = iter.next();
IColumn newColumn = cf.getColumn(name); // null == row delete or it wouldn't be marked Mutated
if (newColumn != null && cf.isMarkedForDelete())
{
// row is marked for delete, but column was also updated. if column is timestamped less than
// the row tombstone, treat it as if it didn't exist. Otherwise we don't care about row
// tombstone for the purpose of the index update and we can proceed as usual.
if (newColumn.timestamp() <= cf.getMarkedForDeleteAt())
{
// don't remove from the cf object; that can race w/ CommitLog write. Leaving it is harmless.
newColumn = null;
}
}
IColumn oldColumn = oldIndexedColumns.getColumn(name);
// deletions are irrelevant to the index unless we're changing state from live -> deleted, i.e.,
// just updating w/ a newer tombstone doesn't matter
boolean bothDeleted = (newColumn == null || newColumn.isMarkedForDelete())
&& (oldColumn == null || oldColumn.isMarkedForDelete());
// obsolete means either the row or the column timestamp we're applying is older than existing data
boolean obsoleteRowTombstone = newColumn == null && oldColumn != null && cf.getMarkedForDeleteAt() < oldColumn.timestamp();
boolean obsoleteColumn = newColumn != null && (newColumn.timestamp() <= oldIndexedColumns.getMarkedForDeleteAt()
|| (oldColumn != null && oldColumn.reconcile(newColumn) == oldColumn));
if (bothDeleted || obsoleteRowTombstone || obsoleteColumn)
{
if (logger.isDebugEnabled())
logger.debug("skipping index update for obsolete mutation of " + cf.getComparator().getString(name));
iter.remove();
oldIndexedColumns.remove(name);
}
}
}
private static ColumnFamily readCurrentIndexedColumns(DecoratedKey<?> key, ColumnFamilyStore cfs, SortedSet<ByteBuffer> mutatedIndexedColumns)
{
QueryFilter filter = QueryFilter.getNamesFilter(key, new QueryPath(cfs.getColumnFamilyName()), mutatedIndexedColumns);
return cfs.getColumnFamily(filter);
}
public AbstractReplicationStrategy getReplicationStrategy()
{
return replicationStrategy;
}
/**
* @param key row to index
* @param cfs ColumnFamily to index row in
* @param indexedColumns columns to index, in comparator order
*/
public static void indexRow(DecoratedKey<?> key, ColumnFamilyStore cfs, SortedSet<ByteBuffer> indexedColumns)
{
if (logger.isDebugEnabled())
logger.debug("Indexing row {} ", cfs.metadata.getKeyValidator().getString(key.key));
switchLock.readLock().lock();
try
{
synchronized (cfs.table.indexLockFor(key.key))
{
ColumnFamily cf = readCurrentIndexedColumns(key, cfs, indexedColumns);
if (cf != null)
try
{
cfs.indexManager.applyIndexUpdates(key.key, cf, cf.getColumnNames(), null);
}
catch (IOException e)
{
throw new IOError(e);
}
}
}
finally
{
switchLock.readLock().unlock();
}
}
private Object indexLockFor(ByteBuffer key)
{
return indexLocks[Math.abs(key.hashCode() % indexLocks.length)];
}
public List<Future<?>> flush() throws IOException
{
List<Future<?>> futures = new ArrayList<Future<?>>();
for (Integer cfId : columnFamilyStores.keySet())
{
Future<?> future = columnFamilyStores.get(cfId).forceFlush();
if (future != null)
futures.add(future);
}
return futures;
}
public static Iterable<Table> all()
{
Function<String, Table> transformer = new Function<String, Table>()
{
public Table apply(String tableName)
{
return Table.open(tableName);
}
};
return Iterables.transform(Schema.instance.getTables(), transformer);
}
@Override
public String toString()
{
return getClass().getSimpleName() + "(name='" + name + "')";
}
}
| |
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.netty.handler.codec.http2;
import java.util.NoSuchElementException;
/**
* Settings for one endpoint in an HTTP/2 connection. Each of the values are optional as defined in
* the spec for the SETTINGS frame.
*/
public class Http2Settings {
private static final byte MAX_HEADER_TABLE_SIZE_MASK = 0x1;
private static final byte PUSH_ENABLED_MASK = 0x2;
private static final byte MAX_CONCURRENT_STREAMS_MASK = 0x4;
private static final byte INITIAL_WINDOW_SIZE_MASK = 0x8;
private static final byte ALLOW_COMPRESSION_MASK = 0x10;
private byte enabled;
private int maxHeaderTableSize;
private boolean pushEnabled;
private int maxConcurrentStreams;
private int initialWindowSize;
private boolean allowCompressedData;
/**
* Indicates whether or not the headerTableSize value is available.
*/
public boolean hasMaxHeaderTableSize() {
return isEnabled(MAX_HEADER_TABLE_SIZE_MASK);
}
/**
* Gets the maximum HPACK header table size or throws {@link NoSuchElementException} if the
* value has not been set.
*/
public int maxHeaderTableSize() {
if (!hasMaxHeaderTableSize()) {
throw new NoSuchElementException("headerTableSize");
}
return maxHeaderTableSize;
}
/**
* Sets the maximum HPACK header table size to the specified value.
*/
public Http2Settings maxHeaderTableSize(int headerTableSize) {
if (headerTableSize < 0) {
throw new IllegalArgumentException("headerTableSize must be >= 0");
}
enable(MAX_HEADER_TABLE_SIZE_MASK);
maxHeaderTableSize = headerTableSize;
return this;
}
/**
* Indicates whether or not the pushEnabled value is available.
*/
public boolean hasPushEnabled() {
return isEnabled(PUSH_ENABLED_MASK);
}
/**
* Gets whether or not server push is enabled or throws {@link NoSuchElementException} if the
* value has not been set.
*/
public boolean pushEnabled() {
if (!hasPushEnabled()) {
throw new NoSuchElementException("pushEnabled");
}
return pushEnabled;
}
/**
* Sets whether or not server push is enabled.
*/
public Http2Settings pushEnabled(boolean pushEnabled) {
enable(PUSH_ENABLED_MASK);
this.pushEnabled = pushEnabled;
return this;
}
/**
* Indicates whether or not the maxConcurrentStreams value is available.
*/
public boolean hasMaxConcurrentStreams() {
return isEnabled(MAX_CONCURRENT_STREAMS_MASK);
}
/**
* Gets the maximum allowed concurrent streams or throws {@link NoSuchElementException} if the
* value has not been set.
*/
public int maxConcurrentStreams() {
if (!hasMaxConcurrentStreams()) {
throw new NoSuchElementException("maxConcurrentStreams");
}
return maxConcurrentStreams;
}
/**
* Sets the maximum allowed concurrent streams to the specified value.
*/
public Http2Settings maxConcurrentStreams(int maxConcurrentStreams) {
if (maxConcurrentStreams < 0) {
throw new IllegalArgumentException("maxConcurrentStreams must be >= 0");
}
enable(MAX_CONCURRENT_STREAMS_MASK);
this.maxConcurrentStreams = maxConcurrentStreams;
return this;
}
/**
* Indicates whether or not the initialWindowSize value is available.
*/
public boolean hasInitialWindowSize() {
return isEnabled(INITIAL_WINDOW_SIZE_MASK);
}
/**
* Gets the initial flow control window size or throws {@link NoSuchElementException} if the
* value has not been set.
*/
public int initialWindowSize() {
if (!hasInitialWindowSize()) {
throw new NoSuchElementException("initialWindowSize");
}
return initialWindowSize;
}
/**
* Sets the initial flow control window size to the specified value.
*/
public Http2Settings initialWindowSize(int initialWindowSize) {
if (initialWindowSize < 0) {
throw new IllegalArgumentException("initialWindowSize must be >= 0");
}
enable(INITIAL_WINDOW_SIZE_MASK);
this.initialWindowSize = initialWindowSize;
return this;
}
/**
* Indicates whether or not the allowCompressedData value is available.
*/
public boolean hasAllowCompressedData() {
return isEnabled(ALLOW_COMPRESSION_MASK);
}
/**
* Gets whether the endpoint allows compressed data or throws {@link NoSuchElementException} if
* the value has not been set.
*/
public boolean allowCompressedData() {
if (!hasAllowCompressedData()) {
throw new NoSuchElementException("allowCompressedData");
}
return allowCompressedData;
}
/**
* Sets whether or not the endpoing allows compressed data.
*/
public Http2Settings allowCompressedData(boolean allowCompressedData) {
enable(ALLOW_COMPRESSION_MASK);
this.allowCompressedData = allowCompressedData;
return this;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (allowCompressedData ? 1231 : 1237);
result = prime * result + enabled;
result = prime * result + maxHeaderTableSize;
result = prime * result + initialWindowSize;
result = prime * result + maxConcurrentStreams;
result = prime * result + (pushEnabled ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Http2Settings other = (Http2Settings) obj;
if (allowCompressedData != other.allowCompressedData) {
return false;
}
if (enabled != other.enabled) {
return false;
}
if (maxHeaderTableSize != other.maxHeaderTableSize) {
return false;
}
if (initialWindowSize != other.initialWindowSize) {
return false;
}
if (maxConcurrentStreams != other.maxConcurrentStreams) {
return false;
}
if (pushEnabled != other.pushEnabled) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Http2Settings [");
if (hasMaxHeaderTableSize()) {
builder.append("maxHeaderTableSize=").append(maxHeaderTableSize).append(",");
}
if (hasPushEnabled()) {
builder.append("pushEnabled=").append(pushEnabled).append(",");
}
if (hasMaxConcurrentStreams()) {
builder.append("maxConcurrentStreams=").append(maxConcurrentStreams).append(",");
}
if (hasInitialWindowSize()) {
builder.append("initialWindowSize=").append(initialWindowSize).append(",");
}
if (hasAllowCompressedData()) {
builder.append("allowCompressedData=").append(allowCompressedData).append(",");
}
builder.append("]");
return builder.toString();
}
private void enable(int mask) {
enabled |= mask;
}
private boolean isEnabled(int mask) {
return (enabled & mask) > 0;
}
}
| |
package yil712.UI;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import yil712.control.RetireAcctControl;
import yil712.control.SymbolControl;
public class SellInvestmentUIR extends JFrame {
private static final long serialVersionUID = -6225573111793696789L;
private JPanel contentPane;
private JButton confirm;
private JButton cancel;
private JLabel lblCurrentBalance;
private JLabel lblTotalAmount_1;
private JTextField symbolFiled;
private JTextField price;
private JTextField numHeld;
private JTextField numToSell;
private JTextField toSell;
private JTextField crtBalance;
private JButton btnCalculate;
private static String symbolStr, accountID;
private int type, number;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SellInvestmentUIR frame = SellInvestmentUIR.getInstance("AAN", "A000006");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private static SellInvestmentUIR singleton = null; // singleton
public static SellInvestmentUIR getInstance(String symbol, String accountNum) {
if (singleton == null) {
singleton = new SellInvestmentUIR(symbol, accountNum);
} else {
symbolStr = symbol;
accountID = accountNum;
}
singleton.upateInfo();
return singleton;
}
public void upateInfo() {
setTitle("Sell - Account Number: " + accountID);
this.symbolFiled.setText(symbolStr);
this.symbolFiled.setEditable(false);
SymbolControl control1 = new SymbolControl();
type = control1.getInvestType(symbolStr);
double priceVal = control1.getCrtPrice(symbolStr, type);
this.price.setText(""+priceVal);
this.price.setEditable(false);
RetireAcctControl control2 = new RetireAcctControl();
int heldNum = control2.getCurrentNumOfShares(accountID, symbolStr);
this.numHeld.setText("" + heldNum);
this.numHeld.setEditable(false);
this.numToSell.setText("");
this.toSell.setText("");
this.toSell.setEditable(false);
RetireAcctControl control3 = new RetireAcctControl();
double bal = control3.getRetireAccountBalance(accountID);
crtBalance.setText("" + bal);
crtBalance.setEditable(false);
}
/**
* Create the frame.
*/
private SellInvestmentUIR(String symbol, String accountNum) {
symbolStr = symbol;
accountID = accountNum;
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(540,400);
this.setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JLabel lblOpenALoan = new JLabel("Sell stocks/mutual_funds");
lblOpenALoan.setBounds(101, 27, 333, 39);
lblOpenALoan.setFont(new Font("Dialog", Font.PLAIN, 30));
JLabel lblLoanId = new JLabel("- Symbol:");
lblLoanId.setBounds(82, 102, 60, 17);
lblLoanId.setFont(new Font("Tahoma", Font.PLAIN, 14));
JLabel priceLabel = new JLabel("- Latest price:");
priceLabel.setBounds(82, 128, 96, 17);
priceLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
JLabel lblAnnualRate = new JLabel("- Number of Shares (NoS) held:");
lblAnnualRate.setBounds(82, 151, 202, 17);
lblAnnualRate.setFont(new Font("Tahoma", Font.PLAIN, 14));
JLabel lblThreshold = new JLabel("- NoS to sell:");
lblThreshold.setBounds(82, 174, 96, 17);
lblThreshold.setFont(new Font("Tahoma", Font.PLAIN, 14));
confirm = new JButton("Confirm");
confirm.setBounds(152, 292, 82, 23);
cancel = new JButton("Cancel");
cancel.setBounds(329, 292, 75, 23);
lblCurrentBalance = new JLabel("- Current balance:");
lblCurrentBalance.setBounds(82, 220, 118, 17);
lblCurrentBalance.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblTotalAmount_1 = new JLabel("- Total amount:");
lblTotalAmount_1.setBounds(82, 197, 96, 17);
lblTotalAmount_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
symbolFiled = new JTextField();
symbolFiled.setBounds(152, 102, 206, 20);
symbolFiled.setColumns(10);
contentPane.setLayout(null);
contentPane.add(lblCurrentBalance);
contentPane.add(lblTotalAmount_1);
contentPane.add(symbolFiled);
contentPane.add(lblAnnualRate);
contentPane.add(priceLabel);
contentPane.add(lblThreshold);
contentPane.add(confirm);
contentPane.add(cancel);
contentPane.add(lblLoanId);
contentPane.add(lblOpenALoan);
price = new JTextField();
price.setColumns(10);
price.setBounds(178, 128, 206, 20);
contentPane.add(price);
numHeld = new JTextField();
numHeld.setColumns(10);
numHeld.setBounds(283, 151, 206, 20);
contentPane.add(numHeld);
numToSell = new JTextField();
numToSell.setColumns(10);
numToSell.setBounds(178, 174, 206, 20);
contentPane.add(numToSell);
toSell = new JTextField();
toSell.setColumns(10);
toSell.setBounds(188, 197, 206, 20);
contentPane.add(toSell);
crtBalance = new JTextField();
crtBalance.setColumns(10);
crtBalance.setBounds(198, 220, 206, 20);
contentPane.add(crtBalance);
btnCalculate = new JButton("Calculate");
btnCalculate.setBounds(400, 173, 89, 23);
contentPane.add(btnCalculate);
calculateEvent();
confirmEvent();
cancelEvent();
}
public void calculateEvent() {
btnCalculate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
number = Integer.parseInt(numToSell.getText());
if (number > 0) {
double crtPrice = Double.parseDouble(price.getText());
double amount = crtPrice * number;
toSell.setText("" + amount);
} else {
JOptionPane.showMessageDialog(null, "Please input a positive number.", "Warning", JOptionPane.INFORMATION_MESSAGE);
}
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(null, "Please input only numbers in this feild.", "Warning", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
public void confirmEvent() {
confirm.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
int heldNum = Integer.parseInt(numHeld.getText());
if (number <= heldNum) {
RetireAcctControl control = new RetireAcctControl();
if (control.sellStocksOrFunds(accountID, symbolStr, type, number)) {
JOptionPane.showMessageDialog(null, "Successfully sold " + number + " of " + symbolStr + ".", "Warning", JOptionPane.INFORMATION_MESSAGE);
singleton.dispose();
}
} else {
JOptionPane.showMessageDialog(null, "Please ensure the number of shares to sell is less than the held number.", "Warning", JOptionPane.INFORMATION_MESSAGE);
}
} catch (NumberFormatException e1) {
JOptionPane.showMessageDialog(null, "Please calculate the amount to pay.", "Warning", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
public void cancelEvent() {
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
singleton.dispose();
}
});
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Danial Goodwin (source: https://github.com/danialgoodwin/android-global-overlay) (created 2015-03-13)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.danialgoodwin.globaloverlay;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
/** All the boilerplate for setting up a nice floating overlay that stays above all apps and
* Activities. Overlays can be removed by the user dragging it down to the remove view at the
* bottom, or by stopping the service.
*
* Currently, only supports one overlay view. And, when the user removes the view,
* the service will be destroyed.
*
* Note: Currently, the `mOnLongClickListener` is not implemented. It might be in the future
* though. Feel free to send a pull request. */
public abstract class GlobalOverlayService extends Service {
private static final String LOGCAT_TAG = "GlobalOverlayService";
private static void log(String message) {
Log.d(LOGCAT_TAG, message);
}
private WindowManager mWindowManager;
private View mRemoveView;
private View mOverlayView;
@SuppressWarnings("FieldCanBeLocal")
private View.OnTouchListener mOnTouchListener;
private View.OnClickListener mOnClickListener;
private View.OnLongClickListener mOnLongClickListener;
private OnRemoveOverlayListener mOnRemoveOverlayListener;
private WindowManager.LayoutParams mOverlayLayoutParams;
@Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mRemoveView = onGetRemoveView();
setupRemoveView(mRemoveView);
}
@Override
public void onDestroy() {
// Views are automatically removed once service is through.
// removeOverlayView(mOverlayView);
// if (mRemoveView != null) { mWindowManager.removeView(mRemoveView); }
super.onDestroy();
}
// Override this to bind.
@Override
public IBinder onBind(Intent intent) {
return null;
}
/** Return the view to use for the "remove view" that appears at the bottom of the screen.
* Override this to change the image for the remove view. Returning null will throw a
* NullPointerException in a subsequent method.*/
@SuppressLint("InflateParams")
protected View onGetRemoveView() {
return LayoutInflater.from(this).inflate(R.layout.overlay_remove_view, null);
}
/** Sets this view to the bottom of the screen and only visible when user is dragging an
* overlay view. This modifies the instance passed in. */
private void setupRemoveView(View removeView) {
removeView.setVisibility(View.GONE);
mWindowManager.addView(removeView, newWindowManagerLayoutParamsForRemoveView());
}
/** Add a global floating view.
*
* @param view the view to overlay across all apps and activities
* @param onClickListener get notified of a click, set null to ignore
*/
public final void addOverlayView(View view, View.OnClickListener onClickListener) {
addOverlayView(view, onClickListener, null, null);
}
/** Add a global floating view.
*
* @param view the view to overlay across all apps and activities
* @param onClickListener get notified of a click, set null to ignore
* @param onLongClickListener not implemented yet, just set as null
* @param onRemoveOverlayListener get notified when overlay is removed (not from a destroyed service though)
*/
public final void addOverlayView(View view, View.OnClickListener onClickListener,
View.OnLongClickListener onLongClickListener, OnRemoveOverlayListener onRemoveOverlayListener) {
mOverlayView = view;
mOnClickListener = onClickListener;
mOnLongClickListener = onLongClickListener;
mOnRemoveOverlayListener = onRemoveOverlayListener;
mOverlayLayoutParams = newWindowManagerLayoutParams();
mOnTouchListener = newSimpleOnTouchListener();
mOverlayView.setOnTouchListener(mOnTouchListener);
mWindowManager.addView(mOverlayView, newWindowManagerLayoutParams());
}
/** Manually remove an overlay without destroying the service. */
public final void removeOverlayView(View view) {
removeOverlayView(view, false);
}
/** Remove a overlay without destroying the service. */
public final void removeOverlayView(View view, boolean isRemovedByUser) {
if (view != null) {
if (mOnRemoveOverlayListener != null) {
mOnRemoveOverlayListener.onRemoveOverlay(view, isRemovedByUser);
}
mWindowManager.removeView(view);
}
}
/** Provides the drag ability for the overlay view. This touch listener
* allows user to drag the view anywhere on screen. */
private View.OnTouchListener newSimpleOnTouchListener() {
return new View.OnTouchListener() {
// private long timeStart; // Maybe use in the future, with ViewConfiguration's getLongClickTime or whatever it is called.
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
private int[] overlayViewLocation = {0,0};
private boolean isOverRemoveView;
private int[] removeViewLocation = {0,0};
private final int touchSlop = ViewConfiguration.get(getBaseContext()).getScaledTouchSlop();
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// timeStart = System.currentTimeMillis();
initialX = mOverlayLayoutParams.x;
initialY = mOverlayLayoutParams.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
mRemoveView.setVisibility(View.VISIBLE);
return true;
case MotionEvent.ACTION_MOVE:
mOverlayLayoutParams.x = initialX + (int) (event.getRawX() - initialTouchX);
mOverlayLayoutParams.y = initialY + (int) (event.getRawY() - initialTouchY);
mWindowManager.updateViewLayout(mOverlayView, mOverlayLayoutParams);
mOverlayView.getLocationOnScreen(overlayViewLocation);
mRemoveView.getLocationOnScreen(removeViewLocation);
isOverRemoveView = isPointInArea(overlayViewLocation[0], overlayViewLocation[1],
removeViewLocation[0], removeViewLocation[1], mRemoveView.getWidth());
if (isOverRemoveView) {
// TODO: Maybe, make it look like the overlay view is perfectly on the remove view.
}
return true;
case MotionEvent.ACTION_UP:
if (isOverRemoveView) {
removeOverlayView(v, true);
// Not sure if setting to null is the best way to handle this. Though,
// currently it's needed to prevent a `IllegalArgumentException ... not attached to window manager`
// v = null;
stopSelf();
} else {
if (mOnClickListener != null && Math.abs(initialTouchY - event.getRawY()) <= touchSlop) {
mOnClickListener.onClick(v);
}
}
mRemoveView.setVisibility(View.GONE);
return true;
case MotionEvent.ACTION_CANCEL:
mRemoveView.setVisibility(View.GONE);
return true;
}
return false;
}
};
}
/** Return true if point (x1,y1) is in the square defined by (x2,y2) with radius, otherwise false. */
private boolean isPointInArea(int x1, int y1, int x2, int y2, int radius) {
// log("isPointInArea(). x1=" + x1 + ",y1=" + y1);
// log("isPointInArea(). x2=" + x2 + ",y2=" + y2 + ",radius=" + radius);
return x1 >= x2 - radius && x1 <= x2 + radius && y1 >= y2 - radius && y1 <= y2 + radius;
}
/** Returns the default layout params for the overlay views. */
private static WindowManager.LayoutParams newWindowManagerLayoutParams() {
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
// WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.START;
return params;
}
private static WindowManager.LayoutParams newWindowManagerLayoutParamsForRemoveView() {
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
params.y = 56;
return params;
}
/** Interface definition for when an overlay view has been removed. */
public static interface OnRemoveOverlayListener {
/** This overlay has been removed.
* @param v the removed view
* @param isRemovedByUser true if user manually removed view, false if removed another way */
public void onRemoveOverlay(View v, boolean isRemovedByUser);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: grpc/file_system_master.proto
package alluxio.grpc;
/**
* Protobuf type {@code alluxio.grpc.file.StopSyncPOptions}
*/
public final class StopSyncPOptions extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:alluxio.grpc.file.StopSyncPOptions)
StopSyncPOptionsOrBuilder {
private static final long serialVersionUID = 0L;
// Use StopSyncPOptions.newBuilder() to construct.
private StopSyncPOptions(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private StopSyncPOptions() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private StopSyncPOptions(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
alluxio.grpc.FileSystemMasterCommonPOptions.Builder subBuilder = null;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
subBuilder = commonOptions_.toBuilder();
}
commonOptions_ = input.readMessage(alluxio.grpc.FileSystemMasterCommonPOptions.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(commonOptions_);
commonOptions_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000001;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return alluxio.grpc.FileSystemMasterProto.internal_static_alluxio_grpc_file_StopSyncPOptions_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return alluxio.grpc.FileSystemMasterProto.internal_static_alluxio_grpc_file_StopSyncPOptions_fieldAccessorTable
.ensureFieldAccessorsInitialized(
alluxio.grpc.StopSyncPOptions.class, alluxio.grpc.StopSyncPOptions.Builder.class);
}
private int bitField0_;
public static final int COMMONOPTIONS_FIELD_NUMBER = 1;
private alluxio.grpc.FileSystemMasterCommonPOptions commonOptions_;
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public boolean hasCommonOptions() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public alluxio.grpc.FileSystemMasterCommonPOptions getCommonOptions() {
return commonOptions_ == null ? alluxio.grpc.FileSystemMasterCommonPOptions.getDefaultInstance() : commonOptions_;
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public alluxio.grpc.FileSystemMasterCommonPOptionsOrBuilder getCommonOptionsOrBuilder() {
return commonOptions_ == null ? alluxio.grpc.FileSystemMasterCommonPOptions.getDefaultInstance() : commonOptions_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeMessage(1, getCommonOptions());
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getCommonOptions());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof alluxio.grpc.StopSyncPOptions)) {
return super.equals(obj);
}
alluxio.grpc.StopSyncPOptions other = (alluxio.grpc.StopSyncPOptions) obj;
boolean result = true;
result = result && (hasCommonOptions() == other.hasCommonOptions());
if (hasCommonOptions()) {
result = result && getCommonOptions()
.equals(other.getCommonOptions());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasCommonOptions()) {
hash = (37 * hash) + COMMONOPTIONS_FIELD_NUMBER;
hash = (53 * hash) + getCommonOptions().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static alluxio.grpc.StopSyncPOptions parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static alluxio.grpc.StopSyncPOptions parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static alluxio.grpc.StopSyncPOptions parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(alluxio.grpc.StopSyncPOptions prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code alluxio.grpc.file.StopSyncPOptions}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:alluxio.grpc.file.StopSyncPOptions)
alluxio.grpc.StopSyncPOptionsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return alluxio.grpc.FileSystemMasterProto.internal_static_alluxio_grpc_file_StopSyncPOptions_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return alluxio.grpc.FileSystemMasterProto.internal_static_alluxio_grpc_file_StopSyncPOptions_fieldAccessorTable
.ensureFieldAccessorsInitialized(
alluxio.grpc.StopSyncPOptions.class, alluxio.grpc.StopSyncPOptions.Builder.class);
}
// Construct using alluxio.grpc.StopSyncPOptions.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getCommonOptionsFieldBuilder();
}
}
public Builder clear() {
super.clear();
if (commonOptionsBuilder_ == null) {
commonOptions_ = null;
} else {
commonOptionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return alluxio.grpc.FileSystemMasterProto.internal_static_alluxio_grpc_file_StopSyncPOptions_descriptor;
}
public alluxio.grpc.StopSyncPOptions getDefaultInstanceForType() {
return alluxio.grpc.StopSyncPOptions.getDefaultInstance();
}
public alluxio.grpc.StopSyncPOptions build() {
alluxio.grpc.StopSyncPOptions result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public alluxio.grpc.StopSyncPOptions buildPartial() {
alluxio.grpc.StopSyncPOptions result = new alluxio.grpc.StopSyncPOptions(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
if (commonOptionsBuilder_ == null) {
result.commonOptions_ = commonOptions_;
} else {
result.commonOptions_ = commonOptionsBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof alluxio.grpc.StopSyncPOptions) {
return mergeFrom((alluxio.grpc.StopSyncPOptions)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(alluxio.grpc.StopSyncPOptions other) {
if (other == alluxio.grpc.StopSyncPOptions.getDefaultInstance()) return this;
if (other.hasCommonOptions()) {
mergeCommonOptions(other.getCommonOptions());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
alluxio.grpc.StopSyncPOptions parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (alluxio.grpc.StopSyncPOptions) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private alluxio.grpc.FileSystemMasterCommonPOptions commonOptions_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
alluxio.grpc.FileSystemMasterCommonPOptions, alluxio.grpc.FileSystemMasterCommonPOptions.Builder, alluxio.grpc.FileSystemMasterCommonPOptionsOrBuilder> commonOptionsBuilder_;
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public boolean hasCommonOptions() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public alluxio.grpc.FileSystemMasterCommonPOptions getCommonOptions() {
if (commonOptionsBuilder_ == null) {
return commonOptions_ == null ? alluxio.grpc.FileSystemMasterCommonPOptions.getDefaultInstance() : commonOptions_;
} else {
return commonOptionsBuilder_.getMessage();
}
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public Builder setCommonOptions(alluxio.grpc.FileSystemMasterCommonPOptions value) {
if (commonOptionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
commonOptions_ = value;
onChanged();
} else {
commonOptionsBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public Builder setCommonOptions(
alluxio.grpc.FileSystemMasterCommonPOptions.Builder builderForValue) {
if (commonOptionsBuilder_ == null) {
commonOptions_ = builderForValue.build();
onChanged();
} else {
commonOptionsBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public Builder mergeCommonOptions(alluxio.grpc.FileSystemMasterCommonPOptions value) {
if (commonOptionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001) &&
commonOptions_ != null &&
commonOptions_ != alluxio.grpc.FileSystemMasterCommonPOptions.getDefaultInstance()) {
commonOptions_ =
alluxio.grpc.FileSystemMasterCommonPOptions.newBuilder(commonOptions_).mergeFrom(value).buildPartial();
} else {
commonOptions_ = value;
}
onChanged();
} else {
commonOptionsBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public Builder clearCommonOptions() {
if (commonOptionsBuilder_ == null) {
commonOptions_ = null;
onChanged();
} else {
commonOptionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public alluxio.grpc.FileSystemMasterCommonPOptions.Builder getCommonOptionsBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getCommonOptionsFieldBuilder().getBuilder();
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
public alluxio.grpc.FileSystemMasterCommonPOptionsOrBuilder getCommonOptionsOrBuilder() {
if (commonOptionsBuilder_ != null) {
return commonOptionsBuilder_.getMessageOrBuilder();
} else {
return commonOptions_ == null ?
alluxio.grpc.FileSystemMasterCommonPOptions.getDefaultInstance() : commonOptions_;
}
}
/**
* <code>optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
alluxio.grpc.FileSystemMasterCommonPOptions, alluxio.grpc.FileSystemMasterCommonPOptions.Builder, alluxio.grpc.FileSystemMasterCommonPOptionsOrBuilder>
getCommonOptionsFieldBuilder() {
if (commonOptionsBuilder_ == null) {
commonOptionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
alluxio.grpc.FileSystemMasterCommonPOptions, alluxio.grpc.FileSystemMasterCommonPOptions.Builder, alluxio.grpc.FileSystemMasterCommonPOptionsOrBuilder>(
getCommonOptions(),
getParentForChildren(),
isClean());
commonOptions_ = null;
}
return commonOptionsBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:alluxio.grpc.file.StopSyncPOptions)
}
// @@protoc_insertion_point(class_scope:alluxio.grpc.file.StopSyncPOptions)
private static final alluxio.grpc.StopSyncPOptions DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new alluxio.grpc.StopSyncPOptions();
}
public static alluxio.grpc.StopSyncPOptions getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<StopSyncPOptions>
PARSER = new com.google.protobuf.AbstractParser<StopSyncPOptions>() {
public StopSyncPOptions parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new StopSyncPOptions(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<StopSyncPOptions> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<StopSyncPOptions> getParserForType() {
return PARSER;
}
public alluxio.grpc.StopSyncPOptions getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openhubframework.openhub.core;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import java.io.StringWriter;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
import javax.xml.bind.*;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
import org.apache.camel.*;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.RouteDefinition;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.openhubframework.openhub.api.asynch.AsynchConstants;
import org.openhubframework.openhub.api.asynch.model.TraceHeader;
import org.openhubframework.openhub.api.asynch.model.TraceIdentifier;
import org.openhubframework.openhub.api.entity.ExternalSystemExtEnum;
import org.openhubframework.openhub.api.entity.Message;
import org.openhubframework.openhub.api.entity.MsgStateEnum;
import org.openhubframework.openhub.api.entity.ServiceExtEnum;
import org.openhubframework.openhub.api.route.AbstractBasicRoute;
import org.openhubframework.openhub.core.common.asynch.AsynchMessageRoute;
import org.openhubframework.openhub.core.common.asynch.TraceHeaderProcessor;
import org.openhubframework.openhub.core.common.asynch.queue.MessagePollExecutor;
import org.openhubframework.openhub.core.common.dao.MessageDao;
import org.openhubframework.openhub.test.route.ActiveRoutes;
/**
* Helper abstract parent for assisted testing of operation routes. This helper provides:
* <ul>
* <li>ability to easily convert JAXB POJO requests to XML requests, and vice-versa for responses</li>
* <li>sender method to send XML payload to async IN route (as if it's a new incoming message from WS)</li>
* <li>sender method to send XML payload to async OUT route (as if pumping persisted message from DB)</li>
* <li>resend method to resent the last sent message to async OUT route (e.g., to resend party failed messages)</li>
* <li>mock URI method for mocking URIs of unstarted routes (to mock WS uris without actually starting WS out routes)</li>
* </ul>
*/
@ActiveRoutes(classes = {AsynchMessageRoute.class})
public abstract class AbstractOperationRouteTest extends AbstractCoreDbTest {
public static final String URI_ASYNC_IN_ROUTE = "direct:testAsyncInRoute";
public static final String URI_SYNC_ROUTE = "direct:testSyncRoute";
@Autowired
protected MessageDao msgDao;
@Produce
protected ProducerTemplate producer;
protected Message lastMessage;
@Override
@After
public void printEntities() {
// override to add @After
super.printEntities();
}
/**
* @param testRequest the request JAXB POJO
* @return a valid request XML that will be used to test the route
*/
protected String getRequestXML(Object testRequest) throws Exception {
return marshalFragment(testRequest, null);
}
/**
* @param testRequest the request JAXB POJO
* @param testRequestQName the request QName (in case JAXB POJO is not annotated with {@link XmlRootElement})
* @return a valid request XML that will be used to test the route
*/
protected String getRequestXML(Object testRequest, QName testRequestQName) throws JAXBException {
return marshalFragment(testRequest, testRequestQName);
}
/**
* @return the external system that normally calls the operation route to be tested
*/
protected abstract ExternalSystemExtEnum getSourceSystem();
/**
* @return the service of the operation route under test
*/
protected abstract ServiceExtEnum getService();
/**
* @return the operation name of the operation route under test
*/
protected abstract String getOperationName();
/**
* The route ID that acts as the IN input to the asynchronous operation,
* responsible for delivering synchronous validation response to the caller,
* but not response for actually executing the asynchronous operation,
* e.g., what is returned by {@link AbstractBasicRoute#getInRouteId(ServiceExtEnum, String)}.
*
* @return the async IN route id.
*/
protected String getAsyncInRouteId() {
return AbstractBasicRoute.getInRouteId(getService(), getOperationName());
}
/**
* The route ID that acts as the OUT input to the asynchronous operation,
* responsible for actually executing the asynchronous operation,
* but not responsible for delivering synchronous response to the caller.
* The asynchronous operation success is reported via confirmation mechanism instead.
* e.g., what is returned by {@link AbstractBasicRoute#getInRouteId(ServiceExtEnum, String)}.
*
* @return the async IN route id.
*/
protected String getAsyncOutRouteId() {
return AbstractBasicRoute.getOutRouteId(getService(), getOperationName());
}
/**
* The route ID that acts as the input/output to the synchronous operation,
* e.g., what is returned by {@link AbstractBasicRoute#getRouteId(ServiceExtEnum, String)}.
*
* @return the sync route id.
*/
protected String getSyncRouteId() {
return AbstractBasicRoute.getRouteId(getService(), getOperationName());
}
@Before
public void connectProducers() throws Exception {
boolean sync = replaceFrom(getSyncRouteId(), URI_SYNC_ROUTE);
boolean async = replaceFrom(getAsyncInRouteId(), URI_ASYNC_IN_ROUTE);
if (!sync && !async) {
throw new IllegalArgumentException(String.format(
"Neither Sync, nor Async route ID is known based on Service %s and Operation Name %s" +
" - didn't find route with ID %s or %s",
getService(), getOperationName(), getSyncRouteId(), getAsyncInRouteId()));
}
}
@Before
public void redirectAsyncRoute() throws Exception {
getCamelContext().addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from(AsynchConstants.URI_ASYNC_MSG)
.routeId(AsynchMessageRoute.ROUTE_ID_ASYNC)
.log(LoggingLevel.WARN, "Ignoring Message: ${body}");
}
});
}
/**
* Sends the test request to the Sync route (as if it was received via Spring WS).
*
* @param requestXML the request payload (XML) to send
* @return the result as an exchange with getOut() containing the response message
*/
protected Exchange sendSyncMessage(final String requestXML) throws Exception {
return producer.request(URI_SYNC_ROUTE, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody(requestXML);
}
});
}
/**
* Sends the test request to the Sync route (as if it was received via Spring WS).
*
* @param requestXML the request payload (XML) to send
* @param responseClass {@link String}.class to get the response body as String,
* or the class to unmarshal the response body to using JAXB
* @return the result as the specified class
*/
protected <T> T sendSyncMessage(String requestXML, Class<T> responseClass) throws Exception {
Exchange result = sendSyncMessage(requestXML);
Exception exception = result.getException();
if (exception != null) {
throw exception;
}
String responseXML = result.getOut().getMandatoryBody(String.class);
if (responseClass.isAssignableFrom(String.class)) {
return responseClass.cast(responseXML);
}
return unmarshalFragment(responseXML, responseClass);
}
/**
* Sends the test request to the IN route (as if it was received via Spring WS).
*
* @param requestXML the request payload (XML) to send
* @param finalState the final state of the {@link Message} created in the DB - for automatic verification
* @param responseClass the response class to parse response XML as
* @return the response parsed from XML as the specified responseClass
* @throws AssertionError if the message state doesn't match the specified state
*/
protected <T> T sendAsyncInMessage(String requestXML, MsgStateEnum finalState, Class<T> responseClass) throws Exception {
String correlationID = UUID.randomUUID().toString();
return sendAsyncInMessage(correlationID, Instant.now(), requestXML, getMessageStateVerifier(finalState), responseClass);
}
/**
* Sends the test request to the IN route (as if it was received via Spring WS).
*
* @param requestXML the request payload (XML) to send
* @param messageVerifier the processor that can verify the {@link Message} created in the DB
* @param responseClass the response class to parse response XML as
* @return the response parsed from XML as the specified responseClass
* @throws AssertionError if the message state doesn't match the specified state
*/
protected <T> T sendAsyncInMessage(String requestXML, MessageCallback messageVerifier, Class<T> responseClass) throws Exception {
String correlationID = UUID.randomUUID().toString();
return sendAsyncInMessage(correlationID, Instant.now(), requestXML, messageVerifier, responseClass);
}
/**
* Sends the test request to the IN route (as if it was received via Spring WS).
*
* @param correlationID the new message correlation ID
* @param msgTimestamp the new message timestamp
* @param requestXML the request payload (XML) to send
* @param messageVerifier the processor that can verify the {@link Message} created in the DB
* @param responseClass the response class to parse response XML as
* @return the response parsed from XML as the specified responseClass
* @throws AssertionError if the message state doesn't match the specified state
*/
protected <T> T sendAsyncInMessage(String correlationID, Instant msgTimestamp, String requestXML,
MessageCallback messageVerifier, Class<T> responseClass) throws Exception {
Exchange result = sendAsyncInMessage(correlationID, msgTimestamp, requestXML);
Exception exception = result.getException();
if (exception != null) {
throw exception;
}
verifyMessage(getSourceSystem(), correlationID, messageVerifier);
String responseXML = result.getOut().getMandatoryBody(String.class);
if (responseClass.isAssignableFrom(String.class)) {
return responseClass.cast(responseXML);
}
return unmarshalFragment(responseXML, responseClass);
}
/**
* Sends the test request to the IN route
*
* @param requestXML the request payload (XML) to send
* @param responseClass the response class to parse response XML as
* @return the response parsed from XML as the specified responseClass
*/
protected <T> T sendAsyncInMessage(String requestXML, Class<T> responseClass) throws Exception {
return sendAsyncInMessage(requestXML, (MessageCallback) null, responseClass);
}
/**
* Sends the test request to the IN route
*
* @param correlationID the new message correlation ID
* @param msgTimestamp the new message timestamp
* @param requestXML the request payload (XML) to send
* @param responseClass the response class to parse response XML as
* @return the response parsed from XML as the specified responseClass
*/
protected <T> T sendAsyncInMessage(String correlationID, Instant msgTimestamp, String requestXML, Class<T> responseClass) throws Exception {
return sendAsyncInMessage(correlationID, msgTimestamp, requestXML, getMessageStateVerifier(null), responseClass);
}
/**
* Sends the test request to the IN route.
*
* @return the result as an exchange with getOut() containing the output message
*/
protected Exchange sendAsyncInMessage(final String correlationID, final Instant timestamp, final String payload) {
Exchange result = producer.request(URI_ASYNC_IN_ROUTE, new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody(payload);
exchange.getIn().setHeaders(createTraceHeader(correlationID, timestamp));
}
});
lastMessage = msgDao.findByCorrelationId(correlationID, getSourceSystem());
return result;
}
/**
* Sends a new message with the test request to the OUT route,
* similarly to what {@link MessagePollExecutor} does.
*
* @param requestXML the request payload (XML) to send
* @param finalState the final state of the {@link Message} created in the DB - for automatic verification
* @return the {@link Message} that was sent and processed
* @throws AssertionError if the message state doesn't match the specified state
*/
protected Message sendAsyncOutMessage(String requestXML, MsgStateEnum finalState) throws Exception {
lastMessage = createAndSaveMessage(requestXML);
producer.requestBody(AsynchMessageRoute.URI_SYNC_MSG, lastMessage);
verifyMessage(lastMessage.getSourceSystem(), lastMessage.getCorrelationId(), getMessageStateVerifier(finalState));
return lastMessage;
}
/**
* Sends a new message with the test request to the OUT route,
* similarly to what {@link MessagePollExecutor} does.
*
* @param correlationID the new message correlation ID
* @param msgTimestamp the new message timestamp
* @param requestXML the request payload (XML) to send
* @param finalState the final state of the {@link Message} created in the DB - for automatic verification
* @return the {@link Message} that was sent and processed
* @throws AssertionError if the message state doesn't match the specified state
*/
protected Message sendAsyncOutMessage(final String correlationID, final Instant msgTimestamp,
final String requestXML, MsgStateEnum finalState) throws Exception {
return sendAsyncOutMessage(new MessageCallback() {
@Override
public void beforeInsert(Message message, int order) {
message.setMsgTimestamp(msgTimestamp);
message.setCorrelationId(correlationID);
message.setPayload(requestXML);
}
}, finalState);
}
/**
* Sends a new message with the test request to the OUT route,
* similarly to what {@link MessagePollExecutor} does.
*
* @param initializer the message initializer that will set message fields as necessary
* @return the {@link Message} that was sent and processed
* @throws AssertionError if the message state doesn't match the specified state
*/
protected Message sendAsyncOutMessage(MessageCallback initializer) throws Exception {
return sendAsyncOutMessage(initializer, null);
}
/**
* Sends a new message with the test request to the OUT route,
* similarly to what {@link MessagePollExecutor} does.
*
* @param initializer the message initializer that will set message fields as necessary
* @param finalState the final state of the {@link Message} created in the DB - for automatic verification
* @return the {@link Message} that was sent and processed
* @throws AssertionError if the message state doesn't match the specified state
*/
protected Message sendAsyncOutMessage(final MessageCallback initializer, MsgStateEnum finalState) throws Exception {
lastMessage = createAndSaveMessage(new MessageCallback() {
@Override
public void beforeInsert(Message message, int order) throws Exception {
message.setSourceSystem(getSourceSystem());
message.setService(getService());
message.setOperationName(getOperationName());
message.setMsgTimestamp(Instant.now());
message.setReceiveTimestamp(Instant.now());
message.setCorrelationId(UUID.randomUUID().toString());
initializer.beforeInsert(message, 0); // let the provided initializer init the other fields
}
});
producer.requestBody(AsynchMessageRoute.URI_SYNC_MSG, lastMessage);
verifyMessage(lastMessage.getSourceSystem(), lastMessage.getCorrelationId(), getMessageStateVerifier(finalState));
return lastMessage;
}
/**
* Sends a new message with the test request to the OUT route,
* similarly to what {@link MessagePollExecutor} does.
*
* @param requestXML the request payload (XML) to send
* @return the {@link Message} that was sent and processed
*/
protected Message sendAsyncOutMessage(String requestXML) throws Exception {
return sendAsyncOutMessage(requestXML, null);
}
/**
* Sends a new message with the test request to the OUT route,
* similarly to what {@link MessagePollExecutor} does.
*
* @param correlationID the new message correlation ID
* @param msgTimestamp the new message timestamp
* @param requestXML the request payload (XML) to send
* @return the {@link Message} that was sent and processed
*/
protected Message sendAsyncOutMessage(String correlationID, Instant msgTimestamp, String requestXML) throws Exception {
return sendAsyncOutMessage(correlationID, msgTimestamp, requestXML, null);
}
/**
* Re-sends the last sent message, first setting it's state to {@link MsgStateEnum#PROCESSING}.
*
* @return the last {@link Message}, after it was re-sent and re-processed
*/
protected Message resendAsyncOutMessage(MsgStateEnum finalState) throws Exception {
return resendAsyncOutMessage(lastMessage, finalState);
}
/**
* Re-sends the specified message, first setting it's state to {@link MsgStateEnum#PROCESSING}.
*
* @return the same {@link Message}, after it was re-sent and re-processed
*/
protected Message resendAsyncOutMessage(Message msg, MsgStateEnum finalState) throws Exception {
msg.setState(MsgStateEnum.PROCESSING);
producer.requestBody(AsynchMessageRoute.URI_SYNC_MSG, msg);
verifyMessage(msg.getSourceSystem(), msg.getCorrelationId(), getMessageStateVerifier(finalState));
return msg;
}
/**
* Re-sends the last sent message, first setting it's state to {@link MsgStateEnum#PROCESSING}
*
* @return the last {@link Message}, after it was re-sent and re-processed
*/
protected Message resendAsyncOutMessage() throws Exception {
return resendAsyncOutMessage(lastMessage, null);
}
/**
* Re-sends the specified message, first setting it's state to {@link MsgStateEnum#PROCESSING}
*
* @return the same {@link Message}, after it was re-sent and re-processed
*/
protected Message resendAsyncOutMessage(Message msg) throws Exception {
return resendAsyncOutMessage(msg, null);
}
@Nullable
protected MessageCallback getMessageStateVerifier(@Nullable final MsgStateEnum finalState) {
return finalState == null ? null : new MessageCallback() {
@Override
public void beforeInsert(Message message, int order) throws Exception {
String stateFailReason = String.format(
"Message doesn't have the expected state. failedErrorCode=%s, failedErrorDesc=%s, businessError=%s",
message.getFailedErrorCode(), message.getFailedDesc(), message.getBusinessError());
assertThat(stateFailReason, message.getState(), is(finalState));
}
};
}
private void verifyMessage(ExternalSystemExtEnum sourceSystem, String correlationID, MessageCallback msgVerifier) throws Exception {
if (msgVerifier != null) {
Message message = msgDao.findByCorrelationId(correlationID, sourceSystem);
String msgMissingReason = String.format(
"No message found for sourceSystem=%s and correlationID=%s", sourceSystem, correlationID);
assertThat(msgMissingReason, message, notNullValue());
msgVerifier.beforeInsert(message, 0);
}
}
private Map<String, Object> createTraceHeader(String correlationID, Instant timestamp) {
TraceIdentifier traceId = new TraceIdentifier();
traceId.setCorrelationID(correlationID);
traceId.setApplicationID(getApplicationID());
traceId.setTimestamp(OffsetDateTime.ofInstant(timestamp, ZoneId.systemDefault()));
TraceHeader traceHeader = new TraceHeader();
traceHeader.setTraceIdentifier(traceId);
final Map<String, Object> headers = new HashMap<String, Object>();
headers.put(TraceHeaderProcessor.TRACE_HEADER, traceHeader);
return headers;
}
protected Message createAndSaveMessage(String requestXML) throws Exception {
return createAndSaveMessage(getSourceSystem(), getService(), getOperationName(), requestXML);
}
protected Message createAndSaveMessage(MessageCallback initializer) throws Exception {
return createAndSaveMessages(1, initializer)[0];
}
protected Message createMessage(String requestXML) {
return createMessage(getSourceSystem(), getService(), getOperationName(), requestXML);
}
public Map<String, Object> createHeaders(String correlationID, String applicationID, Instant timestamp) {
TraceIdentifier traceId = new TraceIdentifier();
traceId.setCorrelationID(correlationID);
traceId.setApplicationID(applicationID);
traceId.setTimestamp(OffsetDateTime.ofInstant(timestamp, ZoneId.systemDefault()));
TraceHeader traceHeader = new TraceHeader();
traceHeader.setTraceIdentifier(traceId);
HashMap<String, Object> headers = new HashMap<String, Object>();
headers.put(TraceHeaderProcessor.TRACE_HEADER, getTraceHeader());
return headers;
}
/**
* Gets the applicationID that corresponds to {@link #getSourceSystem()}.
*/
protected String getApplicationID() {
return getSourceSystem().getSystemName();
}
protected <T> T unmarshalFragment(String responseXML, Class<T> fragmentClass) throws JAXBException {
Unmarshaller unmarshaller = JAXBContext.newInstance(fragmentClass).createUnmarshaller();
JAXBElement<T> jaxbElement = unmarshaller.unmarshal(new StringSource(responseXML), fragmentClass);
return jaxbElement.getValue();
}
protected <T> String marshalFragment(T request, QName qName) throws JAXBException {
StringWriter stringWriter = new StringWriter();
Marshaller marshaller = JAXBContext.newInstance(request.getClass()).createMarshaller();
Object element = request;
if (qName != null) {
element = new JAXBElement<T>(qName, (Class<T>) request.getClass(), request);
}
marshaller.marshal(element, stringWriter);
return stringWriter.toString();
}
private boolean replaceFrom(String routeId, final String uri) throws Exception {
RouteDefinition routeDefinition = getCamelContext().getRouteDefinition(routeId);
if (routeDefinition != null) {
routeDefinition.adviceWith(getCamelContext(), new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
replaceFromWith(uri);
}
});
}
return routeDefinition != null;
}
/**
* Mocks a hand-over-type endpoint (direct, direct-vm, seda or vm)
* by simply providing the other (consumer=From) side connected to a mock.
* <p/>
* There should be no consumer existing, i.e., the consumer route should not be started.
*
* @param uri the URI a new mock should consume from
* @return the mock that is newly consuming from the URI
*/
protected MockEndpoint mockDirect(final String uri) throws Exception {
return mockDirect(uri, null);
}
/**
* Same as {@link #mockDirect(String)}, except with route ID to be able to override an existing route with the mock.
*
* @param uri the URI a new mock should consume from
* @param routeId the route ID for the new mock route
* (existing route with this ID will be overridden by this new route)
* @return the mock that is newly consuming from the URI
*/
protected MockEndpoint mockDirect(final String uri, final String routeId) throws Exception {
// precaution: check that URI can be mocked by just providing the other side:
Assert.assertThat(uri, anyOf(startsWith("direct:"), startsWith("direct-vm:"), startsWith("seda:"), startsWith("vm:")));
// create the mock:
final MockEndpoint createCtidMock = getCamelContext().getEndpoint("mock:" + uri, MockEndpoint.class);
// redirect output to this mock:
getCamelContext().addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
RouteDefinition routeDef = from(uri);
if (routeId != null) {
routeDef.routeId(routeId);
}
routeDef.to(createCtidMock);
}
});
return createCtidMock;
}
}
| |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.views.modal;
import javax.annotation.Nullable;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.R;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.uimanager.JSTouchDispatcher;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.views.view.ReactViewGroup;
/**
* ReactModalHostView is a view that sits in the view hierarchy representing a Modal view.
*
* It does a number of things:
* 1. It creates a Dialog. We use this Dialog to actually display the Modal in the window.
* 2. It creates a DialogRootViewGroup. This view is the view that is displayed by the Dialog. To
* display a view within a Dialog, that view must have its parent set to the window the Dialog
* creates. Because of this, we can not use the ReactModalHostView since it sits in the
* normal React view hierarchy. We do however want all of the layout magic to happen as if the
* DialogRootViewGroup were part of the hierarchy. Therefore, we forward all view changes
* around addition and removal of views to the DialogRootViewGroup.
*/
public class ReactModalHostView extends ViewGroup {
// This listener is called when the user presses KeyEvent.KEYCODE_BACK
// An event is then passed to JS which can either close or not close the Modal by setting the
// visible property
public interface OnRequestCloseListener {
void onRequestClose(DialogInterface dialog);
}
private DialogRootViewGroup mHostView;
private @Nullable Dialog mDialog;
private boolean mTransparent;
private boolean mAnimated;
// Set this flag to true if changing a particular property on the view requires a new Dialog to
// be created. For instance, animation does since it affects Dialog creation through the theme
// but transparency does not since we can access the window to update the property.
private boolean mPropertyRequiresNewDialog;
private @Nullable DialogInterface.OnShowListener mOnShowListener;
private @Nullable OnRequestCloseListener mOnRequestCloseListener;
public ReactModalHostView(Context context) {
super(context);
mHostView = new DialogRootViewGroup(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Do nothing as we are laid out by UIManager
}
@Override
public void addView(View child, int index) {
mHostView.addView(child, index);
}
@Override
public int getChildCount() {
return mHostView.getChildCount();
}
@Override
public View getChildAt(int index) {
return mHostView.getChildAt(index);
}
@Override
public void removeView(View child) {
mHostView.removeView(child);
}
@Override
public void removeViewAt(int index) {
View child = getChildAt(index);
mHostView.removeView(child);
}
public void dismiss() {
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
// We need to remove the mHostView from the parent
// It is possible we are dismissing this dialog and reattaching the hostView to another
ViewGroup parent = (ViewGroup) mHostView.getParent();
parent.removeViewAt(0);
}
}
protected void setOnRequestCloseListener(OnRequestCloseListener listener) {
mOnRequestCloseListener = listener;
}
protected void setOnShowListener(DialogInterface.OnShowListener listener) {
mOnShowListener = listener;
}
protected void setTransparent(boolean transparent) {
mTransparent = transparent;
}
protected void setAnimated(boolean animated) {
mAnimated = animated;
mPropertyRequiresNewDialog = true;
}
@VisibleForTesting
public @Nullable Dialog getDialog() {
return mDialog;
}
/**
* showOrUpdate will display the Dialog. It is called by the manager once all properties are set
* because we need to know all of them before creating the Dialog. It is also smart during
* updates if the changed properties can be applied directly to the Dialog or require the
* recreation of a new Dialog.
*/
protected void showOrUpdate() {
// If the existing Dialog is currently up, we may need to redraw it or we may be able to update
// the property without having to recreate the dialog
if (mDialog != null) {
if (mPropertyRequiresNewDialog) {
dismiss();
} else {
updateProperties();
return;
}
}
// Reset the flag since we are going to create a new dialog
mPropertyRequiresNewDialog = false;
int theme = R.style.Theme_FullScreenDialog;
if (mAnimated) {
theme = R.style.Theme_FullScreenDialogAnimated;
}
mDialog = new Dialog(getContext(), theme);
mDialog.setContentView(mHostView);
updateProperties();
mDialog.setOnShowListener(mOnShowListener);
mDialog.setOnKeyListener(
new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// We need to stop the BACK button from closing the dialog by default so we capture that
// event and instead inform JS so that it can make the decision as to whether or not to
// allow the back button to close the dialog. If it chooses to, it can just set visible
// to false on the Modal and the Modal will go away
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (event.getAction() == KeyEvent.ACTION_UP) {
Assertions.assertNotNull(
mOnRequestCloseListener,
"setOnRequestCloseListener must be called by the manager");
mOnRequestCloseListener.onRequestClose(dialog);
}
return true;
}
return false;
}
});
mDialog.show();
}
/**
* updateProperties will update the properties that do not require us to recreate the dialog
* Properties that do require us to recreate the dialog should set mPropertyRequiresNewDialog to
* true when the property changes
*/
private void updateProperties() {
Assertions.assertNotNull(mDialog, "mDialog must exist when we call updateProperties");
if (mTransparent) {
mDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
} else {
mDialog.getWindow().setDimAmount(0.5f);
mDialog.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_DIM_BEHIND,
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
}
/**
* DialogRootViewGroup is the ViewGroup which contains all the children of a Modal. It gets all
* child information forwarded from ReactModalHostView and uses that to create children. It is
* also responsible for acting as a RootView and handling touch events. It does this the same
* way as ReactRootView.
*/
static class DialogRootViewGroup extends ReactViewGroup implements RootView {
private final JSTouchDispatcher mJSTouchDispatcher = new JSTouchDispatcher(this);
public DialogRootViewGroup(Context context) {
super(context);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
mJSTouchDispatcher.handleTouchEvent(event, getEventDispatcher());
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mJSTouchDispatcher.handleTouchEvent(event, getEventDispatcher());
super.onTouchEvent(event);
// In case when there is no children interested in handling touch event, we return true from
// the root view in order to receive subsequent events related to that gesture
return true;
}
@Override
public void onChildStartedNativeGesture(MotionEvent androidEvent) {
mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, getEventDispatcher());
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// No-op - override in order to still receive events to onInterceptTouchEvent
// even when some other view disallow that
}
private EventDispatcher getEventDispatcher() {
ReactContext reactContext = (ReactContext) getContext();
return reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
}
}
}
| |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui.screen;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Container;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.gdx.bomberman.Constants;
import java.util.ArrayList;
import client.Client;
import gui.AudioManager;
import gui.TextureManager;
import inputHandling.InputHandler;
import server.Server;
import static gui.TextureManager.backSkin;
/**
*
* @author qubasa
*/
public class WinnerScreen extends Screens implements Screen
{
//Objects
private Stage stage;
private Table rootTable = new Table();
private InputHandler inputHandler = new InputHandler();
// Player positions
ArrayList<Integer> playerPositions = new ArrayList<>();
private boolean isWinner;
// Buttons
private TextButton backButton;
// Labels
private Label titel;
private WidgetGroup positionPlayerWidget = new WidgetGroup();
private Label p1Position;
private Label p2Position;
private Label p3Position;
private Label p4Position;
// Player dispaly widget
private WidgetGroup joinedPlayerGroup = new WidgetGroup();
private Container p1Field;
private Container p2Field;
private Container p3Field;
private Container p4Field;
//Player highlight
private WidgetGroup playerhighlightWidget = new WidgetGroup();
private Container p1FieldHighlight;
private Container p2FieldHighlight;
private Container p3FieldHighlight;
private Container p4FieldHighlight;
public WinnerScreen(ArrayList<Integer> playerPositions,final Game game,final Client client,final Server server)
{
super(game, client, server);
//Set input and viewpoint
stage = new Stage(new StretchViewport(Constants.SCREENWIDTH, Constants.SCREENHEIGHT));
inputHandler.setInputSource(stage);
// Unhides the cursor
Gdx.input.setCursorCatched(false);
this.playerPositions = playerPositions;
//Set background
rootTable.background(new TextureRegionDrawable(new TextureRegion(TextureManager.hostBackground)));
rootTable.setFillParent(true);
stage.addActor(rootTable);
//Initialise Font
FreeTypeFontGenerator.FreeTypeFontParameter fontOptions = new FreeTypeFontGenerator.FreeTypeFontParameter();
fontOptions.size = 11;
BitmapFont font = TextureManager.menuFont.generateFont(fontOptions);
/**------------------------LABEL STYLE------------------------**/
Label.LabelStyle labelStyle = new Label.LabelStyle();
fontOptions.size = 60;
labelStyle.font = TextureManager.menuFont.generateFont(fontOptions);
labelStyle.fontColor = Color.GOLD;
/**------------------------PLAYER DISPLAY WIDGET------------------------**/
//Table options
Table table = new Table();
table.setFillParent(true);
//P1 spawn field
p1Field = new Container();
p1Field.background(new TextureRegionDrawable((TextureRegion) TextureManager.p1WalkingDownAnim.getKeyFrame(0)));
table.add(p1Field).width(64).height(64);
//P2 spawn field
p2Field = new Container();
p2Field.setVisible(false);
p2Field.background(new TextureRegionDrawable((TextureRegion) TextureManager.p2WalkingDownAnim.getKeyFrame(0)));
table.add(p2Field).width(64).height(64).padLeft(96);
//P3 spawn field
p3Field = new Container();
p3Field.setVisible(false);
p3Field.background(new TextureRegionDrawable((TextureRegion) TextureManager.p3WalkingDownAnim.getKeyFrame(0)));
table.add(p3Field).width(64).height(64).padLeft(96);
//P4 spawn field
p4Field = new Container();
p4Field.setVisible(false);
p4Field.background(new TextureRegionDrawable((TextureRegion) TextureManager.p4WalkingDownAnim.getKeyFrame(0)));
table.add(p4Field).width(64).height(64).padLeft(96);
//Stage & group options
joinedPlayerGroup.addActor(table);
joinedPlayerGroup.setPosition(443, 150);
stage.addActor(joinedPlayerGroup);
/**------------------------PLAYER HIGHLIGHT WIDGET------------------------**/
//Table options
Table table2 = new Table();
table2.setFillParent(true);
//P1 spawn field
p1FieldHighlight = new Container();
p1FieldHighlight.setVisible(false);
p1FieldHighlight.background(new TextureRegionDrawable(new TextureRegion(TextureManager.playerMarker)));
table2.add(p1FieldHighlight).width(80).height(77);
//P2 spawn field
p2FieldHighlight = new Container();
p2FieldHighlight.setVisible(false);
p2FieldHighlight.background(new TextureRegionDrawable(new TextureRegion(TextureManager.playerMarker)));
table2.add(p2FieldHighlight).width(80).height(77).padLeft(80);
//P3 spawn field
p3FieldHighlight = new Container();
p3FieldHighlight.setVisible(false);
p3FieldHighlight.background(new TextureRegionDrawable(new TextureRegion(TextureManager.playerMarker)));
table2.add(p3FieldHighlight).width(80).height(77).padLeft(80);
//P4 spawn field
p4FieldHighlight = new Container();
p4FieldHighlight.setVisible(false);
p4FieldHighlight.background(new TextureRegionDrawable(new TextureRegion(TextureManager.playerMarker)));
table2.add(p4FieldHighlight).width(80).height(77).padLeft(80);
//Stage & group options
playerhighlightWidget.addActor(table2);
playerhighlightWidget.setPosition(442, 152);
stage.addActor(playerhighlightWidget);
/**------------------------LABELS------------------------**/
// Titel
titel = new Label("", labelStyle);
titel.setAlignment(Align.center);
titel.setPosition((Constants.SCREENWIDTH - titel.getWidth()) / 2 + 50, 385);
stage.addActor(titel);
// If you are the winner
if(Constants.PLAYERID == playerPositions.get(playerPositions.size() -1))
{
titel.setText("YOU WON!");
isWinner = true;
}else
{
isWinner = false;
titel.setText("YOU LOOSE!");
titel.setColor(Color.RED);
}
if(-1 == playerPositions.get(playerPositions.size() -1))
{
titel.setText("DRAW!");
titel.setColor(Color.DARK_GRAY);
isWinner = false;
}
Table positionTable = new Table();
positionTable.setFillParent(true);
p1Position = new Label("", labelStyle);
p1Position.setAlignment(Align.center);
p2Position = new Label("", labelStyle);
p2Position.setAlignment(Align.center);
p3Position = new Label("", labelStyle);
p3Position.setAlignment(Align.center);
p4Position = new Label("", labelStyle);
p4Position.setAlignment(Align.center);
positionTable.add(p1Position).width(64).height(64);
positionTable.add(p2Position).width(64).height(64).padLeft(96);
positionTable.add(p3Position).width(64).height(64).padLeft(96);
positionTable.add(p4Position).width(64).height(64).padLeft(96);
positionPlayerWidget.addActor(positionTable);
positionPlayerWidget.setPosition(443, 230);
stage.addActor(positionPlayerWidget);
/**------------------------MUSIC------------------------**/
if(isWinner == false)
{
AudioManager.setCurrentMusic(AudioManager.getLooserMusic());
AudioManager.getCurrentMusic().setLooping(true);
AudioManager.getCurrentMusic().play();
AudioManager.getCurrentMusic().setVolume(AudioManager.getMusicVolume() * 4);
}else
{
AudioManager.setCurrentMusic(AudioManager.getWinnerMusic());
AudioManager.getCurrentMusic().setLooping(true);
AudioManager.getCurrentMusic().play();
AudioManager.getCurrentMusic().setVolume(AudioManager.getMusicVolume() * 6);
}
/**------------------------BUTTONS------------------------**/
TextButton.TextButtonStyle textButtonStyleBack = new TextButton.TextButtonStyle();
textButtonStyleBack.font = font;
textButtonStyleBack.up = backSkin.getDrawable("button_up");
textButtonStyleBack.down = backSkin.getDrawable("button_down");
textButtonStyleBack.over = backSkin.getDrawable("button_checked");
// Back button
backButton = new TextButton("", textButtonStyleBack);
backButton.setPosition(0, Constants.SCREENHEIGHT - backButton.getHeight() + 7);
stage.addActor(backButton);
renderPlayers();
//Add click listener --> Back button
backButton.addListener(new ChangeListener()
{
@Override
public void changed (ChangeListener.ChangeEvent event, Actor actor)
{
//Add click musik
AudioManager.playClickSound();
// Wait till sound is done
try
{
Thread.sleep(100);
} catch (InterruptedException ex)
{
}
if(isWinner)
{
AudioManager.getCurrentMusic().stop();
}else
{
AudioManager.getCurrentMusic().stop();
}
server.stopServer();
game.setScreen(new MenuScreen(game, client, server));
}
});
}
public final void renderPlayers()
{
// Display participated players
for(int i=0; i < playerPositions.size(); i++)
{
switch(playerPositions.get(i))
{
case 1:
p1Position.setText(Integer.toString(playerPositions.size() -i));
p1Field.setVisible(true);
if(1 == Constants.PLAYERID)
{
p1FieldHighlight.setVisible(true);
}
break;
case 2:
p2Position.setText(Integer.toString(playerPositions.size() -i));
p2Field.setVisible(true);
if(2 == Constants.PLAYERID)
{
p2FieldHighlight.setVisible(true);
}
break;
case 3:
p3Position.setText(Integer.toString(playerPositions.size() -i));
p3Field.setVisible(true);
if(3 == Constants.PLAYERID)
{
p3FieldHighlight.setVisible(true);
}
break;
case 4:
p4Position.setText(Integer.toString(playerPositions.size() -i));
p4Field.setVisible(true);
if(4 == Constants.PLAYERID)
{
p4FieldHighlight.setVisible(true);
}
break;
}
}
}
/**------------------------RENDER------------------------**/
@Override
public void render(float f)
{
//Debug
//stage.setDebugAll(true);
//Clear Screen
Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
//Draw stage
stage.act(Constants.DELTATIME);
stage.draw();
/*------------------SWITCH TO FULLSCREEN AND BACK------------------*/
super.changeToFullScreenOnF12();
/*------------------QUIT GAME------------------*/
if (Gdx.input.isKeyPressed(Input.Keys.ESCAPE))
{
if(isWinner)
{
AudioManager.getCurrentMusic().stop();
}else
{
AudioManager.getCurrentMusic().stop();
}
server.stopServer();
game.setScreen(new MenuScreen(game, client, server));
}
}
@Override
public void dispose()
{
stage.dispose();
backSkin.dispose();
}
@Override
public void show() {
}
@Override
public void resize(int i, int i1) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
}
| |
/*
* Copyright 2011-2013, by Vladimir Kostyukov and Contributors.
*
* This file is part of la4j project (http://la4j.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s): Daniel Renshaw
* Jakob Moellers
* Maxim Samoylov
*
*/
package org.la4j.vector;
import java.io.Externalizable;
import org.la4j.factory.Factory;
import org.la4j.matrix.Matrix;
import org.la4j.vector.functor.VectorAccumulator;
import org.la4j.vector.functor.VectorFunction;
import org.la4j.vector.functor.VectorPredicate;
import org.la4j.vector.functor.VectorProcedure;
/**
* The real vector interface.
*/
public interface Vector extends Externalizable {
/**
* Returns an element that stored at index {@code i} in this vector.
*
* @param i index
* @return vector element
*/
double get(int i);
/**
* Assigns an element that stored at index {@code i} in this vector to
* given {@code value}.
*
* @param i index
* @param value
*/
void set(int i, double value);
/**
* Assigns all elements of this vector to given {@code value}.
*
* @param value
*/
void assign(double value);
/**
* Returns the length of this vector.
*
* @return length of this vector
*/
int length();
/**
* Adds given {@code value} to this vector. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param value
* @return new vector
*/
Vector add(double value);
/**
* Adds given {@code value} to this vector. The new vector will be
* constructed with given {@code factory}.
*
* @param value
* @param factory
* @return new vector
*/
Vector add(double value, Factory factory);
/**
* Adds given {@code vector} to this vector. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param vector
* @return new vector
*/
Vector add(Vector vector);
/**
* Adds given {@code vector} to this vector. The new vector will be
* constructed with given {@code factory}.
*
* @param vector
* @param factory
* @return new vector
*/
Vector add(Vector vector, Factory factory);
/**
* Multiplies this vector by given {@code value}. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param value
* @return new vector
*/
Vector multiply(double value);
/**
* Multiplies this vector by given {@code value}. The new vector will be
* constructed with given {@code factory}.
*
* @param value
* @param factory
* @return new vector
*/
Vector multiply(double value, Factory factory);
/**
* Calculates the Hadamard (element-wise/pointwise) product of this vector
* and given {@code vector}. The new vector will be constructed with
* default {@link Factory factory}.
*
* @param vector
* @return new vector
*/
Vector hadamardProduct(Vector vector);
/**
* Calculates the Hadamard (element-wise/pointwise) product of this vector
* and given {@code vector}. The new vector will be constructed with given
* {@link Factory factory}.
*
* @param vector
* @param factory
* @return new vector
*/
Vector hadamardProduct(Vector vector, Factory factory);
/**
* Multiples this vector by given {@code matrix}. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param matrix
* @return new vector
*/
Vector multiply(Matrix matrix);
/**
* Multiples this vector by given {@code matrix}. The new vector will be
* constructed with given {@code factory}.
* @param matrix
* @param factory
* @return new vector
*/
Vector multiply(Matrix matrix, Factory factory);
/**
* Subtracts given {@code value} from this vector. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param value
* @return new vector
*/
Vector subtract(double value);
/**
* Subtracts given {@code value} from this vector. The new vector will be
* constructed with given {@code factory}.
* @param value
* @param factory
* @return new vector
*/
Vector subtract(double value, Factory factory);
/**
* Subtracts given {@code vector} from this vector. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param vector
* @return new vector
*/
Vector subtract(Vector vector);
/**
* Subtracts given {@code vector} from this vector. The new vector will be
* constructed with given {@code factory}.
*
* @param vector
* @param factory
* @return new vector
*/
Vector subtract(Vector vector, Factory factory);
/**
* Divides this vector by {@code value}. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param value
* @return new vector
*/
Vector divide(double value);
/**
* Divides this vector by {@code value}. The new vector will be
* constructed with given {@code factory}.
* @param value
* @param factory
* @return new vector
*/
Vector divide(double value, Factory factory);
/**
* Productizes all elements of the vector
*
* @return product of all vector elements
*/
double product();
/**
* Summarizes all elements of the vector
*
* @return sum of all elements of the vector
*/
double sum();
/**
* Calculates the inner product of this vector and given {@code vector}.
*
* @param vector
* @return product of two vectors
*/
double innerProduct(Vector vector);
/**
* Calculates the outer product of this vector and given {@code vector}.
* The new matrix will be constructed with default {@code factory}.
*
* @param vector
* @return outer product of two vectors
*/
Matrix outerProduct(Vector vector);
/**
* Calculates the outer product of this vector and given {@code vector}.
* The new matrix will be constructed with given {@code factory}.
*
* @param vector
* @param factory
* @return outer product of two vectors
*/
Matrix outerProduct(Vector vector, Factory factory);
/**
* Calculates the norm of this vector.
*
* @return norm of this vector
*/
double norm();
/**
* Normalizes this vector. The new vector will be constructed
* with default {@link Factory factory}.
*
* @return normalized vector
*/
Vector normalize();
/**
* Normalizes this vector. The new vector will be constructed
* with given {@code factory}.
*
* @param factory
* @return normalized vector
*/
Vector normalize(Factory factory);
/**
* Swaps two elements of this vector. Elements that stored at {@code i} and
* {@code j} indices will be swapped.
*
* @param i index
* @param j index
*/
void swap(int i, int j);
/**
* Creates a blank copy of this vector. The new vector will be constructed
* with default {@link Factory factory}.
*
* @return blank vector
*/
Vector blank();
/**
* Creates a blank copy of this vector. The new vector will be constructed
* with given {@code factory}.
*
* @param factory
* @return blank vector
*/
Vector blank(Factory factory);
/**
* Copies this vector. The new vector will be constructed
* with default {@link Factory factory}.
*
* @return copy of this vector
*/
Vector copy();
/**
* Copies this vector. The new vector will be constructed
* with given {@code factory}.
*
* @param factory
* @return copy of this vector
*/
Vector copy(Factory factory);
/**
* Resizes this vector to new {@code length}. The new vector
* will be constructed with default {@link Factory factory}.
*
* @param length
* @return new vector
*/
Vector resize(int length);
/**
* Resizes this vector to new {@code length}. The new vector
* will be constructed with given {@code factory}.
*
* @param length
* @param factory
* @return new vector
*/
Vector resize(int length, Factory factory);
/**
* Vector that contains the same elements but with the elements shuffled
* around (which might also result in the same vector (all outcomes are
* equally probable)).
*
* @return The shuffled vector.
*/
Vector shuffle();
/**
* Vector that contains the same elements but with the elements shuffled
* around (which might also result in the same vector (all outcomes are
* equally probable)).
*
* @param factory
* The factory to use for this
* @return The shuffled vector.
*/
Vector shuffle(Factory factory);
/**
* Slices this vector to given interval [{@code from}; {@code until}).
* The new vector will be constructed with default {@link Factory factory}.
*
* @param from
* @param until
* @return new vector
*/
Vector slice(int from, int until);
/**
* Slices this vector to given interval [{@code from}; {@code until}).
* The new vector will be constructed with given {@code factory}.
*
* @param from
* @param until
* @param factory
* @return new vector
*/
Vector slice(int from, int until, Factory factory);
/**
* Slices this vector to given left interval [0; {@code until}).
* The new vector will be constructed with default {@link Factory factory}.
*
* @param until
* @return new vector
*/
Vector sliceLeft(int until);
/**
* Slices this vector to given left interval [0; {@code until}).
* The new vector will be constructed with given {@code factory}.
*
* @param until
* @param factory
* @return new vector
*/
Vector sliceLeft(int until, Factory factory);
/**
* Slices this vector to given right interval [{@code from}; {@code length}).
* The new vector will be constructed with default {@link Factory factory}.
*
* @param from
* @return new vector
*/
Vector sliceRight(int from);
/**
* Slices this vector to given right interval [{@code from}; {@code length}).
* The new vector will be constructed with given {@code factory}.
*
* @param from
* @param factory
* @return new vector
*/
Vector sliceRight(int from, Factory factory);
/**
* Returns a factory that associated with this vector.
*
* @return factory
*/
Factory factory();
/**
* Applies given {@code procedure} to each element of this vector.
*
* @param procedure
*/
void each(VectorProcedure procedure);
/**
* Applies given {@code procedure} to each non-zero element of this vector.
*
* @param procedure
*/
void eachNonZero(VectorProcedure procedure);
/**
* Builds a new vector by applying given {@code function} to each element
* of this vector. The new vector will be constructed with default
* {@link Factory factory}.
*
* @param function
* @return new vector
*/
Vector transform(VectorFunction function);
/**
* Builds a new vector by applying given {@code function} to each element
* of this vector. The new vector will be constructed with given
* {@code factory}.
*
* @param function
* @param factory
* @return new vector
*/
Vector transform(VectorFunction function, Factory factory);
/**
* Builds a new vector by applying given {@code function} to element that
* stored at {@code i} index in this vector. The new vector will be
* constructed with default {@link Factory factory}.
*
* @param i index
* @param function
* @return new vector
*/
Vector transform(int i, VectorFunction function);
/**
* Builds a new vector by applying given {@code function} to element that
* stored at {@code i} index in this vector. The new vector will be
* constructed with given {@code factory}.
*
* @param i index
* @param function
* @param factory
* @return new vector
*/
Vector transform(int i, VectorFunction function, Factory factory);
/**
* Updates all elements of this vector by evaluating a given {@code function}.
*
* @param function
*/
void update(VectorFunction function);
/**
* Updates element that stored at {@code i} index of this vector by
* evaluating a given {@code function}.
*
* @param i index
* @param function
*/
void update(int i, VectorFunction function);
/**
* Combines all elements of this vector into the value by using given
* {@code accumulator}.
*
* @param accumulator
* @return
*/
double fold(VectorAccumulator accumulator);
/**
* Checks whether this vector matches to given {@code predicate}.
*
* @param predicate
* @return whether matches or not
*/
boolean is(VectorPredicate predicate);
/**
* Wraps this vector with safe interface.
*
* @return safe vector
*/
Vector safe();
/**
* Wraps this vector with unsafe interface.
*
* @return unsafe vector
*/
Vector unsafe();
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.authorization;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.Restricted;
import org.apache.nifi.authorization.resource.AccessPolicyAuthorizable;
import org.apache.nifi.authorization.resource.Authorizable;
import org.apache.nifi.authorization.resource.DataAuthorizable;
import org.apache.nifi.authorization.resource.DataTransferAuthorizable;
import org.apache.nifi.authorization.resource.ResourceFactory;
import org.apache.nifi.authorization.resource.ResourceType;
import org.apache.nifi.authorization.resource.RestrictedComponentsAuthorizable;
import org.apache.nifi.authorization.resource.TenantAuthorizable;
import org.apache.nifi.authorization.user.NiFiUser;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.components.ConfigurableComponent;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.connectable.Connectable;
import org.apache.nifi.connectable.Connection;
import org.apache.nifi.connectable.Port;
import org.apache.nifi.controller.ConfiguredComponent;
import org.apache.nifi.controller.ProcessorNode;
import org.apache.nifi.controller.ReportingTaskNode;
import org.apache.nifi.controller.Snippet;
import org.apache.nifi.controller.service.ControllerServiceNode;
import org.apache.nifi.controller.service.ControllerServiceReference;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.nar.ExtensionManager;
import org.apache.nifi.remote.PortAuthorizationResult;
import org.apache.nifi.remote.RootGroupPort;
import org.apache.nifi.util.BundleUtils;
import org.apache.nifi.web.ResourceNotFoundException;
import org.apache.nifi.web.api.dto.BundleDTO;
import org.apache.nifi.web.api.dto.FlowSnippetDTO;
import org.apache.nifi.web.controller.ControllerFacade;
import org.apache.nifi.web.dao.AccessPolicyDAO;
import org.apache.nifi.web.dao.ConnectionDAO;
import org.apache.nifi.web.dao.ControllerServiceDAO;
import org.apache.nifi.web.dao.FunnelDAO;
import org.apache.nifi.web.dao.LabelDAO;
import org.apache.nifi.web.dao.PortDAO;
import org.apache.nifi.web.dao.ProcessGroupDAO;
import org.apache.nifi.web.dao.ProcessorDAO;
import org.apache.nifi.web.dao.RemoteProcessGroupDAO;
import org.apache.nifi.web.dao.ReportingTaskDAO;
import org.apache.nifi.web.dao.SnippetDAO;
import org.apache.nifi.web.dao.TemplateDAO;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
class StandardAuthorizableLookup implements AuthorizableLookup {
private static final TenantAuthorizable TENANT_AUTHORIZABLE = new TenantAuthorizable();
private static final Authorizable RESTRICTED_COMPONENTS_AUTHORIZABLE = new RestrictedComponentsAuthorizable();
private static final Authorizable POLICIES_AUTHORIZABLE = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getPoliciesResource();
}
};
private static final Authorizable PROVENANCE_AUTHORIZABLE = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getProvenanceResource();
}
};
private static final Authorizable COUNTERS_AUTHORIZABLE = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getCountersResource();
}
};
private static final Authorizable RESOURCE_AUTHORIZABLE = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getResourceResource();
}
};
private static final Authorizable SITE_TO_SITE_AUTHORIZABLE = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getSiteToSiteResource();
}
};
private static final Authorizable FLOW_AUTHORIZABLE = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getFlowResource();
}
};
private static final Authorizable SYSTEM_AUTHORIZABLE = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getSystemResource();
}
};
// nifi core components
private ControllerFacade controllerFacade;
// data access objects
private ProcessorDAO processorDAO;
private ProcessGroupDAO processGroupDAO;
private RemoteProcessGroupDAO remoteProcessGroupDAO;
private LabelDAO labelDAO;
private FunnelDAO funnelDAO;
private SnippetDAO snippetDAO;
private PortDAO inputPortDAO;
private PortDAO outputPortDAO;
private ConnectionDAO connectionDAO;
private ControllerServiceDAO controllerServiceDAO;
private ReportingTaskDAO reportingTaskDAO;
private TemplateDAO templateDAO;
private AccessPolicyDAO accessPolicyDAO;
@Override
public Authorizable getController() {
return controllerFacade;
}
@Override
public ComponentAuthorizable getConfigurableComponent(final String type, final BundleDTO bundle) {
try {
final ConfigurableComponent configurableComponent = controllerFacade.getTemporaryComponent(type, bundle);
return new ConfigurableComponentAuthorizable(configurableComponent);
} catch (final Exception e) {
throw new AccessDeniedException("Unable to create component to verify if it references any Controller Services.");
}
}
@Override
public ComponentAuthorizable getProcessor(final String id) {
final ProcessorNode processorNode = processorDAO.getProcessor(id);
return new ProcessorComponentAuthorizable(processorNode);
}
@Override
public RootGroupPortAuthorizable getRootGroupInputPort(String id) {
final Port inputPort = inputPortDAO.getPort(id);
if (!(inputPort instanceof RootGroupPort)) {
throw new IllegalArgumentException(String.format("The specified id '%s' does not represent an input port in the root group.", id));
}
final DataTransferAuthorizable baseAuthorizable = new DataTransferAuthorizable(inputPort);
return new RootGroupPortAuthorizable() {
@Override
public Authorizable getAuthorizable() {
return baseAuthorizable;
}
@Override
public AuthorizationResult checkAuthorization(NiFiUser user) {
// perform the authorization of the user by using the underlying component, ensures consistent authorization with raw s2s
final PortAuthorizationResult authorizationResult = ((RootGroupPort) inputPort).checkUserAuthorization(user);
if (authorizationResult.isAuthorized()) {
return AuthorizationResult.approved();
} else {
return AuthorizationResult.denied(authorizationResult.getExplanation());
}
}
};
}
@Override
public RootGroupPortAuthorizable getRootGroupOutputPort(String id) {
final Port outputPort = outputPortDAO.getPort(id);
if (!(outputPort instanceof RootGroupPort)) {
throw new IllegalArgumentException(String.format("The specified id '%s' does not represent an output port in the root group.", id));
}
final DataTransferAuthorizable baseAuthorizable = new DataTransferAuthorizable(outputPort);
return new RootGroupPortAuthorizable() {
@Override
public Authorizable getAuthorizable() {
return baseAuthorizable;
}
@Override
public AuthorizationResult checkAuthorization(NiFiUser user) {
// perform the authorization of the user by using the underlying component, ensures consistent authorization with raw s2s
final PortAuthorizationResult authorizationResult = ((RootGroupPort) outputPort).checkUserAuthorization(user);
if (authorizationResult.isAuthorized()) {
return AuthorizationResult.approved();
} else {
return AuthorizationResult.denied(authorizationResult.getExplanation());
}
}
};
}
@Override
public Authorizable getInputPort(final String id) {
return inputPortDAO.getPort(id);
}
@Override
public Authorizable getOutputPort(final String id) {
return outputPortDAO.getPort(id);
}
@Override
public ConnectionAuthorizable getConnection(final String id) {
final Connection connection = connectionDAO.getConnection(id);
return new StandardConnectionAuthorizable(connection);
}
@Override
public ProcessGroupAuthorizable getProcessGroup(final String id) {
final ProcessGroup processGroup = processGroupDAO.getProcessGroup(id);
return new StandardProcessGroupAuthorizable(processGroup);
}
@Override
public Authorizable getRemoteProcessGroup(final String id) {
return remoteProcessGroupDAO.getRemoteProcessGroup(id);
}
@Override
public Authorizable getLabel(final String id) {
return labelDAO.getLabel(id);
}
@Override
public Authorizable getFunnel(final String id) {
return funnelDAO.getFunnel(id);
}
@Override
public ComponentAuthorizable getControllerService(final String id) {
final ControllerServiceNode controllerService = controllerServiceDAO.getControllerService(id);
return new ControllerServiceComponentAuthorizable(controllerService);
}
@Override
public Authorizable getProvenance() {
return PROVENANCE_AUTHORIZABLE;
}
@Override
public Authorizable getCounters() {
return COUNTERS_AUTHORIZABLE;
}
@Override
public Authorizable getResource() {
return RESOURCE_AUTHORIZABLE;
}
@Override
public Authorizable getSiteToSite() {
return SITE_TO_SITE_AUTHORIZABLE;
}
@Override
public Authorizable getFlow() {
return FLOW_AUTHORIZABLE;
}
private ConfiguredComponent findControllerServiceReferencingComponent(final ControllerServiceReference referencingComponents, final String id) {
ConfiguredComponent reference = null;
for (final ConfiguredComponent component : referencingComponents.getReferencingComponents()) {
if (component.getIdentifier().equals(id)) {
reference = component;
break;
}
if (component instanceof ControllerServiceNode) {
final ControllerServiceNode refControllerService = (ControllerServiceNode) component;
reference = findControllerServiceReferencingComponent(refControllerService.getReferences(), id);
if (reference != null) {
break;
}
}
}
return reference;
}
@Override
public Authorizable getControllerServiceReferencingComponent(String controllerServiceId, String id) {
final ControllerServiceNode controllerService = controllerServiceDAO.getControllerService(controllerServiceId);
final ControllerServiceReference referencingComponents = controllerService.getReferences();
final ConfiguredComponent reference = findControllerServiceReferencingComponent(referencingComponents, id);
if (reference == null) {
throw new ResourceNotFoundException("Unable to find referencing component with id " + id);
}
return reference;
}
@Override
public ComponentAuthorizable getReportingTask(final String id) {
final ReportingTaskNode reportingTaskNode = reportingTaskDAO.getReportingTask(id);
return new ReportingTaskComponentAuthorizable(reportingTaskNode);
}
@Override
public SnippetAuthorizable getSnippet(final String id) {
final Snippet snippet = snippetDAO.getSnippet(id);
final ProcessGroup processGroup = processGroupDAO.getProcessGroup(snippet.getParentGroupId());
return new SnippetAuthorizable() {
@Override
public Authorizable getParentProcessGroup() {
return processGroup;
}
@Override
public Set<ComponentAuthorizable> getSelectedProcessors() {
return processGroup.getProcessors().stream()
.filter(processor -> snippet.getProcessors().containsKey(processor.getIdentifier()))
.map(processor -> getProcessor(processor.getIdentifier()))
.collect(Collectors.toSet());
}
@Override
public Set<ConnectionAuthorizable> getSelectedConnections() {
return processGroup.getConnections().stream()
.filter(connection -> snippet.getConnections().containsKey(connection.getIdentifier()))
.map(connection -> getConnection(connection.getIdentifier()))
.collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getSelectedInputPorts() {
return processGroup.getInputPorts().stream()
.filter(inputPort -> snippet.getInputPorts().containsKey(inputPort.getIdentifier()))
.map(inputPort -> getInputPort(inputPort.getIdentifier()))
.collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getSelectedOutputPorts() {
return processGroup.getOutputPorts().stream()
.filter(outputPort -> snippet.getOutputPorts().containsKey(outputPort.getIdentifier()))
.map(outputPort -> getOutputPort(outputPort.getIdentifier()))
.collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getSelectedFunnels() {
return processGroup.getFunnels().stream()
.filter(funnel -> snippet.getFunnels().containsKey(funnel.getIdentifier()))
.map(funnel -> getFunnel(funnel.getIdentifier()))
.collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getSelectedLabels() {
return processGroup.getLabels().stream()
.filter(label -> snippet.getLabels().containsKey(label.getIdentifier()))
.map(label -> getLabel(label.getIdentifier()))
.collect(Collectors.toSet());
}
@Override
public Set<ProcessGroupAuthorizable> getSelectedProcessGroups() {
return processGroup.getProcessGroups().stream()
.filter(processGroup -> snippet.getProcessGroups().containsKey(processGroup.getIdentifier()))
.map(processGroup -> getProcessGroup(processGroup.getIdentifier()))
.collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getSelectedRemoteProcessGroups() {
return processGroup.getRemoteProcessGroups().stream()
.filter(remoteProcessGroup -> snippet.getRemoteProcessGroups().containsKey(remoteProcessGroup.getIdentifier()))
.map(remoteProcessGroup -> getRemoteProcessGroup(remoteProcessGroup.getIdentifier()))
.collect(Collectors.toSet());
}
};
}
@Override
public Authorizable getTenant() {
return TENANT_AUTHORIZABLE;
}
@Override
public Authorizable getPolicies() {
return POLICIES_AUTHORIZABLE;
}
@Override
public Authorizable getAccessPolicyById(final String id) {
final AccessPolicy policy = accessPolicyDAO.getAccessPolicy(id);
return getAccessPolicyByResource(policy.getResource());
}
@Override
public Authorizable getAccessPolicyByResource(final String resource) {
try {
return new AccessPolicyAuthorizable(getAuthorizableFromResource(resource));
} catch (final ResourceNotFoundException e) {
// the underlying component has been removed or resource is invalid... require /policies permissions
return POLICIES_AUTHORIZABLE;
}
}
@Override
public Authorizable getAuthorizableFromResource(String resource) {
// parse the resource type
ResourceType resourceType = null;
for (ResourceType type : ResourceType.values()) {
if (resource.equals(type.getValue()) || resource.startsWith(type.getValue() + "/")) {
resourceType = type;
}
}
if (resourceType == null) {
throw new ResourceNotFoundException("Unrecognized resource: " + resource);
}
// if this is a policy or a provenance event resource, there should be another resource type
if (ResourceType.Policy.equals(resourceType) || ResourceType.Data.equals(resourceType) || ResourceType.DataTransfer.equals(resourceType)) {
final ResourceType primaryResourceType = resourceType;
// get the resource type
resource = StringUtils.substringAfter(resource, resourceType.getValue());
for (ResourceType type : ResourceType.values()) {
if (resource.equals(type.getValue()) || resource.startsWith(type.getValue() + "/")) {
resourceType = type;
}
}
if (resourceType == null) {
throw new ResourceNotFoundException("Unrecognized resource: " + resource);
}
// must either be a policy, event, or data transfer
if (ResourceType.Policy.equals(primaryResourceType)) {
return new AccessPolicyAuthorizable(getAccessPolicy(resourceType, resource));
} else if (ResourceType.Data.equals(primaryResourceType)) {
return new DataAuthorizable(getAccessPolicy(resourceType, resource));
} else {
return new DataTransferAuthorizable(getAccessPolicy(resourceType, resource));
}
} else {
return getAccessPolicy(resourceType, resource);
}
}
private Authorizable getAccessPolicy(final ResourceType resourceType, final String resource) {
final String slashComponentId = StringUtils.substringAfter(resource, resourceType.getValue());
if (slashComponentId.startsWith("/")) {
return getAccessPolicyByResource(resourceType, slashComponentId.substring(1));
} else {
return getAccessPolicyByResource(resourceType);
}
}
private Authorizable getAccessPolicyByResource(final ResourceType resourceType, final String componentId) {
Authorizable authorizable = null;
switch (resourceType) {
case ControllerService:
authorizable = getControllerService(componentId).getAuthorizable();
break;
case Funnel:
authorizable = getFunnel(componentId);
break;
case InputPort:
authorizable = getInputPort(componentId);
break;
case Label:
authorizable = getLabel(componentId);
break;
case OutputPort:
authorizable = getOutputPort(componentId);
break;
case Processor:
authorizable = getProcessor(componentId).getAuthorizable();
break;
case ProcessGroup:
authorizable = getProcessGroup(componentId).getAuthorizable();
break;
case RemoteProcessGroup:
authorizable = getRemoteProcessGroup(componentId);
break;
case ReportingTask:
authorizable = getReportingTask(componentId).getAuthorizable();
break;
case Template:
authorizable = getTemplate(componentId);
break;
}
if (authorizable == null) {
throw new IllegalArgumentException("An unexpected type of resource in this policy " + resourceType.getValue());
}
return authorizable;
}
private Authorizable getAccessPolicyByResource(final ResourceType resourceType) {
Authorizable authorizable = null;
switch (resourceType) {
case Controller:
authorizable = getController();
break;
case Counters:
authorizable = getCounters();
break;
case Flow:
authorizable = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getFlowResource();
}
};
break;
case Provenance:
authorizable = getProvenance();
break;
case Proxy:
authorizable = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getProxyResource();
}
};
break;
case Policy:
authorizable = getPolicies();
break;
case Resource:
authorizable = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getResourceResource();
}
};
break;
case SiteToSite:
authorizable = new Authorizable() {
@Override
public Authorizable getParentAuthorizable() {
return null;
}
@Override
public Resource getResource() {
return ResourceFactory.getSiteToSiteResource();
}
};
break;
case System:
authorizable = getSystem();
break;
case Tenant:
authorizable = getTenant();
break;
case RestrictedComponents:
authorizable = getRestrictedComponents();
break;
}
if (authorizable == null) {
throw new IllegalArgumentException("An unexpected type of resource in this policy " + resourceType.getValue());
}
return authorizable;
}
/**
* Creates temporary instances of all processors and controller services found in the specified snippet.
*
* @param snippet snippet
* @param processors processors
* @param controllerServices controller services
*/
private void createTemporaryProcessorsAndControllerServices(final FlowSnippetDTO snippet,
final Set<ComponentAuthorizable> processors,
final Set<ComponentAuthorizable> controllerServices) {
if (snippet == null) {
return;
}
if (snippet.getProcessors() != null) {
snippet.getProcessors().forEach(processor -> {
try {
final BundleCoordinate bundle = BundleUtils.getCompatibleBundle(processor.getType(), processor.getBundle());
processors.add(getConfigurableComponent(processor.getType(), new BundleDTO(bundle.getGroup(), bundle.getId(), bundle.getVersion())));
} catch (final IllegalStateException e) {
// no compatible bundles... no additional auth checks necessary... if created, will be ghosted
}
});
}
if (snippet.getControllerServices() != null) {
snippet.getControllerServices().forEach(controllerService -> {
try {
final BundleCoordinate bundle = BundleUtils.getCompatibleBundle(controllerService.getType(), controllerService.getBundle());
controllerServices.add(getConfigurableComponent(controllerService.getType(), new BundleDTO(bundle.getGroup(), bundle.getId(), bundle.getVersion())));
} catch (final IllegalStateException e) {
// no compatible bundles... no additional auth checks necessary... if created, will be ghosted
}
});
}
if (snippet.getProcessGroups() != null) {
snippet.getProcessGroups().stream().forEach(group -> createTemporaryProcessorsAndControllerServices(group.getContents(), processors, controllerServices));
}
}
@Override
public Authorizable getTemplate(String id) {
return templateDAO.getTemplate(id);
}
@Override
public TemplateContentsAuthorizable getTemplateContents(final FlowSnippetDTO snippet) {
// templates are immutable so we can pre-compute all encapsulated processors and controller services
final Set<ComponentAuthorizable> processors = new HashSet<>();
final Set<ComponentAuthorizable> controllerServices = new HashSet<>();
// find all processors and controller services
createTemporaryProcessorsAndControllerServices(snippet, processors, controllerServices);
return new TemplateContentsAuthorizable() {
@Override
public Set<ComponentAuthorizable> getEncapsulatedProcessors() {
return processors;
}
@Override
public Set<ComponentAuthorizable> getEncapsulatedControllerServices() {
return controllerServices;
}
};
}
@Override
public Authorizable getLocalConnectable(String id) {
final ProcessGroup group = processGroupDAO.getProcessGroup(controllerFacade.getRootGroupId());
final Connectable connectable = group.findLocalConnectable(id);
if (connectable == null) {
throw new ResourceNotFoundException("Unable to find component with id " + id);
}
return connectable;
}
@Override
public Authorizable getRestrictedComponents() {
return RESTRICTED_COMPONENTS_AUTHORIZABLE;
}
@Override
public Authorizable getSystem() {
return SYSTEM_AUTHORIZABLE;
}
/**
* ComponentAuthorizable for a ConfigurableComponent. This authorizable is intended only to be used when
* creating new components.
*/
private static class ConfigurableComponentAuthorizable implements ComponentAuthorizable {
private final ConfigurableComponent configurableComponent;
public ConfigurableComponentAuthorizable(final ConfigurableComponent configurableComponent) {
this.configurableComponent = configurableComponent;
}
@Override
public Authorizable getAuthorizable() {
throw new UnsupportedOperationException();
}
@Override
public boolean isRestricted() {
return configurableComponent.getClass().isAnnotationPresent(Restricted.class);
}
@Override
public String getValue(PropertyDescriptor propertyDescriptor) {
return null;
}
@Override
public PropertyDescriptor getPropertyDescriptor(String propertyName) {
return configurableComponent.getPropertyDescriptor(propertyName);
}
@Override
public List<PropertyDescriptor> getPropertyDescriptors() {
return configurableComponent.getPropertyDescriptors();
}
@Override
public void cleanUpResources() {
ExtensionManager.removeInstanceClassLoader(configurableComponent.getIdentifier());
}
}
/**
* ComponentAuthorizable for a ProcessorNode.
*/
private static class ProcessorComponentAuthorizable implements ComponentAuthorizable {
private final ProcessorNode processorNode;
public ProcessorComponentAuthorizable(ProcessorNode processorNode) {
this.processorNode = processorNode;
}
@Override
public Authorizable getAuthorizable() {
return processorNode;
}
@Override
public boolean isRestricted() {
return processorNode.isRestricted();
}
@Override
public String getValue(PropertyDescriptor propertyDescriptor) {
return processorNode.getProperty(propertyDescriptor);
}
@Override
public PropertyDescriptor getPropertyDescriptor(String propertyName) {
return processorNode.getPropertyDescriptor(propertyName);
}
@Override
public List<PropertyDescriptor> getPropertyDescriptors() {
return processorNode.getPropertyDescriptors();
}
@Override
public void cleanUpResources() {
ExtensionManager.removeInstanceClassLoader(processorNode.getIdentifier());
}
}
/**
* ComponentAuthorizable for a ControllerServiceNode.
*/
private static class ControllerServiceComponentAuthorizable implements ComponentAuthorizable {
private final ControllerServiceNode controllerServiceNode;
public ControllerServiceComponentAuthorizable(ControllerServiceNode controllerServiceNode) {
this.controllerServiceNode = controllerServiceNode;
}
@Override
public Authorizable getAuthorizable() {
return controllerServiceNode;
}
@Override
public boolean isRestricted() {
return controllerServiceNode.isRestricted();
}
@Override
public String getValue(PropertyDescriptor propertyDescriptor) {
return controllerServiceNode.getProperty(propertyDescriptor);
}
@Override
public PropertyDescriptor getPropertyDescriptor(String propertyName) {
return controllerServiceNode.getControllerServiceImplementation().getPropertyDescriptor(propertyName);
}
@Override
public List<PropertyDescriptor> getPropertyDescriptors() {
return controllerServiceNode.getControllerServiceImplementation().getPropertyDescriptors();
}
@Override
public void cleanUpResources() {
ExtensionManager.removeInstanceClassLoader(controllerServiceNode.getIdentifier());
}
}
/**
* ComponentAuthorizable for a ProcessorNode.
*/
private static class ReportingTaskComponentAuthorizable implements ComponentAuthorizable {
private final ReportingTaskNode reportingTaskNode;
public ReportingTaskComponentAuthorizable(ReportingTaskNode reportingTaskNode) {
this.reportingTaskNode = reportingTaskNode;
}
@Override
public Authorizable getAuthorizable() {
return reportingTaskNode;
}
@Override
public boolean isRestricted() {
return reportingTaskNode.isRestricted();
}
@Override
public String getValue(PropertyDescriptor propertyDescriptor) {
return reportingTaskNode.getProperty(propertyDescriptor);
}
@Override
public PropertyDescriptor getPropertyDescriptor(String propertyName) {
return reportingTaskNode.getReportingTask().getPropertyDescriptor(propertyName);
}
@Override
public List<PropertyDescriptor> getPropertyDescriptors() {
return reportingTaskNode.getReportingTask().getPropertyDescriptors();
}
@Override
public void cleanUpResources() {
ExtensionManager.removeInstanceClassLoader(reportingTaskNode.getIdentifier());
}
}
private static class StandardProcessGroupAuthorizable implements ProcessGroupAuthorizable {
private final ProcessGroup processGroup;
public StandardProcessGroupAuthorizable(ProcessGroup processGroup) {
this.processGroup = processGroup;
}
@Override
public Authorizable getAuthorizable() {
return processGroup;
}
@Override
public Set<ComponentAuthorizable> getEncapsulatedProcessors() {
return processGroup.findAllProcessors().stream().map(
processorNode -> new ProcessorComponentAuthorizable(processorNode)).collect(Collectors.toSet());
}
@Override
public Set<ConnectionAuthorizable> getEncapsulatedConnections() {
return processGroup.findAllConnections().stream().map(
connection -> new StandardConnectionAuthorizable(connection)).collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getEncapsulatedInputPorts() {
return processGroup.findAllInputPorts().stream().collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getEncapsulatedOutputPorts() {
return processGroup.findAllOutputPorts().stream().collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getEncapsulatedFunnels() {
return processGroup.findAllFunnels().stream().collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getEncapsulatedLabels() {
return processGroup.findAllLabels().stream().collect(Collectors.toSet());
}
@Override
public Set<ProcessGroupAuthorizable> getEncapsulatedProcessGroups() {
return processGroup.findAllProcessGroups().stream().map(
group -> new StandardProcessGroupAuthorizable(group)).collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getEncapsulatedRemoteProcessGroups() {
return processGroup.findAllRemoteProcessGroups().stream().collect(Collectors.toSet());
}
@Override
public Set<Authorizable> getEncapsulatedTemplates() {
return processGroup.findAllTemplates().stream().collect(Collectors.toSet());
}
@Override
public Set<ComponentAuthorizable> getEncapsulatedControllerServices() {
return processGroup.findAllControllerServices().stream().map(
controllerServiceNode -> new ControllerServiceComponentAuthorizable(controllerServiceNode)).collect(Collectors.toSet());
}
}
private static class StandardConnectionAuthorizable implements ConnectionAuthorizable {
private final Connection connection;
public StandardConnectionAuthorizable(Connection connection) {
this.connection = connection;
}
@Override
public Authorizable getAuthorizable() {
return connection;
}
@Override
public Connectable getSource() {
return connection.getSource();
}
@Override
public Authorizable getSourceData() {
return new DataAuthorizable(connection.getSourceAuthorizable());
}
@Override
public Connectable getDestination() {
return connection.getDestination();
}
@Override
public Authorizable getDestinationData() {
return new DataAuthorizable(connection.getDestinationAuthorizable());
}
@Override
public ProcessGroup getParentGroup() {
return connection.getProcessGroup();
}
}
public void setProcessorDAO(ProcessorDAO processorDAO) {
this.processorDAO = processorDAO;
}
public void setProcessGroupDAO(ProcessGroupDAO processGroupDAO) {
this.processGroupDAO = processGroupDAO;
}
public void setRemoteProcessGroupDAO(RemoteProcessGroupDAO remoteProcessGroupDAO) {
this.remoteProcessGroupDAO = remoteProcessGroupDAO;
}
public void setLabelDAO(LabelDAO labelDAO) {
this.labelDAO = labelDAO;
}
public void setFunnelDAO(FunnelDAO funnelDAO) {
this.funnelDAO = funnelDAO;
}
public void setSnippetDAO(SnippetDAO snippetDAO) {
this.snippetDAO = snippetDAO;
}
public void setInputPortDAO(PortDAO inputPortDAO) {
this.inputPortDAO = inputPortDAO;
}
public void setOutputPortDAO(PortDAO outputPortDAO) {
this.outputPortDAO = outputPortDAO;
}
public void setConnectionDAO(ConnectionDAO connectionDAO) {
this.connectionDAO = connectionDAO;
}
public void setControllerServiceDAO(ControllerServiceDAO controllerServiceDAO) {
this.controllerServiceDAO = controllerServiceDAO;
}
public void setReportingTaskDAO(ReportingTaskDAO reportingTaskDAO) {
this.reportingTaskDAO = reportingTaskDAO;
}
public void setTemplateDAO(TemplateDAO templateDAO) {
this.templateDAO = templateDAO;
}
public void setAccessPolicyDAO(AccessPolicyDAO accessPolicyDAO) {
this.accessPolicyDAO = accessPolicyDAO;
}
public void setControllerFacade(ControllerFacade controllerFacade) {
this.controllerFacade = controllerFacade;
}
}
| |
/**********************************************************************************
Copyright (c) 2018 Apereo Foundation
Licensed under the Educational Community License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/ecl2
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********************************************************************************/
package org.sakaiproject.jsf2.renderer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.fileupload.FileItem;
import org.sakaiproject.jsf2.util.RendererUtil;
public class InputFileUploadRenderer extends Renderer
{
private static final String ID_INPUT_ELEMENT = ".uploadId";
private static final String ID_HIDDEN_ELEMENT = ".hiddenId";
private static final String ATTR_REQUEST_DECODED = ".decoded";
private static final String[] PASSTHROUGH_ATTRIBUTES = { "accept", "accesskey",
"align", "disabled", "maxlength", "readonly", "size", "style", "tabindex" };
public static final String ATTR_UPLOADS_DONE = "sakai.uploads.done";
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException
{
if (!component.isRendered()) return;
ResponseWriter writer = context.getResponseWriter();
String clientId = component.getClientId(context);
//HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
// check that the structure of the form is valid
boolean atDecodeTime = false;
String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
if (errorMessage != null)
{
addFacesMessage(context, clientId, errorMessage);
}
// output field that allows user to upload a file
writer.startElement("input", null);
writer.writeAttribute("type", "file", null);
writer.writeAttribute("name", clientId + ID_INPUT_ELEMENT, null);
String styleClass = (String) RendererUtil.getAttribute(context, component, "styleClass");
if (styleClass != null) writer.writeAttribute("class", styleClass, null);
boolean writeNullPassthroughAttributes = false;
RendererUtil.writePassthroughAttributes(PASSTHROUGH_ATTRIBUTES,
writeNullPassthroughAttributes, context, component);
writer.endElement("input");
// another comment
// output hidden field that helps test that the filter is working right
writer.startElement("input", null);
writer.writeAttribute("type", "hidden", null);
writer.writeAttribute("name", clientId + ID_HIDDEN_ELEMENT, null);
writer.writeAttribute("value", "filter_is_functioning_properly", null);
writer.endElement("input");
}
public void decode(FacesContext context, UIComponent comp)
{
UIInput component = (UIInput) comp;
if (!component.isRendered()) return;
ExternalContext external = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) external.getRequest();
String clientId = component.getClientId(context);
String directory = (String) RendererUtil.getAttribute(context, component, "directory");
// mark that this component has had decode() called during request
// processing
request.setAttribute(clientId + ATTR_REQUEST_DECODED, "true");
// check for user errors and developer errors
boolean atDecodeTime = true;
String errorMessage = checkForErrors(context, component, clientId, atDecodeTime);
if (errorMessage != null)
{
addFacesMessage(context, clientId, errorMessage);
return;
}
// get the file item
FileItem item = getFileItem(context, component);
if (item.getName() == null || item.getName().length() == 0)
{
if (component.isRequired())
{
addFacesMessage(context, clientId, "Please specify a file.");
component.setValid(false);
}
return;
}
if (directory == null || directory.length() == 0)
{
// just passing on the FileItem as the value of the component, without persisting it.
component.setSubmittedValue(item);
}
else
{
// persisting to a permenent file in a directory.
// pass on the server-side filename as the value of the component.
File dir = new File(directory);
String filename = item.getName();
filename = filename.replace('\\','/'); // replaces Windows path seperator character "\" with "/"
filename = filename.substring(filename.lastIndexOf("/")+1);
File persistentFile = new File(dir, filename);
try
{
item.write(persistentFile);
component.setSubmittedValue(persistentFile.getPath());
}
catch (Exception ex)
{
throw new FacesException(ex);
}
}
}
/**
* Check for errors (both developer errors and user errors) - return a
* user-friendly error message describing the error, or null if there are no
* errors.
*/
private static String checkForErrors(FacesContext context, UIComponent component,
String clientId, boolean atDecodeTime)
{
ExternalContext external = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) external.getRequest();
UIForm form = null;
try
{
form = getForm(component);
}
catch (IllegalArgumentException e)
{
// there are more than one nested form - thats not OK!
return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form. Nested forms confuse the browser.";
}
if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype")))
{
return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag.";
}
// check tag attributes
String directory = (String) RendererUtil.getAttribute(context, component, "directory");
if (directory != null && directory.length() != 0)
{
// the tag is configured to persist the uploaded files to a directory.
// check that the specified directory exists, and is writeable
File dir = new File(directory);
if (!dir.isDirectory() || !dir.exists())
{
return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n"
+ "Check the permissions on directory:\n"
+ dir;
}
}
FileItem item = getFileItem(context, component);
boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null;
String requestFilterStatus = (String) request.getAttribute("upload.status");
Object requestFilterUploadLimit = request.getAttribute("upload.limit");
Exception requestFilterException = (Exception) request.getAttribute("upload.exception");
boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED));
if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime)
{
// decode() was already called on the request, and we're now at encode() time - so don't do further error checking
// as the FileItem may no longer be valid.
return null;
}
// at this point, if its not a multipart request, it doesn't have a file and there isn't an error.
if (!isMultipartRequest) return null;
// check for user errors
if ("exception".equals(requestFilterStatus))
{
return "An error occured while processing the uploaded file. The error was:\n"
+ requestFilterException;
}
else if ("size_limit_exceeded".equals(requestFilterStatus))
{
// the user tried to upload too large a file
return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded.";
}
else if (item == null || item.getName() == null || item.getName().length() == 0)
{
// The file item will be null if the component was previously not rendered.
return null;
}
else if (item.getSize() == 0)
{
return "The filename '"+item.getName()+"' is invalid. Please select a valid file.";
}
if (!wasMultipartRequestFullyParsed)
{
return "An error occured while processing the uploaded file. The error was:\n"
+ "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n"
+ "Check that the Sakai RequestFilter is properly configured in web.xml.";
}
if (item.getName().indexOf("..") >= 0)
{
return "The filename '"+item.getName()+"' is invalid. Please select a valid file.";
}
// everything checks out fine! The upload was parsed, and a FileItem
// exists with a filename and non-zero length
return null;
}
/**
* Return the FileItem (if present) for the given component. Subclasses
* of this Renderer could get the FileItem in a different way.
* First, try getting it from the request attributes (Sakai style). Then
* try getting it from a method called getFileItem() on the HttpServletRequest
* (unwrapping the request if necessary).
*/
private static FileItem getFileItem(FacesContext context, UIComponent component)
{
String clientId = component.getClientId(context);
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
FileItem item = null;
String fieldName = clientId + ID_INPUT_ELEMENT;
// first try just getting it from the request attributes,
// where the Sakai RequestFilter puts it.
item = (FileItem) request.getAttribute(fieldName);
if (item != null) return item;
// For custom filter compatibility (MyFaces for example),
// walk up the HttpServletRequestWrapper chain looking for a getFileItem() method.
while (request != null)
{
// call the getFileItem() method by reflection, so as to not introduce a dependency
// on MyFaces, and so the wrapper class that has getFileItem() doesn't have to
// implement an interface (as long as it has the right method signature it'll work).
try
{
Class reqClass = request.getClass();
Method getFileItemMethod = reqClass.getMethod("getFileItem", new Class[] {String.class});
Object returned = getFileItemMethod.invoke(request, new Object[] {fieldName});
if (returned instanceof FileItem) return (FileItem) returned;
}
catch (NoSuchMethodException nsme)
{
}
catch (InvocationTargetException ite)
{
}
catch (IllegalArgumentException iae)
{
}
catch (IllegalAccessException iaxe)
{
}
// trace up the request wrapper classes, looking for a getFileItem() method
if (request instanceof HttpServletRequestWrapper)
{
request = (HttpServletRequest) ((HttpServletRequestWrapper) request).getRequest();
}
else
{
request = null;
}
}
return null;
}
private static void addFacesMessage(FacesContext context, String clientId,
String message)
{
context.addMessage(clientId, new FacesMessage(FacesMessage.SEVERITY_ERROR,
message, message));
}
/**
* get containing UIForm from component hierarchy.
* @throws IllegalArgumentException If there is more than one enclosing form - only one form is allowed!
*/
private static UIForm getForm(UIComponent component)
throws IllegalArgumentException
{
UIForm ret = null;
while (component != null)
{
if (component instanceof UIForm)
{
if (ret != null)
{
// Cannot have a doubly-nested form!
throw new IllegalArgumentException();
}
ret = (UIForm) component;
}
component = component.getParent();
}
return ret;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.openstack.keystone.v2_0.domain;
import static com.google.common.base.Preconditions.checkNotNull;
import java.beans.ConstructorProperties;
import java.util.Set;
import org.jclouds.javax.annotation.Nullable;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.ImmutableSet;
/**
* An OpenStack service, such as Compute (Nova), Object Storage (Swift), or Image Service (Glance).
* A service provides one or more endpoints through which users can access resources and perform
* (presumably useful) operations.
*
* @see <a href="http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html"
/>
*/
public class Service extends ForwardingSet<Endpoint> {
public static Builder<?> builder() {
return new ConcreteBuilder();
}
public Builder<?> toBuilder() {
return new ConcreteBuilder().fromService(this);
}
public abstract static class Builder<T extends Builder<T>> {
protected abstract T self();
protected String id;
protected String type;
protected String name;
protected String description;
protected ImmutableSet.Builder<Endpoint> endpoints = ImmutableSet.<Endpoint>builder();
/**
* @see Service#getId()
*/
public T id(String id) {
this.id = id;
return self();
}
/**
* @see Service#getType()
*/
public T type(String type) {
this.type = type;
return self();
}
/**
* @see Service#getName()
*/
public T name(String name) {
this.name = name;
return self();
}
/**
* @see Service#getDescription()
*/
public T description(String description) {
this.description = description;
return self();
}
/**
* @see Service#delegate()
*/
public T endpoint(Endpoint endpoint) {
this.endpoints.add(endpoint);
return self();
}
/**
* @see Service#delegate()
*/
public T endpoints(Iterable<Endpoint> endpoints) {
this.endpoints.addAll(endpoints);
return self();
}
public Service build() {
return new Service(id, type, name, description, endpoints.build());
}
public T fromService(Service in) {
return this
.id(in.getId())
.type(in.getType())
.name(in.getName())
.description(in.getDescription())
.endpoints(in);
}
}
private static class ConcreteBuilder extends Builder<ConcreteBuilder> {
@Override
protected ConcreteBuilder self() {
return this;
}
}
private final String id;
private final String type;
private final String name;
private final String description;
private final Set<Endpoint> endpoints;
@ConstructorProperties({
"id", "type", "name", "description", "endpoints"
})
protected Service(@Nullable String id, String type, String name, @Nullable String description, @Nullable Set<Endpoint> endpoints) {
this.id = id;
this.type = checkNotNull(type, "type");
this.name = checkNotNull(name, "name");
this.description = description;
this.endpoints = endpoints == null ? ImmutableSet.<Endpoint>of() : ImmutableSet.copyOf(endpoints);
}
/**
* When providing an ID, it is assumed that the service exists in the current OpenStack deployment
*
* @return the id of the service in the current OpenStack deployment
*/
@Nullable
public String getId() {
return this.id;
}
/**
* such as {@code compute} (Nova), {@code object-store} (Swift), or {@code image} (Glance)
*
* @return the type of the service in the current OpenStack deployment
*/
public String getType() {
return this.type;
}
/**
* @return the name of the service
*/
public String getName() {
return this.name;
}
/**
* @return the description of the service
*/
public String getDescription() {
return this.description;
}
@Override
public int hashCode() {
return Objects.hashCode(id, type, name, description, endpoints);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Service that = Service.class.cast(obj);
return Objects.equal(this.id, that.id)
&& Objects.equal(this.type, that.type)
&& Objects.equal(this.name, that.name)
&& Objects.equal(this.description, that.description)
&& Objects.equal(this.endpoints, that.endpoints);
}
protected ToStringHelper string() {
return Objects.toStringHelper(this).omitNullValues()
.add("id", id).add("type", type).add("name", name)
.add("description", description).add("endpoints", endpoints);
}
@Override
public String toString() {
return string().toString();
}
@Override
protected Set<Endpoint> delegate() {
return endpoints;
}
}
| |
/**
* Copyright 2011-2015 Yahoo Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.omid.transaction;
import static com.yahoo.omid.transaction.HBaseTransactionManager.SHADOW_CELL_SUFFIX;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellComparator;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
public class CellUtils {
private static final Logger LOG = LoggerFactory.getLogger(CellUtils.class);
/**
* Utility interface to get rid of the dependency on HBase server package
*/
public interface CellGetter {
public Result get(Get get) throws IOException;
}
/**
* Returns true if the particular cell passed exists in the datastore.
* @param row
* @param family
* @param qualifier
* @param version
* @param cellGetter
* @return true if the cell specified exists. false otherwise
* @throws IOException
*/
public static boolean hasCell(byte[] row,
byte[] family,
byte[] qualifier,
long version,
CellGetter cellGetter)
throws IOException {
Get get = new Get(row);
get.addColumn(family, qualifier);
get.setTimeStamp(version);
Result result = cellGetter.get(get);
return result.containsColumn(family, qualifier);
}
/**
* Returns true if the particular cell passed has a corresponding shadow cell in the datastore.
* @param row
* @param family
* @param qualifier
* @param version
* @param cellGetter
* @return true if it has a shadow cell. false otherwise.
* @throws IOException
*/
public static boolean hasShadowCell(byte[] row,
byte[] family,
byte[] qualifier,
long version,
CellGetter cellGetter) throws IOException {
return hasCell(row, family, addShadowCellSuffix(qualifier),
version, cellGetter);
}
/**
* Builds a new qualifier composed of the HBase qualifier
* passed suffixed with the shadow cell suffix.
* @param qualifierArray
* the qualifier to be suffixed
* @param qualOffset
* the offset where the qualifier starts
* @param qualLength
* the qualifier length
* @return the suffixed qualifier
*/
public static byte[] addShadowCellSuffix(byte[] qualifierArray, int qualOffset, int qualLength) {
byte[] result = new byte[qualLength + SHADOW_CELL_SUFFIX.length];
System.arraycopy(qualifierArray, qualOffset, result, 0, qualLength);
System.arraycopy(SHADOW_CELL_SUFFIX, 0, result, qualLength, SHADOW_CELL_SUFFIX.length);
return result;
}
/**
* Builds a new qualifier composed of the HBase qualifier passed suffixed
* with the shadow cell suffix.
* Contains a reduced signature to avoid boilerplate code in client side.
* @param qualifier
* the qualifier to be suffixed
* @return the suffixed qualifier
*/
public static byte[] addShadowCellSuffix(byte[] qualifier) {
return addShadowCellSuffix(qualifier, 0, qualifier.length);
}
/**
* Builds a new qualifier removing the shadow cell suffix from the
* passed HBase qualifier.
* @param qualifier
* the qualifier to remove the suffix from
* @param qualOffset
* the offset where the qualifier starts
* @param qualLength
* the qualifier length
* @return the new qualifier without the suffix
*/
public static byte[] removeShadowCellSuffix(byte[] qualifier, int qualOffset, int qualLength) {
if (endsWith(qualifier, qualOffset, qualLength, SHADOW_CELL_SUFFIX)) {
return Arrays.copyOfRange(qualifier,
qualOffset,
qualOffset + (qualLength - SHADOW_CELL_SUFFIX.length));
}
throw new IllegalArgumentException(
"Can't find shadow cell suffix in qualifier "
+ Bytes.toString(qualifier));
}
/**
* Returns the qualifier length removing the shadow cell suffix. In case
* that que suffix is not found, just returns the length of the qualifier
* passed.
* @param qualifier
* the qualifier to remove the suffix from
* @param qualOffset
* the offset where the qualifier starts
* @param qualLength
* the qualifier length
* @return the qualifier length without the suffix
*/
public static int qualifierLengthFromShadowCellQualifier(byte[] qualifier, int qualOffset, int qualLength) {
if (endsWith(qualifier, qualOffset, qualLength, SHADOW_CELL_SUFFIX)) {
return qualLength - SHADOW_CELL_SUFFIX.length;
}
return qualLength;
}
/**
* Complement to matchingQualifier() methods in HBase's CellUtil.class
* @param left
* the cell to compare the qualifier
* @param qualArray
* the explicit qualifier array passed
* @param qualOffset
* the explicit qualifier offset passed
* @param qualLen
* the explicit qualifier length passed
* @return whether the qualifiers are equal or not
*/
public static boolean matchingQualifier(final Cell left, final byte[] qualArray, int qualOffset, int qualLen) {
return Bytes.equals(left.getQualifierArray(), left.getQualifierOffset(), left.getQualifierLength(),
qualArray, qualOffset, qualLen);
}
/**
* Check that the cell passed meets the requirements for a valid cell
* identifier with Omid. Basically, users can't:
* 1) specify a timestamp
* 2) use a particular suffix in the qualifier
* @param cell
* @param startTimestamp
*/
public static void validateCell(Cell cell, long startTimestamp) {
// Throw exception if timestamp is set by the user
if (cell.getTimestamp() != HConstants.LATEST_TIMESTAMP
&& cell.getTimestamp() != startTimestamp) {
throw new IllegalArgumentException(
"Timestamp not allowed in transactional user operations");
}
// Throw exception if using a non-allowed qualifier
if (isShadowCell(cell)) {
throw new IllegalArgumentException(
"Reserved string used in column qualifier");
}
}
/**
* Returns whether a cell contains a qualifier that is a shadow cell
* column qualifier or not.
* @param cell
* the cell to check if contains the shadow cell qualifier
* @return whether the cell passed contains a shadow cell qualifier or not
*/
public static boolean isShadowCell(Cell cell) {
byte[] qualifier = cell.getQualifierArray();
int qualOffset = cell.getQualifierOffset();
int qualLength = cell.getQualifierLength();
return endsWith(qualifier, qualOffset, qualLength, SHADOW_CELL_SUFFIX);
}
private static boolean endsWith(byte[] value, int offset, int length, byte[] suffix) {
if (length <= suffix.length) {
return false;
}
int suffixOffset = offset + length - suffix.length;
int result = Bytes.compareTo(value, suffixOffset, suffix.length,
suffix, 0, suffix.length);
return result == 0 ? true : false;
}
/**
* Returns if a cell is marked as a tombstone.
* @param cell
* the cell to check
* @return whether the cell is marked as a tombstone or not
*/
public static boolean isTombstone(Cell cell) {
return CellUtil.matchingValue(cell, TTable.DELETE_TOMBSTONE);
}
/**
* Returns a new shadow cell created from a particular cell.
* @param cell
* the cell to reconstruct the shadow cell from.
* @param shadowCellValue
* the value for the new shadow cell created
* @return the brand-new shadow cell
*/
public static Cell buildShadowCellFromCell(Cell cell, byte[] shadowCellValue) {
byte[] shadowCellQualifier = addShadowCellSuffix(cell.getQualifierArray(),
cell.getQualifierOffset(),
cell.getQualifierLength());
return new KeyValue(
cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength(),
shadowCellQualifier, 0, shadowCellQualifier.length,
cell.getTimestamp(), KeyValue.Type.codeToType(cell.getTypeByte()),
shadowCellValue, 0, shadowCellValue.length);
}
/**
* Analyzes a list of cells, associating the corresponding shadow cell if present.
*
* @param cells
* the list of cells to classify
* @return a sorted map associating each cell with its shadow cell
*/
public static SortedMap<Cell, Optional<Cell>> mapCellsToShadowCells(List<Cell> cells) {
SortedMap<Cell, Optional<Cell>> cellToShadowCellMap
= new TreeMap<Cell, Optional<Cell>>(new CellComparator());
Map<CellId, Cell> cellIdToCellMap = new HashMap<CellId, Cell>();
for (Cell cell : cells) {
if (!isShadowCell(cell)) {
CellId key = new CellId(cell, false);
if (cellIdToCellMap.containsKey(key)) {
// Get the current cell and compare the values
Cell storedCell = cellIdToCellMap.get(key);
if (CellUtil.matchingValue(cell, storedCell)) {
// TODO: Should we check also here the MVCC and swap if its greater???
continue; // Values are the same, ignore
} else {
if (cell.getMvccVersion() > storedCell.getMvccVersion()) { // Swap values
Optional<Cell> previousValue = cellToShadowCellMap.remove(storedCell);
Preconditions.checkNotNull(previousValue, "Should contain an Optional<Cell> value");
cellIdToCellMap.put(key, cell);
cellToShadowCellMap.put(cell, previousValue);
} else {
LOG.warn("Cell {} with an earlier MVCC found. Ignoring...", cell);
continue;
}
}
} else {
cellIdToCellMap.put(key, cell);
cellToShadowCellMap.put(cell, Optional.<Cell> absent());
}
} else {
CellId key = new CellId(cell, true);
if (cellIdToCellMap.containsKey(key)) {
Cell originalCell = cellIdToCellMap.get(key);
cellToShadowCellMap.put(originalCell, Optional.of(cell));
} else {
LOG.trace("Map does not contain key {}", key);
}
}
}
return cellToShadowCellMap;
}
private static class CellId {
private static final int MIN_BITS = 32;
private final Cell cell;
private final boolean isShadowCell;
public CellId(Cell cell, boolean isShadowCell) {
this.cell = cell;
this.isShadowCell = isShadowCell;
}
Cell getCell() {
return cell;
}
boolean isShadowCell() {
return isShadowCell;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof CellId))
return false;
CellId otherCellId = (CellId) o;
Cell otherCell = otherCellId.getCell();
// Row comparison
if (!CellUtil.matchingRow(otherCell, cell)) {
return false;
}
// Family comparison
if (!CellUtil.matchingFamily(otherCell, cell)) {
return false;
}
// Qualifier comparison
if (isShadowCell()) {
int qualifierLength = qualifierLengthFromShadowCellQualifier(cell.getQualifierArray(),
cell.getQualifierOffset(),
cell.getQualifierLength());
if (!matchingQualifier(otherCell,
cell.getQualifierArray(), cell.getQualifierOffset(), qualifierLength)) {
return false;
}
} else {
if (!CellUtil.matchingQualifier(otherCell, cell)) {
return false;
}
}
// Timestamp comparison
if(otherCell.getTimestamp() != cell.getTimestamp()) {
return false;
}
return true;
}
@Override
public int hashCode() {
Hasher hasher = Hashing.goodFastHash(MIN_BITS).newHasher();
hasher.putBytes(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
hasher.putBytes(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
int qualifierLength = cell.getQualifierLength();
if(isShadowCell()) { // Update qualifier length when qualifier is shadow cell
qualifierLength = qualifierLengthFromShadowCellQualifier(cell.getQualifierArray(),
cell.getQualifierOffset(),
cell.getQualifierLength());
}
hasher.putBytes(cell.getQualifierArray(), cell.getQualifierOffset(), qualifierLength);
hasher.putLong(cell.getTimestamp());
return hasher.hash().asInt();
}
@Override
public String toString() {
ToStringHelper helper = Objects.toStringHelper(this);
helper.add("row", Bytes.toStringBinary(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
helper.add("family", Bytes.toString(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()));
helper.add("is shadow cell?", isShadowCell);
helper.add("qualifier",
Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()));
if(isShadowCell()) {
int qualifierLength = qualifierLengthFromShadowCellQualifier(cell.getQualifierArray(),
cell.getQualifierOffset(),
cell.getQualifierLength());
helper.add("qualifier whithout shadow cell suffix",
Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), qualifierLength));
}
helper.add("ts", cell.getTimestamp());
return helper.toString();
}
}
static class CellInfo {
private final Cell cell;
private final Cell shadowCell;
private final long timestamp;
CellInfo(Cell cell, Cell shadowCell) {
assert (cell != null && shadowCell != null);
assert(cell.getTimestamp() == shadowCell.getTimestamp());
this.cell = cell;
this.shadowCell = shadowCell;
this.timestamp = cell.getTimestamp();
}
Cell getCell() {
return cell;
}
Cell getShadowCell() {
return shadowCell;
}
long getTimestamp() {
return timestamp;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("ts", timestamp)
.add("cell", cell)
.add("shadow cell", shadowCell)
.toString();
}
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.util.io.storage;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.util.io.ByteArraySequence;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.PagePool;
import com.intellij.util.io.UnsyncByteArrayInputStream;
import javax.annotation.Nonnull;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.*;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class RefCountingStorage extends AbstractStorage {
private final Map<Integer, Future<?>> myPendingWriteRequests = ContainerUtil.newConcurrentMap();
private int myPendingWriteRequestsSize;
private final ExecutorService myPendingWriteRequestsExecutor = createExecutor();
@Nonnull
protected ExecutorService createExecutor() {
return new ThreadPoolExecutor(1, 1, Long.MAX_VALUE, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(), ConcurrencyUtil
.newNamedThreadFactory("RefCountingStorage write content helper"));
}
private final boolean myDoNotZipCaches;
private static final int MAX_PENDING_WRITE_SIZE = 20 * 1024 * 1024;
public RefCountingStorage(String path) throws IOException {
this(path, CapacityAllocationPolicy.DEFAULT);
}
public RefCountingStorage(String path, CapacityAllocationPolicy capacityAllocationPolicy) throws IOException {
this(path, capacityAllocationPolicy, Boolean.valueOf(System.getProperty("idea.doNotZipCaches")).booleanValue());
}
public RefCountingStorage(String path, CapacityAllocationPolicy capacityAllocationPolicy, boolean doNotZipCaches) throws IOException {
super(path, capacityAllocationPolicy);
myDoNotZipCaches = doNotZipCaches;
}
@Override
public DataInputStream readStream(int record) throws IOException {
if (myDoNotZipCaches) return super.readStream(record);
BufferExposingByteArrayOutputStream stream = internalReadStream(record);
return new DataInputStream(new UnsyncByteArrayInputStream(stream.getInternalBuffer(), 0, stream.size()));
}
@Override
protected byte[] readBytes(int record) throws IOException {
if (myDoNotZipCaches) return super.readBytes(record);
return internalReadStream(record).toByteArray();
}
private BufferExposingByteArrayOutputStream internalReadStream(int record) throws IOException {
waitForPendingWriteForRecord(record);
byte[] result;
synchronized (myLock) {
result = super.readBytes(record);
}
InflaterInputStream in = new CustomInflaterInputStream(result);
try {
final BufferExposingByteArrayOutputStream outputStream = new BufferExposingByteArrayOutputStream();
StreamUtil.copyStreamContent(in, outputStream);
return outputStream;
}
finally {
in.close();
}
}
private static class CustomInflaterInputStream extends InflaterInputStream {
public CustomInflaterInputStream(byte[] compressedData) {
super(new UnsyncByteArrayInputStream(compressedData), new Inflater(), 1);
// force to directly use compressed data, this ensures less round trips with native extraction code and copy streams
this.buf = compressedData;
this.len = -1;
}
@Override
protected void fill() throws IOException {
if (len >= 0) throw new EOFException();
len = buf.length;
inf.setInput(buf, 0, len);
}
@Override
public void close() throws IOException {
super.close();
inf.end(); // custom inflater need explicit dispose
}
}
private void waitForPendingWriteForRecord(int record) {
Future<?> future = myPendingWriteRequests.get(record);
if (future != null) {
try {
future.get();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
protected void appendBytes(int record, ByteArraySequence bytes) throws IOException {
throw new IncorrectOperationException("Appending is not supported");
}
@Override
public void writeBytes(final int record, final ByteArraySequence bytes, final boolean fixedSize) throws IOException {
if (myDoNotZipCaches) {
super.writeBytes(record, bytes, fixedSize);
return;
}
waitForPendingWriteForRecord(record);
synchronized (myLock) {
myPendingWriteRequestsSize += bytes.getLength();
if (myPendingWriteRequestsSize > MAX_PENDING_WRITE_SIZE) {
zipAndWrite(bytes, record, fixedSize);
} else {
myPendingWriteRequests.put(record, myPendingWriteRequestsExecutor.submit(new Callable<Object>() {
@Override
public Object call() throws IOException {
zipAndWrite(bytes, record, fixedSize);
return null;
}
}));
}
}
}
private void zipAndWrite(ByteArraySequence bytes, int record, boolean fixedSize) throws IOException {
BufferExposingByteArrayOutputStream s = new BufferExposingByteArrayOutputStream();
DeflaterOutputStream out = new DeflaterOutputStream(s);
try {
out.write(bytes.getBytes(), bytes.getOffset(), bytes.getLength());
}
finally {
out.close();
}
synchronized (myLock) {
doWrite(record, fixedSize, s);
myPendingWriteRequestsSize -= bytes.getLength();
myPendingWriteRequests.remove(record);
}
}
private void doWrite(int record, boolean fixedSize, BufferExposingByteArrayOutputStream s) throws IOException {
super.writeBytes(record, new ByteArraySequence(s.getInternalBuffer(), 0, s.size()), fixedSize);
}
@Override
protected AbstractRecordsTable createRecordsTable(PagePool pool, File recordsFile) throws IOException {
return new RefCountingRecordsTable(recordsFile, pool);
}
public int acquireNewRecord() throws IOException {
synchronized (myLock) {
int record = myRecordsTable.createNewRecord();
((RefCountingRecordsTable)myRecordsTable).incRefCount(record);
return record;
}
}
public int createNewRecord() throws IOException {
synchronized (myLock) {
return myRecordsTable.createNewRecord();
}
}
public void acquireRecord(int record) {
waitForPendingWriteForRecord(record);
synchronized (myLock) {
((RefCountingRecordsTable)myRecordsTable).incRefCount(record);
}
}
public void releaseRecord(int record) throws IOException {
releaseRecord(record, true);
}
public void releaseRecord(int record, boolean completely) throws IOException {
waitForPendingWriteForRecord(record);
synchronized (myLock) {
if (((RefCountingRecordsTable)myRecordsTable).decRefCount(record) && completely) {
doDeleteRecord(record);
}
}
}
public int getRefCount(int record) {
waitForPendingWriteForRecord(record);
synchronized (myLock) {
return ((RefCountingRecordsTable)myRecordsTable).getRefCount(record);
}
}
@Override
public void force() {
flushPendingWrites();
super.force();
}
@Override
public boolean isDirty() {
return !myPendingWriteRequests.isEmpty() || super.isDirty();
}
@Override
public boolean flushSome() {
flushPendingWrites();
return super.flushSome();
}
@Override
public void dispose() {
flushPendingWrites();
super.dispose();
}
@Override
public void checkSanity(int record) {
flushPendingWrites();
super.checkSanity(record);
}
private void flushPendingWrites() {
for(Map.Entry<Integer, Future<?>> entry:myPendingWriteRequests.entrySet()) {
try {
entry.getValue().get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| |
/**********************************************************************************
*
* $Id$
*
***********************************************************************************
*
* Copyright (c) 2005, 2006, 2007, 2008, 2009 The Sakai Foundation, The MIT Corporation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.gradebook.ui;
import javax.faces.context.FacesContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.section.api.SectionAwareness;
import org.sakaiproject.service.gradebook.shared.GradebookNotFoundException;
import org.sakaiproject.service.gradebook.shared.GradebookPermissionService;
import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService;
import org.sakaiproject.tool.gradebook.Gradebook;
import org.sakaiproject.tool.gradebook.business.GradebookManager;
import org.sakaiproject.tool.gradebook.business.GradebookScoringAgentManager;
import org.sakaiproject.tool.gradebook.facades.*;
/**
* Provide a UI handle to the selected gradebook.
*
* Since all application-specific backing beans (a group that doesn't include
* authentication handlers) require a gradebook ID to use with any of the
* business or facade services, this bean is also a reasonable place to centralize
* configuration of and access to those services.
*/
public class GradebookBean extends InitializableBean {
private static final Logger logger = LoggerFactory.getLogger(GradebookBean.class);
private Long gradebookId;
private String gradebookUid;
// These interfaces are defined application-wide (through Spring, although the
// UI classes don't know that).
private GradebookManager gradebookManager;
private SectionAwareness sectionAwareness;
private UserDirectoryService userDirectoryService;
private Authn authnService;
private Authz authzService;
private ContextManagement contextManagementService;
private EventTrackingService eventTrackingService;
private ConfigurationBean configurationBean;
private GradebookPermissionService gradebookPermissionService;
private GradebookExternalAssessmentService gradebookExternalAssessmentService;
private GradebookScoringAgentManager scoringAgentManager;
/**
* @return Returns the gradebookId.
*/
public final Long getGradebookId() {
refreshFromRequest();
return gradebookId;
}
private final void setGradebookId(Long gradebookId) {
this.gradebookId = gradebookId;
}
/**
* @param newGradebookUid The gradebookId to set.
* Since this is coming from the client, the application should NOT
* trust that the current user actually has access to the gradebook
* with this UID. This design assumes that authorization will come
* into play on each request.
*/
public final void setGradebookUid(String newGradebookUid) {
Long newGradebookId = null;
if (newGradebookUid != null) {
Gradebook gradebook = null;
try {
gradebook = getGradebookManager().getGradebook(newGradebookUid);
} catch (GradebookNotFoundException gnfe) {
logger.error("Request made for inaccessible gradebookUid=" + newGradebookUid);
newGradebookUid = null;
}
if(gradebook == null)
throw new IllegalStateException("Gradebook gradebook == null!");
newGradebookId = gradebook.getId();
if (logger.isDebugEnabled()) logger.debug("setGradebookUid gradebookUid=" + newGradebookUid + ", gradebookId=" + newGradebookId);
}
this.gradebookUid = newGradebookUid;
setGradebookId(newGradebookId);
}
private final void refreshFromRequest() {
String requestUid = contextManagementService.getGradebookUid(FacesContext.getCurrentInstance().getExternalContext().getRequest());
if ((requestUid != null) && (!requestUid.equals(gradebookUid))) {
if (logger.isDebugEnabled()) logger.debug("resetting gradebookUid from " + gradebookUid);
setGradebookUid(requestUid);
}
}
/**
* Static method to pick up the gradebook UID, if any, held by the current GradebookBean, if any.
* Meant to be called from a servlet filter.
*/
public static String getGradebookUidFromRequest(ServletRequest request) {
String gradebookUid = null;
HttpSession session = ((HttpServletRequest)request).getSession();
GradebookBean gradebookBean = (GradebookBean)session.getAttribute("gradebookBean");
if (gradebookBean != null) {
gradebookUid = gradebookBean.gradebookUid;
}
return gradebookUid;
}
// The following getters are used by other backing beans. The setters are used only by
// the bean factory.
/**
* @return Returns the gradebookManager.
*/
public GradebookManager getGradebookManager() {
return gradebookManager;
}
/**
* @param gradebookManager The gradebookManager to set.
*/
public void setGradebookManager(GradebookManager gradebookManager) {
this.gradebookManager = gradebookManager;
}
public SectionAwareness getSectionAwareness() {
return sectionAwareness;
}
public void setSectionAwareness(SectionAwareness sectionAwareness) {
this.sectionAwareness = sectionAwareness;
}
/**
* @return Returns the userDirectoryService.
*/
public UserDirectoryService getUserDirectoryService() {
return userDirectoryService;
}
/**
* @param userDirectoryService The userDirectoryService to set.
*/
public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
this.userDirectoryService = userDirectoryService;
}
/**
* @return Returns the authnService.
*/
public Authn getAuthnService() {
return authnService;
}
/**
* @param authnService The authnService to set.
*/
public void setAuthnService(Authn authnService) {
this.authnService = authnService;
}
public Authz getAuthzService() {
return authzService;
}
public void setAuthzService(Authz authzService) {
this.authzService = authzService;
}
/**
* @return Returns the contextManagementService.
*/
public ContextManagement getContextManagementService() {
return contextManagementService;
}
/**
* @param contextManagementService The contextManagementService to set.
*/
public void setContextManagementService(ContextManagement contextManagementService) {
this.contextManagementService = contextManagementService;
}
public EventTrackingService getEventTrackingService() {
return eventTrackingService;
}
public void setEventTrackingService(EventTrackingService eventTrackingService) {
this.eventTrackingService = eventTrackingService;
}
public ConfigurationBean getConfigurationBean() {
return configurationBean;
}
public void setConfigurationBean(ConfigurationBean configurationBean) {
this.configurationBean = configurationBean;
}
public GradebookPermissionService getGradebookPermissionService() {
return gradebookPermissionService;
}
public void setGradebookPermissionService(GradebookPermissionService gradebookPermissionService) {
this.gradebookPermissionService = gradebookPermissionService;
}
public GradebookExternalAssessmentService getGradebookExternalAssessmentService() {
return gradebookExternalAssessmentService;
}
public void setGradebookExternalAssessmentService(GradebookExternalAssessmentService gradebookExternalAssessmentService) {
this.gradebookExternalAssessmentService = gradebookExternalAssessmentService;
}
public GradebookScoringAgentManager getScoringAgentManager() {
return this.scoringAgentManager;
}
public void setScoringAgentManager(GradebookScoringAgentManager scoringAgentManager) {
this.scoringAgentManager = scoringAgentManager;
}
}
| |
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.devtools.build.lib.analysis.util.AnalysisTestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Test for visibility of targets. */
@RunWith(JUnit4.class)
public class VisibilityTest extends AnalysisTestCase {
void setupArgsScenario() throws Exception {
scratch.file("tool/tool.sh", "#!/bin/sh", "echo Hello > $2", "cat $1 >> $2");
scratch.file("rule/BUILD");
scratch.file(
"rule/rule.bzl",
"def _impl(ctx):",
" output = ctx.actions.declare_file(ctx.label.name + '.out')",
" ctx.actions.run(",
" inputs = ctx.files._tool + ctx.files.data,",
" executable = ctx.files._tool[0].path,",
" arguments = [f.path for f in ctx.files.data] + [output.path],",
" outputs = [output],",
" )",
"",
"greet = rule(",
" implementation = _impl,",
" attrs = {",
" 'data' : attr.label(allow_files=True),",
" '_tool' : attr.label(cfg='host', allow_files=True,",
" default = Label('//tool:tool.sh')),",
" },",
" outputs = {'out' : '%{name}.out'},",
")");
scratch.file("data/data.txt", "World");
scratch.file(
"use/BUILD",
"load('//rule:rule.bzl', 'greet')",
"",
"greet(",
" name = 'world',",
" data = '//data:data.txt',",
")");
}
@Test
public void testToolVisibilityRuleCheckAtRule() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:public'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//rule:__pkg__'])");
useConfiguration("--incompatible_visibility_private_attributes_at_definition");
update("//use:world");
assertThat(hasErrors(getConfiguredTarget("//use:world"))).isFalse();
}
@Test
public void testToolVisibilityRuleCheckAtUse() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:public'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//rule:__pkg__'])");
useConfiguration("--noincompatible_visibility_private_attributes_at_definition");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//use:world"));
}
@Test
public void testToolVisibilityUseCheckAtUse() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:public'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//use:__pkg__'])");
useConfiguration("--noincompatible_visibility_private_attributes_at_definition");
update("//use:world");
assertThat(hasErrors(getConfiguredTarget("//use:world"))).isFalse();
}
@Test
public void testToolVisibilityUseCheckAtRule() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:public'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//use:__pkg__'])");
useConfiguration("--incompatible_visibility_private_attributes_at_definition");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//use:world"));
}
@Test
public void testToolVisibilityPrivateCheckAtUse() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:public'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//visibility:private'])");
useConfiguration("--noincompatible_visibility_private_attributes_at_definition");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//use:world"));
}
@Test
public void testToolVisibilityPrivateCheckAtRule() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:public'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//visibility:private'])");
useConfiguration("--incompatible_visibility_private_attributes_at_definition");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//use:world"));
}
@Test
public void testDataVisibilityUseCheckPrivateAtUse() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//use:__pkg__'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//visibility:public'])");
useConfiguration("--noincompatible_visibility_private_attributes_at_definition");
update("//use:world");
assertThat(hasErrors(getConfiguredTarget("//use:world"))).isFalse();
}
@Test
public void testDataVisibilityUseCheckPrivateAtRule() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//use:__pkg__'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//visibility:public'])");
useConfiguration("--incompatible_visibility_private_attributes_at_definition");
update("//use:world");
assertThat(hasErrors(getConfiguredTarget("//use:world"))).isFalse();
}
@Test
public void testDataVisibilityPrivateCheckPrivateAtRule() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:private'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//visibility:public'])");
useConfiguration("--incompatible_visibility_private_attributes_at_definition");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//use:world"));
}
@Test
public void testDataVisibilityPrivateCheckPrivateAtUse() throws Exception {
setupArgsScenario();
scratch.file("data/BUILD", "exports_files(['data.txt'], visibility=['//visibility:private'])");
scratch.file("tool/BUILD", "exports_files(['tool.sh'], visibility=['//visibility:public'])");
useConfiguration("--noincompatible_visibility_private_attributes_at_definition");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//use:world"));
}
void setupFilesScenario(String wantRead) throws Exception {
scratch.file("src/source.txt", "source");
scratch.file("src/BUILD", "exports_files(['source.txt'], visibility=['//pkg:__pkg__'])");
scratch.file("pkg/foo.txt", "foo");
scratch.file("pkg/bar.txt", "bar");
scratch.file("pkg/groupfile.txt", "groupfile");
scratch.file("pkg/unused.txt", "unused");
scratch.file("pkg/exported.txt", "exported");
scratch.file(
"pkg/BUILD",
"package(default_visibility=['//visibility:public'])",
"exports_files(['exported.txt'])",
"",
"genrule(",
" name = 'foobar',",
" outs = ['foobar.txt'],",
" srcs = ['foo.txt', 'bar.txt'],",
" cmd = 'cat $(SRCS) > $@',",
")",
"",
"filegroup(",
" name = 'remotegroup',",
" srcs = ['//src:source.txt'],",
")",
"",
"filegroup(",
" name = 'localgroup',",
" srcs = [':groupfile.txt'],",
")");
scratch.file(
"otherpkg/BUILD",
"genrule(",
" name = 'it',",
" srcs = ['//pkg:" + wantRead + "'],",
" outs = ['it.xt'],",
" cmd = 'cp $< $@',",
")");
}
@Test
public void testTargetImplicitExport() throws Exception {
setupFilesScenario("foobar");
useConfiguration("--noincompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testTargetNoImplicitExport() throws Exception {
setupFilesScenario("foobar");
useConfiguration("--incompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testLocalFilegroupImplicitExport() throws Exception {
setupFilesScenario("localgroup");
useConfiguration("--noincompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testLocalFilegroupNoImplicitExport() throws Exception {
setupFilesScenario("localgroup");
useConfiguration("--incompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testRemoteFilegroupImplicitExport() throws Exception {
setupFilesScenario("remotegroup");
useConfiguration("--noincompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testRemoteFilegroupNoImplicitExport() throws Exception {
setupFilesScenario("remotegroup");
useConfiguration("--incompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testExportedImplicitExport() throws Exception {
setupFilesScenario("exported.txt");
useConfiguration("--noincompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testExportedNoImplicitExport() throws Exception {
setupFilesScenario("exported.txt");
useConfiguration("--incompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testUnusedImplicitExport() throws Exception {
setupFilesScenario("unused.txt");
useConfiguration("--noincompatible_no_implicit_file_export");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//otherpkg:it"));
}
@Test
public void testUnusedNoImplicitExport() throws Exception {
setupFilesScenario("unused.txt");
useConfiguration("--incompatible_no_implicit_file_export");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//otherpkg:it"));
}
@Test
public void testSourcefileImplicitExport() throws Exception {
setupFilesScenario("foo.txt");
useConfiguration("--noincompatible_no_implicit_file_export");
update("//otherpkg:it");
assertThat(hasErrors(getConfiguredTarget("//otherpkg:it"))).isFalse();
}
@Test
public void testSourcefileNoImplicitExport() throws Exception {
setupFilesScenario("foo.txt");
useConfiguration("--incompatible_no_implicit_file_export");
reporter.removeHandler(failFastHandler);
assertThrows(ViewCreationFailedException.class, () -> update("//otherpkg:it"));
}
}
| |
package com.airhacks.enhydrator.flexpipe;
/*
* #%L
* enhydrator
* %%
* Copyright (C) 2014 Adam Bien
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.airhacks.enhydrator.in.Source;
import com.airhacks.enhydrator.out.Sink;
import com.airhacks.enhydrator.out.NamedSink;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author airhacks.com
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "pipeline")
public class Pipeline {
private String name;
private Source source;
@XmlElement(name = "stop-on-error")
private boolean stopOnError;
@XmlElement(name = "scripts-home")
private String scriptsHome;
@XmlElement(name = "sql-query")
private String sqlQuery;
@XmlElement(name = "query-param")
private List<Object> queryParams;
@XmlElement(name = "filter")
private List<String> filters;
@XmlElement(name = "pre-row-transformation")
private List<RowTransformation> preRowTransformers;
@XmlElement(name = "column-transformation")
private List<ColumnTransformation> columnTransformations;
@XmlElement(name = "expression")
private List<String> expressions;
@XmlElement(name = "post-row-transformation")
private List<RowTransformation> postRowTransfomers;
@XmlElement(name = "sink")
private List<NamedSink> sinks;
Pipeline() {
this.preRowTransformers = new ArrayList<>();
this.columnTransformations = new ArrayList<>();
this.postRowTransfomers = new ArrayList<>();
this.queryParams = new ArrayList<>();
this.expressions = new ArrayList<>();
this.filters = new ArrayList<>();
this.stopOnError = false;
}
public Pipeline(String name, String scriptsHome, String sqlQuery, Source source) {
this();
this.preRowTransformers = new ArrayList<>();
this.sinks = new ArrayList<>();
this.sqlQuery = sqlQuery;
this.scriptsHome = scriptsHome;
this.name = name;
this.source = source;
}
public String getName() {
return name;
}
public void addPreRowTransformation(RowTransformation transformer) {
this.preRowTransformers.add(transformer);
}
public void addEntryTransformation(ColumnTransformation et) {
this.columnTransformations.add(et);
}
public void addPostRowTransformation(RowTransformation transformer) {
this.postRowTransfomers.add(transformer);
}
public void addExpression(String expression) {
this.expressions.add(expression);
}
public void addFilter(String filter) {
this.filters.add(filter);
}
public void addQueryParam(Object value) {
this.queryParams.add(value);
}
public void addSink(NamedSink sink) {
this.sinks.add(sink);
}
public Source getSource() {
return source;
}
public void setSource(Source source) {
this.source = source;
}
public String getSqlQuery() {
return sqlQuery;
}
public List<Object> getQueryParams() {
return queryParams;
}
public List<Sink> getSinks() {
return sinks.stream().map(s -> (Sink) s).collect(Collectors.toList());
}
public List<RowTransformation> getPreRowTransformers() {
return preRowTransformers;
}
public List<ColumnTransformation> getColumnTransformations() {
return columnTransformations;
}
public List<RowTransformation> getPostRowTransfomers() {
return postRowTransfomers;
}
public List<String> getExpressions() {
return expressions;
}
public List<String> getFilters() {
return filters;
}
public String getScriptsHome() {
return scriptsHome;
}
public void setScriptsHome(String scriptsHome) {
this.scriptsHome = scriptsHome;
}
public void setStopOnError(boolean stopOnError) {
this.stopOnError = stopOnError;
}
@Override
public int hashCode() {
int hash = 3;
hash = 67 * hash + Objects.hashCode(this.name);
hash = 67 * hash + Objects.hashCode(this.source);
hash = 67 * hash + Objects.hashCode(this.sqlQuery);
hash = 67 * hash + Objects.hashCode(this.queryParams);
hash = 67 * hash + Objects.hashCode(this.sinks);
hash = 67 * hash + Objects.hashCode(this.preRowTransformers);
hash = 67 * hash + Objects.hashCode(this.columnTransformations);
hash = 67 * hash + Objects.hashCode(this.postRowTransfomers);
hash = 67 * hash + Objects.hashCode(this.expressions);
hash = 67 * hash + Objects.hashCode(this.filters);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pipeline other = (Pipeline) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.source, other.source)) {
return false;
}
if (!Objects.equals(this.sqlQuery, other.sqlQuery)) {
return false;
}
if (!Objects.equals(this.queryParams, other.queryParams)) {
return false;
}
if (!Objects.equals(this.sinks, other.sinks)) {
return false;
}
if (!Objects.equals(this.preRowTransformers, other.preRowTransformers)) {
return false;
}
if (!Objects.equals(this.columnTransformations, other.columnTransformations)) {
return false;
}
if (!Objects.equals(this.postRowTransfomers, other.postRowTransfomers)) {
return false;
}
if (!Objects.equals(this.expressions, other.expressions)) {
return false;
}
if (!Objects.equals(this.filters, other.filters)) {
return false;
}
return true;
}
@Override
public String toString() {
return "JDBCPipeline{" + "name=" + name + ", source=" + source + ", sqlQuery=" + sqlQuery + ", queryParams=" + queryParams + ", sink=" + sinks + ", preRowTransformers=" + preRowTransformers + ", entryTransformations=" + columnTransformations + ", postRowTransfomers=" + postRowTransfomers + ", expressions=" + expressions + '}';
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.reef.webserver;
import org.apache.reef.driver.catalog.NodeDescriptor;
import org.apache.reef.driver.context.ActiveContext;
import org.apache.reef.driver.evaluator.AllocatedEvaluator;
import org.apache.reef.driver.evaluator.EvaluatorDescriptor;
import org.apache.reef.driver.restart.DriverRestarted;
import org.apache.reef.driver.task.RunningTask;
import org.apache.reef.runtime.common.driver.DriverStatusManager;
import org.apache.reef.runtime.common.utils.RemoteManager;
import org.apache.reef.tang.annotations.Unit;
import org.apache.reef.wake.EventHandler;
import org.apache.reef.wake.time.event.StartTime;
import org.apache.reef.wake.time.event.StopTime;
import javax.inject.Inject;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Reef Event Manager that manages Reef states.
*/
@Unit
public final class ReefEventStateManager {
/**
* Standard Java logger.
*/
private static final Logger LOG = Logger.getLogger(ReefEventStateManager.class.getName());
/**
* Date format.
*/
private static final Format FORMAT = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
/**
* Map of evaluators.
*/
private final Map<String, EvaluatorDescriptor> evaluators = new HashMap<>();
/**
* Map from context ID to running evaluator context.
*/
private final Map<String, ActiveContext> contexts = new HashMap<>();
private final List<AvroReefServiceInfo> serviceInfoList = new ArrayList<>();
/**
* Remote manager in driver the carries information such as driver endpoint identifier.
*/
private final RemoteManager remoteManager;
/**
* Driver Status Manager that controls the driver status.
*/
private final DriverStatusManager driverStatusManager;
/**
* Evaluator start time.
*/
private StartTime startTime;
/**
* Evaluator stop time.
*/
private StopTime stopTime;
/**
* ReefEventStateManager that keeps the states of Reef components.
*/
@Inject
public ReefEventStateManager(final RemoteManager remoteManager, final DriverStatusManager driverStatusManager) {
this.remoteManager = remoteManager;
this.driverStatusManager = driverStatusManager;
}
/**
* get start time.
*
* @return
*/
public String getStartTime() {
if (startTime != null) {
return convertTime(startTime.getTimeStamp());
}
return null;
}
/**
* get stop time.
*
* @return
*/
public String getStopTime() {
if (stopTime != null) {
return convertTime(stopTime.getTimeStamp());
}
return null;
}
/**
* convert time from long to formatted string.
*
* @param time
* @return
*/
private String convertTime(final long time) {
final Date date = new Date(time);
return FORMAT.format(date);
}
/**
* get evaluator map.
*
* @return
*/
public Map<String, EvaluatorDescriptor> getEvaluators() {
return evaluators;
}
/**
* get driver endpoint identifier.
*/
public String getDriverEndpointIdentifier() {
return remoteManager.getMyIdentifier();
}
public List<AvroReefServiceInfo> getServicesInfo() {
return this.serviceInfoList;
}
public void registerServiceInfo(final AvroReefServiceInfo serviceInfo) {
synchronized (this.serviceInfoList) {
serviceInfoList.add(serviceInfo);
LOG.log(Level.INFO, "Registered Service [{0}] with Info [{1}]",
new Object[]{serviceInfo.getServiceName(), serviceInfo.getServiceInfo()});
}
}
/**
* get a map of contexts.
*
* @return
*/
public Map<String, ActiveContext> getContexts() {
return contexts;
}
/**
* pus a entry to evaluators.
*
* @param key
* @param value
*/
public void put(final String key, final EvaluatorDescriptor value) {
evaluators.put(key, value);
}
/**
* get a value from evaluators by key.
*
* @param key
* @return
*/
public EvaluatorDescriptor get(final String key) {
return evaluators.get(key);
}
/**
* getEvaluatorDescriptor.
*
* @param evaluatorId
* @return
*/
public EvaluatorDescriptor getEvaluatorDescriptor(final String evaluatorId) {
return evaluators.get(evaluatorId);
}
/**
* get Evaluator NodeDescriptor.
*
* @param evaluatorId
* @return
*/
public NodeDescriptor getEvaluatorNodeDescriptor(final String evaluatorId) {
return evaluators.get(evaluatorId).getNodeDescriptor();
}
/**
* Kill driver by calling onComplete() . This method is called when client wants to kill the driver and evaluators.
*/
public void onClientKill() {
driverStatusManager.onComplete();
}
/**
* Job Driver is ready and the clock is set up.
*/
public final class StartStateHandler implements EventHandler<StartTime> {
@Override
@SuppressWarnings("checkstyle:hiddenfield")
public void onNext(final StartTime startTime) {
LOG.log(Level.INFO,
"StartStateHandler: Driver started with endpoint identifier [{0}] and StartTime [{1}]",
new Object[]{ReefEventStateManager.this.remoteManager.getMyIdentifier(), startTime});
ReefEventStateManager.this.startTime = startTime;
}
}
/**
* Job Driver has been restarted.
*/
public final class DriverRestartHandler implements EventHandler<DriverRestarted> {
@Override
@SuppressWarnings("checkstyle:hiddenfield")
public void onNext(final DriverRestarted restartTime) {
LOG.log(Level.INFO, "DriverRestartHandler called. StartTime: {0}", restartTime);
}
}
/**
* Job driver stopped, log the stop time.
*/
public final class StopStateHandler implements EventHandler<StopTime> {
@Override
@SuppressWarnings("checkstyle:hiddenfield")
public void onNext(final StopTime stopTime) {
LOG.log(Level.INFO, "StopStateHandler called. StopTime: {0}", stopTime);
ReefEventStateManager.this.stopTime = stopTime;
}
}
/**
* Receive notification that an Evaluator had been allocated.
*/
public final class AllocatedEvaluatorStateHandler implements EventHandler<AllocatedEvaluator> {
@Override
public void onNext(final AllocatedEvaluator eval) {
synchronized (ReefEventStateManager.this) {
ReefEventStateManager.this.put(eval.getId(), eval.getEvaluatorDescriptor());
}
}
}
/**
* Receive event when task is running.
*/
public final class TaskRunningStateHandler implements EventHandler<RunningTask> {
@Override
public void onNext(final RunningTask runningTask) {
LOG.log(Level.INFO, "Running task {0} received.", runningTask.getId());
}
}
/**
* Receive event during driver restart that a task is running in previous evaluator.
*/
public final class DriverRestartTaskRunningStateHandler implements EventHandler<RunningTask> {
@Override
public void onNext(final RunningTask runningTask) {
LOG.log(Level.INFO, "Running task {0} received during driver restart.", runningTask.getId());
}
}
/**
* Receive notification that a new Context is available.
*/
public final class ActiveContextStateHandler implements EventHandler<ActiveContext> {
@Override
public void onNext(final ActiveContext context) {
synchronized (ReefEventStateManager.this) {
LOG.log(Level.INFO, "Active Context {0} received and handled in state handler", context);
contexts.put(context.getId(), context);
}
}
}
/**
* Receive notification that a new Context is available.
*/
public final class DriverRestartActiveContextStateHandler implements EventHandler<ActiveContext> {
@Override
public void onNext(final ActiveContext context) {
synchronized (ReefEventStateManager.this) {
LOG.log(Level.INFO, "Active Context {0} received and handled in state handler during driver restart.", context);
evaluators.put(context.getEvaluatorId(), context.getEvaluatorDescriptor());
contexts.put(context.getId(), context);
}
}
}
/**
* Receive notification from the client.
*/
public final class ClientMessageStateHandler implements EventHandler<byte[]> {
@Override
public void onNext(final byte[] message) {
synchronized (ReefEventStateManager.this) {
LOG.log(Level.INFO, "ClientMessageStateHandler OnNext called");
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.runtime;
import static org.jboss.web.JasperMessages.MESSAGES;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
/**
* Bunch of util methods that are used by code generated for useBean,
* getProperty and setProperty.
*
* The __begin, __end stuff is there so that the JSP engine can
* actually parse this file and inline them if people don't want
* runtime dependencies on this class. However, I'm not sure if that
* works so well right now. It got forgotten at some point. -akv
*
* @author Mandar Raje
* @author Shawn Bayern
*/
public class JspRuntimeLibrary {
private static final String SERVLET_EXCEPTION
= "javax.servlet.error.exception";
private static final String JSP_EXCEPTION
= "javax.servlet.jsp.jspException";
protected static class PrivilegedIntrospectHelper
implements PrivilegedExceptionAction {
private Object bean;
private String prop;
private String value;
private ServletRequest request;
private String param;
private boolean ignoreMethodNF;
PrivilegedIntrospectHelper(Object bean, String prop,
String value, ServletRequest request,
String param, boolean ignoreMethodNF)
{
this.bean = bean;
this.prop = prop;
this.value = value;
this.request = request;
this.param = param;
this.ignoreMethodNF = ignoreMethodNF;
}
public Object run() throws JasperException {
internalIntrospecthelper(
bean,prop,value,request,param,ignoreMethodNF);
return null;
}
}
/**
* Returns the value of the javax.servlet.error.exception request
* attribute value, if present, otherwise the value of the
* javax.servlet.jsp.jspException request attribute value.
*
* This method is called at the beginning of the generated servlet code
* for a JSP error page, when the "exception" implicit scripting language
* variable is initialized.
*/
public static Throwable getThrowable(ServletRequest request) {
Throwable error = (Throwable) request.getAttribute(SERVLET_EXCEPTION);
if (error == null) {
error = (Throwable) request.getAttribute(JSP_EXCEPTION);
if (error != null) {
/*
* The only place that sets JSP_EXCEPTION is
* PageContextImpl.handlePageException(). It really should set
* SERVLET_EXCEPTION, but that would interfere with the
* ErrorReportValve. Therefore, if JSP_EXCEPTION is set, we
* need to set SERVLET_EXCEPTION.
*/
request.setAttribute(SERVLET_EXCEPTION, error);
}
}
return error;
}
public static boolean coerceToBoolean(String s) {
if (s == null || s.length() == 0)
return false;
else
return Boolean.valueOf(s).booleanValue();
}
public static byte coerceToByte(String s) {
if (s == null || s.length() == 0)
return (byte) 0;
else
return Byte.valueOf(s).byteValue();
}
public static char coerceToChar(String s) {
if (s == null || s.length() == 0) {
return (char) 0;
} else {
// this trick avoids escaping issues
return (char)(int) s.charAt(0);
}
}
public static double coerceToDouble(String s) {
if (s == null || s.length() == 0)
return (double) 0;
else
return Double.valueOf(s).doubleValue();
}
public static float coerceToFloat(String s) {
if (s == null || s.length() == 0)
return (float) 0;
else
return Float.valueOf(s).floatValue();
}
public static int coerceToInt(String s) {
if (s == null || s.length() == 0)
return 0;
else
return Integer.valueOf(s).intValue();
}
public static short coerceToShort(String s) {
if (s == null || s.length() == 0)
return (short) 0;
else
return Short.valueOf(s).shortValue();
}
public static long coerceToLong(String s) {
if (s == null || s.length() == 0)
return (long) 0;
else
return Long.valueOf(s).longValue();
}
public static Object coerce(String s, Class target) {
boolean isNullOrEmpty = (s == null || s.length() == 0);
if (target == Boolean.class) {
if (isNullOrEmpty) {
s = "false";
}
return new Boolean(s);
} else if (target == Byte.class) {
if (isNullOrEmpty)
return new Byte((byte) 0);
else
return new Byte(s);
} else if (target == Character.class) {
if (isNullOrEmpty)
return new Character((char) 0);
else
return new Character(s.charAt(0));
} else if (target == Double.class) {
if (isNullOrEmpty)
return new Double(0);
else
return new Double(s);
} else if (target == Float.class) {
if (isNullOrEmpty)
return new Float(0);
else
return new Float(s);
} else if (target == Integer.class) {
if (isNullOrEmpty)
return new Integer(0);
else
return new Integer(s);
} else if (target == Short.class) {
if (isNullOrEmpty)
return new Short((short) 0);
else
return new Short(s);
} else if (target == Long.class) {
if (isNullOrEmpty)
return new Long(0);
else
return new Long(s);
} else {
return null;
}
}
// __begin convertMethod
public static Object convert(String propertyName, String s, Class t,
Class propertyEditorClass)
throws JasperException
{
try {
if (s == null) {
if (t.equals(Boolean.class) || t.equals(Boolean.TYPE))
s = "false";
else
return null;
}
if (propertyEditorClass != null) {
return getValueFromBeanInfoPropertyEditor(
t, propertyName, s, propertyEditorClass);
} else if ( t.equals(Boolean.class) || t.equals(Boolean.TYPE) ) {
if (s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true"))
s = "true";
else
s = "false";
return new Boolean(s);
} else if ( t.equals(Byte.class) || t.equals(Byte.TYPE) ) {
return new Byte(s);
} else if (t.equals(Character.class) || t.equals(Character.TYPE)) {
return s.length() > 0 ? new Character(s.charAt(0)) : null;
} else if ( t.equals(Short.class) || t.equals(Short.TYPE) ) {
return new Short(s);
} else if ( t.equals(Integer.class) || t.equals(Integer.TYPE) ) {
return new Integer(s);
} else if ( t.equals(Float.class) || t.equals(Float.TYPE) ) {
return new Float(s);
} else if ( t.equals(Long.class) || t.equals(Long.TYPE) ) {
return new Long(s);
} else if ( t.equals(Double.class) || t.equals(Double.TYPE) ) {
return new Double(s);
} else if ( t.equals(String.class) ) {
return s;
} else if ( t.equals(java.io.File.class) ) {
return new java.io.File(s);
} else if (t.getName().equals("java.lang.Object")) {
return new Object[] {s};
} else {
return getValueFromPropertyEditorManager(
t, propertyName, s);
}
} catch (Exception ex) {
throw new JasperException(ex);
}
}
// __end convertMethod
// __begin introspectMethod
public static void introspect(Object bean, ServletRequest request)
throws JasperException
{
Enumeration e = request.getParameterNames();
while ( e.hasMoreElements() ) {
String name = (String) e.nextElement();
String value = request.getParameter(name);
introspecthelper(bean, name, value, request, name, true);
}
}
// __end introspectMethod
// __begin introspecthelperMethod
public static void introspecthelper(Object bean, String prop,
String value, ServletRequest request,
String param, boolean ignoreMethodNF)
throws JasperException
{
if( Constants.IS_SECURITY_ENABLED ) {
try {
PrivilegedIntrospectHelper dp =
new PrivilegedIntrospectHelper(
bean,prop,value,request,param,ignoreMethodNF);
AccessController.doPrivileged(dp);
} catch( PrivilegedActionException pe) {
Exception e = pe.getException();
throw (JasperException)e;
}
} else {
internalIntrospecthelper(
bean,prop,value,request,param,ignoreMethodNF);
}
}
private static void internalIntrospecthelper(Object bean, String prop,
String value, ServletRequest request,
String param, boolean ignoreMethodNF)
throws JasperException
{
Method method = null;
Class type = null;
Class propertyEditorClass = null;
try {
java.beans.BeanInfo info
= java.beans.Introspector.getBeanInfo(bean.getClass());
if ( info != null ) {
java.beans.PropertyDescriptor pd[]
= info.getPropertyDescriptors();
for (int i = 0 ; i < pd.length ; i++) {
if ( pd[i].getName().equals(prop) ) {
method = pd[i].getWriteMethod();
type = pd[i].getPropertyType();
propertyEditorClass = pd[i].getPropertyEditorClass();
break;
}
}
}
if ( method != null ) {
if (type.isArray()) {
if (request == null) {
throw new JasperException(MESSAGES.failedSettingBeanIndexedProperty());
}
Class t = type.getComponentType();
String[] values = request.getParameterValues(param);
//XXX Please check.
if(values == null) return;
if(t.equals(String.class)) {
method.invoke(bean, new Object[] { values });
} else {
Object tmpval = null;
createTypedArray (prop, bean, method, values, t,
propertyEditorClass);
}
} else {
if(value == null || (param != null && value.equals(""))) return;
Object oval = convert(prop, value, type, propertyEditorClass);
if ( oval != null )
method.invoke(bean, new Object[] { oval });
}
}
} catch (Exception ex) {
throw new JasperException(ex);
}
if (!ignoreMethodNF && (method == null)) {
if (type == null) {
throw new JasperException(MESSAGES.cannotFindBeanProperty(prop, bean.getClass().getName()));
} else {
throw new JasperException(MESSAGES.cannotSetBeanProperty(prop, type.getName(), bean.getClass().getName()));
}
}
}
// __end introspecthelperMethod
//-------------------------------------------------------------------
// functions to convert builtin Java data types to string.
//-------------------------------------------------------------------
// __begin toStringMethod
public static String toString(Object o) {
return String.valueOf(o);
}
public static String toString(byte b) {
return new Byte(b).toString();
}
public static String toString(boolean b) {
return new Boolean(b).toString();
}
public static String toString(short s) {
return new Short(s).toString();
}
public static String toString(int i) {
return new Integer(i).toString();
}
public static String toString(float f) {
return new Float(f).toString();
}
public static String toString(long l) {
return new Long(l).toString();
}
public static String toString(double d) {
return new Double(d).toString();
}
public static String toString(char c) {
return new Character(c).toString();
}
// __end toStringMethod
/**
* Create a typed array.
* This is a special case where params are passed through
* the request and the property is indexed.
*/
public static void createTypedArray(String propertyName,
Object bean,
Method method,
String[] values,
Class t,
Class propertyEditorClass)
throws JasperException {
try {
if (propertyEditorClass != null) {
Object[] tmpval = new Integer[values.length];
for (int i=0; i<values.length; i++) {
tmpval[i] = getValueFromBeanInfoPropertyEditor(
t, propertyName, values[i], propertyEditorClass);
}
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Integer.class)) {
Integer []tmpval = new Integer[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Integer (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Byte.class)) {
Byte[] tmpval = new Byte[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Byte (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Boolean.class)) {
Boolean[] tmpval = new Boolean[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Boolean (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Short.class)) {
Short[] tmpval = new Short[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Short (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Long.class)) {
Long[] tmpval = new Long[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Long (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Double.class)) {
Double[] tmpval = new Double[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Double (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Float.class)) {
Float[] tmpval = new Float[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Float (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(Character.class)) {
Character[] tmpval = new Character[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = new Character(values[i].charAt(0));
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(int.class)) {
int []tmpval = new int[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = Integer.parseInt (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(byte.class)) {
byte[] tmpval = new byte[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = Byte.parseByte (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(boolean.class)) {
boolean[] tmpval = new boolean[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = (Boolean.valueOf(values[i])).booleanValue();
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(short.class)) {
short[] tmpval = new short[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = Short.parseShort (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(long.class)) {
long[] tmpval = new long[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = Long.parseLong (values[i]);
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(double.class)) {
double[] tmpval = new double[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = Double.valueOf(values[i]).doubleValue();
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(float.class)) {
float[] tmpval = new float[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = Float.valueOf(values[i]).floatValue();
method.invoke (bean, new Object[] {tmpval});
} else if (t.equals(char.class)) {
char[] tmpval = new char[values.length];
for (int i = 0 ; i < values.length; i++)
tmpval[i] = values[i].charAt(0);
method.invoke (bean, new Object[] {tmpval});
} else {
Object[] tmpval = new Integer[values.length];
for (int i=0; i<values.length; i++) {
tmpval[i] =
getValueFromPropertyEditorManager(
t, propertyName, values[i]);
}
method.invoke (bean, new Object[] {tmpval});
}
} catch (Exception ex) {
throw new JasperException ("error in invoking method", ex);
}
}
/**
* Escape special shell characters.
* @param unescString The string to shell-escape
* @return The escaped shell string.
*/
public static String escapeQueryString(String unescString) {
if ( unescString == null )
return null;
String escString = "";
String shellSpChars = "&;`'\"|*?~<>^()[]{}$\\\n";
for(int index=0; index<unescString.length(); index++) {
char nextChar = unescString.charAt(index);
if( shellSpChars.indexOf(nextChar) != -1 )
escString += "\\";
escString += nextChar;
}
return escString;
}
/**
* Decode an URL formatted string.
* @param encoded The string to decode.
* @return The decoded string.
*/
public static String decode(String encoded) {
// speedily leave if we're not needed
if (encoded == null) return null;
if (encoded.indexOf('%') == -1 && encoded.indexOf('+') == -1)
return encoded;
//allocate the buffer - use byte[] to avoid calls to new.
byte holdbuffer[] = new byte[encoded.length()];
char holdchar;
int bufcount = 0;
for (int count = 0; count < encoded.length(); count++) {
char cur = encoded.charAt(count);
if (cur == '%') {
holdbuffer[bufcount++] =
(byte)Integer.parseInt(encoded.substring(count+1,count+3),16);
if (count + 2 >= encoded.length())
count = encoded.length();
else
count += 2;
} else if (cur == '+') {
holdbuffer[bufcount++] = (byte) ' ';
} else {
holdbuffer[bufcount++] = (byte) cur;
}
}
// REVISIT -- remedy for Deprecated warning.
//return new String(holdbuffer,0,0,bufcount);
return new String(holdbuffer,0,bufcount);
}
// __begin lookupReadMethodMethod
public static Object handleGetProperty(Object o, String prop)
throws JasperException {
if (o == null) {
throw new JasperException(MESSAGES.nullBean());
}
Object value = null;
try {
Method method = getReadMethod(o.getClass(), prop);
value = method.invoke(o, (Object[]) null);
} catch (Exception ex) {
throw new JasperException (ex);
}
return value;
}
// __end lookupReadMethodMethod
// handles <jsp:setProperty> with EL expression for 'value' attribute
/** Use proprietaryEvaluate
public static void handleSetPropertyExpression(Object bean,
String prop, String expression, PageContext pageContext,
VariableResolver variableResolver, FunctionMapper functionMapper )
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] {
pageContext.getExpressionEvaluator().evaluate(
expression,
method.getParameterTypes()[0],
variableResolver,
functionMapper,
null )
});
} catch (Exception ex) {
throw new JasperException(ex);
}
}
**/
public static void handleSetPropertyExpression(Object bean,
String prop, String expression, PageContext pageContext,
ProtectedFunctionMapper functionMapper )
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] {
PageContextImpl.proprietaryEvaluate(
expression,
method.getParameterTypes()[0],
pageContext,
functionMapper,
false )
});
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
Object value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { value });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
int value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Integer(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
short value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Short(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
long value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Long(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
double value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Double(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
float value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Float(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
char value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Character(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
byte value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Byte(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static void handleSetProperty(Object bean, String prop,
boolean value)
throws JasperException
{
try {
Method method = getWriteMethod(bean.getClass(), prop);
method.invoke(bean, new Object[] { new Boolean(value) });
} catch (Exception ex) {
throw new JasperException(ex);
}
}
public static Method getWriteMethod(Class beanClass, String prop)
throws JasperException {
Method method = null;
Class type = null;
try {
java.beans.BeanInfo info
= java.beans.Introspector.getBeanInfo(beanClass);
if ( info != null ) {
java.beans.PropertyDescriptor pd[]
= info.getPropertyDescriptors();
for (int i = 0 ; i < pd.length ; i++) {
if ( pd[i].getName().equals(prop) ) {
method = pd[i].getWriteMethod();
type = pd[i].getPropertyType();
break;
}
}
} else {
// just in case introspection silently fails.
throw new JasperException(MESSAGES.cannotFindBeanInfo(beanClass.getName()));
}
} catch (Exception ex) {
throw new JasperException (ex);
}
if (method == null) {
if (type == null) {
throw new JasperException(MESSAGES.cannotFindBeanProperty(prop, beanClass.getName()));
} else {
throw new JasperException(MESSAGES.cannotSetBeanProperty(prop, type.getName(), beanClass.getName()));
}
}
return method;
}
public static Method getReadMethod(Class beanClass, String prop)
throws JasperException {
Method method = null;
Class type = null;
try {
java.beans.BeanInfo info
= java.beans.Introspector.getBeanInfo(beanClass);
if ( info != null ) {
java.beans.PropertyDescriptor pd[]
= info.getPropertyDescriptors();
for (int i = 0 ; i < pd.length ; i++) {
if ( pd[i].getName().equals(prop) ) {
method = pd[i].getReadMethod();
type = pd[i].getPropertyType();
break;
}
}
} else {
// just in case introspection silently fails.
throw new JasperException(MESSAGES.cannotFindBeanInfo(beanClass.getName()));
}
} catch (Exception ex) {
throw new JasperException (ex);
}
if (method == null) {
if (type == null) {
throw new JasperException(MESSAGES.cannotFindBeanProperty(prop, beanClass.getName()));
} else {
throw new JasperException(MESSAGES.cannotGetBeanProperty(prop, beanClass.getName()));
}
}
return method;
}
//*********************************************************************
// PropertyEditor Support
public static Object getValueFromBeanInfoPropertyEditor(
Class attrClass, String attrName, String attrValue,
Class propertyEditorClass)
throws JasperException
{
try {
PropertyEditor pe = (PropertyEditor)propertyEditorClass.newInstance();
pe.setAsText(attrValue);
return pe.getValue();
} catch (Exception ex) {
throw new JasperException(MESSAGES.errorConvertingBeanProperty
(attrValue, attrClass.getName(), attrName, ex.getMessage()));
}
}
public static Object getValueFromPropertyEditorManager(
Class attrClass, String attrName, String attrValue)
throws JasperException
{
try {
PropertyEditor propEditor =
PropertyEditorManager.findEditor(attrClass);
if (propEditor != null) {
propEditor.setAsText(attrValue);
return propEditor.getValue();
} else {
throw MESSAGES.noRegisteredPropertyEditor();
}
} catch (IllegalArgumentException ex) {
throw new JasperException(MESSAGES.errorConvertingBeanProperty
(attrValue, attrClass.getName(), attrName, ex.getMessage()));
}
}
// ************************************************************************
// General Purpose Runtime Methods
// ************************************************************************
/**
* Convert a possibly relative resource path into a context-relative
* resource path that starts with a '/'.
*
* @param request The servlet request we are processing
* @param relativePath The possibly relative resource path
*/
public static String getContextRelativePath(ServletRequest request,
String relativePath) {
if (relativePath.startsWith("/"))
return (relativePath);
if (!(request instanceof HttpServletRequest))
return (relativePath);
HttpServletRequest hrequest = (HttpServletRequest) request;
String uri = (String)
request.getAttribute("javax.servlet.include.servlet_path");
if (uri != null) {
String pathInfo = (String)
request.getAttribute("javax.servlet.include.path_info");
if (pathInfo == null) {
if (uri.lastIndexOf('/') >= 0)
uri = uri.substring(0, uri.lastIndexOf('/'));
}
}
else {
uri = hrequest.getServletPath();
if (uri.lastIndexOf('/') >= 0)
uri = uri.substring(0, uri.lastIndexOf('/'));
}
return uri + '/' + relativePath;
}
/**
* Perform a RequestDispatcher.include() operation, with optional flushing
* of the response beforehand.
*
* @param request The servlet request we are processing
* @param response The servlet response we are processing
* @param relativePath The relative path of the resource to be included
* @param out The Writer to whom we are currently writing
* @param flush Should we flush before the include is processed?
*
* @exception IOException if thrown by the included servlet
* @exception ServletException if thrown by the included servlet
*/
public static void include(ServletRequest request,
ServletResponse response,
String relativePath,
JspWriter out,
boolean flush)
throws IOException, ServletException {
if (flush && !(out instanceof BodyContent))
out.flush();
// FIXME - It is tempting to use request.getRequestDispatcher() to
// resolve a relative path directly, but Catalina currently does not
// take into account whether the caller is inside a RequestDispatcher
// include or not. Whether Catalina *should* take that into account
// is a spec issue currently under review. In the mean time,
// replicate Jasper's previous behavior
String resourcePath = getContextRelativePath(request, relativePath);
RequestDispatcher rd = request.getRequestDispatcher(resourcePath);
rd.include(request,
new ServletResponseWrapperInclude(response, out));
}
/**
* URL encodes a string, based on the supplied character encoding.
* This performs the same function as java.next.URLEncode.encode
* in J2SDK1.4, and should be removed if the only platform supported
* is 1.4 or higher.
* @param s The String to be URL encoded.
* @param enc The character encoding
* @return The URL encoded String
*/
public static String URLEncode(String s, String enc) {
if (s == null) {
return "null";
}
if (enc == null) {
enc = "ISO-8859-1"; // The default request encoding
}
StringBuilder out = new StringBuilder(s.length());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(buf, enc);
} catch (java.io.UnsupportedEncodingException ex) {
// Use the default encoding?
writer = new OutputStreamWriter(buf);
}
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i);
if (c == ' ') {
out.append('+');
} else if (isSafeChar(c)) {
out.append((char)c);
} else {
// convert to external encoding before hex conversion
try {
writer.write(c);
writer.flush();
} catch(IOException e) {
buf.reset();
continue;
}
byte[] ba = buf.toByteArray();
for (int j = 0; j < ba.length; j++) {
out.append('%');
// Converting each byte in the buffer
out.append(Character.forDigit((ba[j]>>4) & 0xf, 16));
out.append(Character.forDigit(ba[j] & 0xf, 16));
}
buf.reset();
}
}
return out.toString();
}
private static boolean isSafeChar(int c) {
if (c >= 'a' && c <= 'z') {
return true;
}
if (c >= 'A' && c <= 'Z') {
return true;
}
if (c >= '0' && c <= '9') {
return true;
}
if (c == '-' || c == '_' || c == '.' || c == '!' ||
c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
return true;
}
return false;
}
}
| |
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.skylark.skylint;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.syntax.AssignmentStatement;
import com.google.devtools.build.lib.syntax.BuildFileAST;
import com.google.devtools.build.lib.syntax.Expression;
import com.google.devtools.build.lib.syntax.ExpressionStatement;
import com.google.devtools.build.lib.syntax.FunctionDefStatement;
import com.google.devtools.build.lib.syntax.Identifier;
import com.google.devtools.build.lib.syntax.Statement;
import com.google.devtools.build.lib.syntax.StringLiteral;
import java.util.AbstractMap;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/** Utilities to extract and parse docstrings. */
public final class DocstringUtils {
private DocstringUtils() {}
/**
* Collect all docstrings in the AST and store them in a map: name -> docstring.
*
* <p>Note that local variables can't have docstrings.
*
* @param ast the AST to traverse
* @return a map from identifier names to their docstring; if there is a file-level docstring, its
* key is "".
*/
static ImmutableMap<String, StringLiteral> collectDocstringLiterals(BuildFileAST ast) {
ImmutableMap.Builder<String, StringLiteral> nameToDocstringLiteral = ImmutableMap.builder();
Statement previousStatement = null;
for (Statement currentStatement : ast.getStatements()) {
Entry<String, StringLiteral> entry = getNameAndDocstring(previousStatement, currentStatement);
if (entry != null) {
nameToDocstringLiteral.put(entry);
}
previousStatement = currentStatement;
}
return nameToDocstringLiteral.build();
}
@Nullable
private static Entry<String, StringLiteral> getNameAndDocstring(
@Nullable Statement previousStatement, Statement currentStatement) {
// function docstring:
if (currentStatement instanceof FunctionDefStatement) {
StringLiteral docstring =
extractDocstring(((FunctionDefStatement) currentStatement).getStatements());
if (docstring != null) {
return new AbstractMap.SimpleEntry<>(
((FunctionDefStatement) currentStatement).getIdentifier().getName(), docstring);
}
} else {
StringLiteral docstring = getStringLiteral(currentStatement);
if (docstring != null) {
if (previousStatement == null) {
// file docstring:
return new SimpleEntry<>("", docstring);
} else {
// variable docstring:
String variable = getAssignedVariableName(previousStatement);
if (variable != null) {
return new SimpleEntry<>(variable, docstring);
}
}
}
}
return null;
}
/** If the statement is an assignment to one variable, returns its name, or otherwise null. */
@Nullable
static String getAssignedVariableName(@Nullable Statement stmt) {
if (stmt instanceof AssignmentStatement) {
Expression lhs = ((AssignmentStatement) stmt).getLValue().getExpression();
if (lhs instanceof Identifier) {
return ((Identifier) lhs).getName();
}
}
return null;
}
/** If the statement is a string literal, returns it, or otherwise null. */
@Nullable
static StringLiteral getStringLiteral(Statement stmt) {
if (stmt instanceof ExpressionStatement) {
Expression expr = ((ExpressionStatement) stmt).getExpression();
if (expr instanceof StringLiteral) {
return (StringLiteral) expr;
}
}
return null;
}
/** Takes a function body and returns the docstring literal, if present. */
@Nullable
static StringLiteral extractDocstring(List<Statement> statements) {
if (statements.isEmpty()) {
return null;
}
return getStringLiteral(statements.get(0));
}
/** Parses a docstring from a string literal and appends any new errors to the given list. */
static DocstringInfo parseDocstring(StringLiteral docstring, List<DocstringParseError> errors) {
int indentation = docstring.getLocation().getStartLineAndColumn().getColumn() - 1;
return parseDocstring(docstring.getValue(), indentation, errors);
}
/**
* Parses a docstring.
*
* <p>The format of the docstring is as follows
*
* <pre>{@code
* """One-line summary: must be followed and may be preceded by a blank line.
*
* Optional additional description like this.
*
* If it's a function docstring and the function has more than one argument, the docstring has
* to document these parameters as follows:
*
* Args:
* parameter1: description of the first parameter. Each parameter line
* should be indented by one, preferably two, spaces (as here).
* parameter2: description of the second
* parameter that spans two lines. Each additional line should have a
* hanging indentation of at least one, preferably two, additional spaces (as here).
* another_parameter (unused, mutable): a parameter may be followed
* by additional attributes in parentheses
*
* Returns:
* Description of the return value.
* Should be indented by at least one, preferably two spaces (as here)
* Can span multiple lines.
* """
* }</pre>
*
* @param docstring a docstring of the format described above
* @param indentation the indentation level (number of spaces) of the docstring
* @param parseErrors a list to which parsing error messages are written
* @return the parsed docstring information
*/
static DocstringInfo parseDocstring(
String docstring, int indentation, List<DocstringParseError> parseErrors) {
DocstringParser parser = new DocstringParser(docstring, indentation);
DocstringInfo result = parser.parse();
parseErrors.addAll(parser.errors);
return result;
}
static class DocstringInfo {
/** The one-line summary at the start of the docstring. */
final String summary;
/** Documentation of function parameters from the 'Args:' section. */
final List<ParameterDoc> parameters;
/** Documentation of the return value from the 'Returns:' section, or empty if there is none. */
final String returns;
/** Deprecation warning from the 'Deprecated:' section, or empty if there is none. */
final String deprecated;
/** Rest of the docstring that is not part of any of the special sections above. */
final String longDescription;
public DocstringInfo(
String summary,
List<ParameterDoc> parameters,
String returns,
String deprecated,
String longDescription) {
this.summary = summary;
this.parameters = ImmutableList.copyOf(parameters);
this.returns = returns;
this.deprecated = deprecated;
this.longDescription = longDescription;
}
public boolean isSingleLineDocstring() {
return longDescription.isEmpty() && parameters.isEmpty() && returns.isEmpty();
}
}
static class ParameterDoc {
final String parameterName;
final List<String> attributes; // e.g. a type annotation, "unused", "mutable"
final String description;
public ParameterDoc(String parameterName, List<String> attributes, String description) {
this.parameterName = parameterName;
this.attributes = ImmutableList.copyOf(attributes);
this.description = description;
}
}
private static class DocstringParser {
private final String docstring;
/** Start offset of the current line. */
private int startOfLineOffset = 0;
/** End offset of the current line. */
private int endOfLineOffset = 0;
/** Current line number within the docstring. */
private int lineNumber = 0;
/**
* The indentation of the doctring literal in the source file.
*
* <p>Every line except the first one must be indented by at least that many spaces.
*/
private int baselineIndentation = 0;
/** Whether there was a blank line before the current line. */
private boolean blankLineBefore = false;
/** Whether we've seen a special section, e.g. 'Args:', already. */
private boolean specialSectionsStarted = false;
/** List of all parsed lines in the docstring so far, including all indentation. */
private ArrayList<String> originalLines = new ArrayList<>();
/**
* The current line in the docstring with the baseline indentation removed.
*
* <p>If the indentation of a docstring line is less than the expected {@link
* #baselineIndentation}, only the existing indentation is stripped; none of the remaining
* characters are cut off.
*/
private String line = "";
/** Errors that occurred so far. */
private final List<DocstringParseError> errors = new ArrayList<>();
DocstringParser(String docstring, int indentation) {
this.docstring = docstring;
nextLine();
// the indentation is only relevant for the following lines, not the first one:
this.baselineIndentation = indentation;
}
/**
* Move on to the next line and update the parser's internal state accordingly.
*
* @return whether there are lines remaining to be parsed
*/
private boolean nextLine() {
if (startOfLineOffset >= docstring.length()) {
return false;
}
blankLineBefore = line.trim().isEmpty();
startOfLineOffset = endOfLineOffset;
if (startOfLineOffset >= docstring.length()) {
// Previous line was the last; previous line had no trailing newline character.
line = "";
return false;
}
// If not the first line, advance start past the newline character. In the case where there is
// no more content, then the previous line was the second-to-last line and this last line is
// empty.
if (docstring.charAt(startOfLineOffset) == '\n') {
startOfLineOffset += 1;
}
lineNumber++;
endOfLineOffset = docstring.indexOf('\n', startOfLineOffset);
if (endOfLineOffset < 0) {
endOfLineOffset = docstring.length();
}
String originalLine = docstring.substring(startOfLineOffset, endOfLineOffset);
originalLines.add(originalLine);
int indentation = getIndentation(originalLine);
if (endOfLineOffset == docstring.length() && startOfLineOffset != 0) {
if (!originalLine.trim().isEmpty()) {
error("closing docstring quote should be on its own line, indented the same as the "
+ "opening quote");
} else if (indentation != baselineIndentation) {
error("closing docstring quote should be indented the same as the opening quote");
}
}
if (originalLine.trim().isEmpty()) {
line = "";
} else {
if (indentation < baselineIndentation) {
error(
"line indented too little (here: "
+ indentation
+ " spaces; expected: "
+ baselineIndentation
+ " spaces)");
startOfLineOffset += indentation;
} else {
startOfLineOffset += baselineIndentation;
}
line = docstring.substring(startOfLineOffset, endOfLineOffset);
}
return true;
}
/**
* Returns whether the current line is the last one in the docstring.
*
* <p>It is possible for both this function and {@link #eof} to return true if all content has
* been exhausted, or if the last line is empty.
*/
private boolean onLastLine() {
return endOfLineOffset >= docstring.length();
}
private boolean eof() {
return startOfLineOffset >= docstring.length();
}
private static int getIndentation(String line) {
int index = 0;
while (index < line.length() && line.charAt(index) == ' ') {
index++;
}
return index;
}
private void error(String message) {
error(this.lineNumber, message);
}
private void error(int lineNumber, String message) {
errors.add(new DocstringParseError(message, lineNumber, originalLines.get(lineNumber - 1)));
}
DocstringInfo parse() {
String summary = line;
String nonStandardDeprecation = checkForNonStandardDeprecation(line);
if (!nextLine()) {
return new DocstringInfo(summary, Collections.emptyList(), "", nonStandardDeprecation, "");
}
if (!line.isEmpty()) {
error("the one-line summary should be followed by a blank line");
} else {
nextLine();
}
List<String> longDescriptionLines = new ArrayList<>();
List<ParameterDoc> params = new ArrayList<>();
String returns = "";
String deprecated = "";
boolean descriptionBodyAfterSpecialSectionsReported = false;
while (!eof()) {
switch (line) {
case "Args:":
checkSectionStart(!params.isEmpty());
if (!returns.isEmpty()) {
error("'Args:' section should go before the 'Returns:' section");
}
if (!deprecated.isEmpty()) {
error("'Args:' section should go before the 'Deprecated:' section");
}
params.addAll(parseParameters());
break;
case "Returns:":
checkSectionStart(!returns.isEmpty());
if (!deprecated.isEmpty()) {
error("'Returns:' section should go before the 'Deprecated:' section");
}
returns = parseSectionAfterHeading();
break;
case "Deprecated:":
checkSectionStart(!deprecated.isEmpty());
deprecated = parseSectionAfterHeading();
break;
default:
if (specialSectionsStarted && !descriptionBodyAfterSpecialSectionsReported) {
error("description body should go before the special sections");
descriptionBodyAfterSpecialSectionsReported = true;
}
if (deprecated.isEmpty() && nonStandardDeprecation.isEmpty()) {
nonStandardDeprecation = checkForNonStandardDeprecation(line);
}
if (!(onLastLine() && line.trim().isEmpty())) {
longDescriptionLines.add(line);
}
nextLine();
}
}
if (deprecated.isEmpty()) {
deprecated = nonStandardDeprecation;
}
return new DocstringInfo(
summary, params, returns, deprecated, String.join("\n", longDescriptionLines));
}
private void checkSectionStart(boolean duplicateSection) {
specialSectionsStarted = true;
if (!blankLineBefore) {
error("section should be preceded by a blank line");
}
if (duplicateSection) {
error("duplicate '" + line + "' section");
}
}
private String checkForNonStandardDeprecation(String line) {
if (line.toLowerCase().startsWith("deprecated:") || line.contains("DEPRECATED")) {
error("use a 'Deprecated:' section for deprecations, similar to a 'Returns:' section");
return line;
}
return "";
}
private static final Pattern paramLineMatcher =
Pattern.compile(
"\\s*(?<name>[*\\w]+)( \\(\\s*(?<attributes>.*)\\s*\\))?: (?<description>.*)");
private static final Pattern attributesSeparator = Pattern.compile("\\s*,\\s*");
private List<ParameterDoc> parseParameters() {
int sectionLineNumber = lineNumber;
nextLine();
List<ParameterDoc> params = new ArrayList<>();
int expectedParamLineIndentation = -1;
while (!eof()) {
if (line.isEmpty()) {
nextLine();
continue;
}
int actualIndentation = getIndentation(line);
if (actualIndentation == 0) {
if (!blankLineBefore) {
error("end of 'Args' section without blank line");
}
break;
}
String trimmedLine;
if (expectedParamLineIndentation == -1) {
expectedParamLineIndentation = actualIndentation;
}
if (expectedParamLineIndentation != actualIndentation) {
error(
"inconsistent indentation of parameter lines (before: "
+ expectedParamLineIndentation
+ "; here: "
+ actualIndentation
+ " spaces)");
}
int paramLineNumber = lineNumber;
trimmedLine = line.substring(actualIndentation);
Matcher matcher = paramLineMatcher.matcher(trimmedLine);
if (!matcher.matches()) {
error("invalid parameter documentation");
nextLine();
continue;
}
String parameterName = Preconditions.checkNotNull(matcher.group("name"));
String attributesString = matcher.group("attributes");
StringBuilder description = new StringBuilder(matcher.group("description"));
List<String> attributes =
attributesString == null
? Collections.emptyList()
: Arrays.asList(attributesSeparator.split(attributesString));
parseContinuedParamDescription(actualIndentation, description);
String parameterDescription = description.toString().trim();
if (parameterDescription.isEmpty()) {
error(paramLineNumber, "empty parameter description for '" + parameterName + "'");
}
params.add(new ParameterDoc(parameterName, attributes, parameterDescription));
}
if (params.isEmpty()) {
error(sectionLineNumber, "section is empty");
}
return params;
}
/** Parses additional lines that can come after "param: foo" in an 'Args' section. */
private void parseContinuedParamDescription(
int baselineIndentation, StringBuilder description) {
while (nextLine()) {
if (line.isEmpty()) {
description.append('\n');
continue;
}
if (getIndentation(line) <= baselineIndentation) {
break;
}
String trimmedLine = line.substring(baselineIndentation);
description.append('\n');
description.append(trimmedLine);
}
}
private String parseSectionAfterHeading() {
int sectionLineNumber = lineNumber;
nextLine();
StringBuilder contents = new StringBuilder();
boolean firstLine = true;
while (!eof()) {
String trimmedLine;
if (line.isEmpty()) {
trimmedLine = line;
} else if (getIndentation(line) == 0) {
if (!blankLineBefore) {
error("end of section without blank line");
}
break;
} else {
if (getIndentation(line) < 2) {
error(
"text in a section has to be indented by two spaces"
+ " (relative to the left margin of the docstring)");
trimmedLine = line.substring(getIndentation(line));
} else {
trimmedLine = line.substring(2);
}
}
if (!firstLine) {
contents.append('\n');
}
contents.append(trimmedLine);
nextLine();
firstLine = false;
}
String result = contents.toString().trim();
if (result.isEmpty()) {
error(sectionLineNumber, "section is empty");
}
return result;
}
}
static class DocstringParseError {
final String message;
final int lineNumber;
final String line;
public DocstringParseError(String message, int lineNumber, String line) {
this.message = message;
this.lineNumber = lineNumber;
this.line = line;
}
@Override
public String toString() {
return lineNumber + ": " + message;
}
}
}
| |
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sun.org.apache.xpath.internal.res;
import java.util.ListResourceBundle;
/**
* Set up error messages.
* We build a two dimensional array of message keys and
* message strings. In order to add a new message here,
* you need to first add a Static string constant for the
* Key and update the contents array with Key, Value pair
* Also you need to update the count of messages(MAX_CODE)or
* the count of warnings(MAX_WARNING) [ Information purpose only]
* @xsl.usage advanced
*/
public class XPATHErrorResources_es extends ListResourceBundle
{
/*
* General notes to translators:
*
* This file contains error and warning messages related to XPath Error
* Handling.
*
* 1) Xalan (or more properly, Xalan-interpretive) and XSLTC are names of
* components.
* XSLT is an acronym for "XML Stylesheet Language: Transformations".
* XSLTC is an acronym for XSLT Compiler.
*
* 2) A stylesheet is a description of how to transform an input XML document
* into a resultant XML document (or HTML document or text). The
* stylesheet itself is described in the form of an XML document.
*
* 3) A template is a component of a stylesheet that is used to match a
* particular portion of an input document and specifies the form of the
* corresponding portion of the output document.
*
* 4) An element is a mark-up tag in an XML document; an attribute is a
* modifier on the tag. For example, in <elem attr='val' attr2='val2'>
* "elem" is an element name, "attr" and "attr2" are attribute names with
* the values "val" and "val2", respectively.
*
* 5) A namespace declaration is a special attribute that is used to associate
* a prefix with a URI (the namespace). The meanings of element names and
* attribute names that use that prefix are defined with respect to that
* namespace.
*
* 6) "Translet" is an invented term that describes the class file that
* results from compiling an XML stylesheet into a Java class.
*
* 7) XPath is a specification that describes a notation for identifying
* nodes in a tree-structured representation of an XML document. An
* instance of that notation is referred to as an XPath expression.
*
* 8) The context node is the node in the document with respect to which an
* XPath expression is being evaluated.
*
* 9) An iterator is an object that traverses nodes in the tree, one at a time.
*
* 10) NCName is an XML term used to describe a name that does not contain a
* colon (a "no-colon name").
*
* 11) QName is an XML term meaning "qualified name".
*/
/*
* static variables
*/
public static final String ERROR0000 = "ERROR0000";
public static final String ER_CURRENT_NOT_ALLOWED_IN_MATCH =
"ER_CURRENT_NOT_ALLOWED_IN_MATCH";
public static final String ER_CURRENT_TAKES_NO_ARGS =
"ER_CURRENT_TAKES_NO_ARGS";
public static final String ER_DOCUMENT_REPLACED = "ER_DOCUMENT_REPLACED";
public static final String ER_CONTEXT_HAS_NO_OWNERDOC =
"ER_CONTEXT_HAS_NO_OWNERDOC";
public static final String ER_LOCALNAME_HAS_TOO_MANY_ARGS =
"ER_LOCALNAME_HAS_TOO_MANY_ARGS";
public static final String ER_NAMESPACEURI_HAS_TOO_MANY_ARGS =
"ER_NAMESPACEURI_HAS_TOO_MANY_ARGS";
public static final String ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS =
"ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS";
public static final String ER_NUMBER_HAS_TOO_MANY_ARGS =
"ER_NUMBER_HAS_TOO_MANY_ARGS";
public static final String ER_NAME_HAS_TOO_MANY_ARGS =
"ER_NAME_HAS_TOO_MANY_ARGS";
public static final String ER_STRING_HAS_TOO_MANY_ARGS =
"ER_STRING_HAS_TOO_MANY_ARGS";
public static final String ER_STRINGLENGTH_HAS_TOO_MANY_ARGS =
"ER_STRINGLENGTH_HAS_TOO_MANY_ARGS";
public static final String ER_TRANSLATE_TAKES_3_ARGS =
"ER_TRANSLATE_TAKES_3_ARGS";
public static final String ER_UNPARSEDENTITYURI_TAKES_1_ARG =
"ER_UNPARSEDENTITYURI_TAKES_1_ARG";
public static final String ER_NAMESPACEAXIS_NOT_IMPLEMENTED =
"ER_NAMESPACEAXIS_NOT_IMPLEMENTED";
public static final String ER_UNKNOWN_AXIS = "ER_UNKNOWN_AXIS";
public static final String ER_UNKNOWN_MATCH_OPERATION =
"ER_UNKNOWN_MATCH_OPERATION";
public static final String ER_INCORRECT_ARG_LENGTH ="ER_INCORRECT_ARG_LENGTH";
public static final String ER_CANT_CONVERT_TO_NUMBER =
"ER_CANT_CONVERT_TO_NUMBER";
public static final String ER_CANT_CONVERT_XPATHRESULTTYPE_TO_NUMBER =
"ER_CANT_CONVERT_XPATHRESULTTYPE_TO_NUMBER";
public static final String ER_CANT_CONVERT_TO_NODELIST =
"ER_CANT_CONVERT_TO_NODELIST";
public static final String ER_CANT_CONVERT_TO_MUTABLENODELIST =
"ER_CANT_CONVERT_TO_MUTABLENODELIST";
public static final String ER_CANT_CONVERT_TO_TYPE ="ER_CANT_CONVERT_TO_TYPE";
public static final String ER_EXPECTED_MATCH_PATTERN =
"ER_EXPECTED_MATCH_PATTERN";
public static final String ER_COULDNOT_GET_VAR_NAMED =
"ER_COULDNOT_GET_VAR_NAMED";
public static final String ER_UNKNOWN_OPCODE = "ER_UNKNOWN_OPCODE";
public static final String ER_EXTRA_ILLEGAL_TOKENS ="ER_EXTRA_ILLEGAL_TOKENS";
public static final String ER_EXPECTED_DOUBLE_QUOTE =
"ER_EXPECTED_DOUBLE_QUOTE";
public static final String ER_EXPECTED_SINGLE_QUOTE =
"ER_EXPECTED_SINGLE_QUOTE";
public static final String ER_EMPTY_EXPRESSION = "ER_EMPTY_EXPRESSION";
public static final String ER_EXPECTED_BUT_FOUND = "ER_EXPECTED_BUT_FOUND";
public static final String ER_INCORRECT_PROGRAMMER_ASSERTION =
"ER_INCORRECT_PROGRAMMER_ASSERTION";
public static final String ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL =
"ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL";
public static final String ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG =
"ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG";
public static final String ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG =
"ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG";
public static final String ER_PREDICATE_ILLEGAL_SYNTAX =
"ER_PREDICATE_ILLEGAL_SYNTAX";
public static final String ER_ILLEGAL_AXIS_NAME = "ER_ILLEGAL_AXIS_NAME";
public static final String ER_UNKNOWN_NODETYPE = "ER_UNKNOWN_NODETYPE";
public static final String ER_PATTERN_LITERAL_NEEDS_BE_QUOTED =
"ER_PATTERN_LITERAL_NEEDS_BE_QUOTED";
public static final String ER_COULDNOT_BE_FORMATTED_TO_NUMBER =
"ER_COULDNOT_BE_FORMATTED_TO_NUMBER";
public static final String ER_COULDNOT_CREATE_XMLPROCESSORLIAISON =
"ER_COULDNOT_CREATE_XMLPROCESSORLIAISON";
public static final String ER_DIDNOT_FIND_XPATH_SELECT_EXP =
"ER_DIDNOT_FIND_XPATH_SELECT_EXP";
public static final String ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH =
"ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH";
public static final String ER_ERROR_OCCURED = "ER_ERROR_OCCURED";
public static final String ER_ILLEGAL_VARIABLE_REFERENCE =
"ER_ILLEGAL_VARIABLE_REFERENCE";
public static final String ER_AXES_NOT_ALLOWED = "ER_AXES_NOT_ALLOWED";
public static final String ER_KEY_HAS_TOO_MANY_ARGS =
"ER_KEY_HAS_TOO_MANY_ARGS";
public static final String ER_COUNT_TAKES_1_ARG = "ER_COUNT_TAKES_1_ARG";
public static final String ER_COULDNOT_FIND_FUNCTION =
"ER_COULDNOT_FIND_FUNCTION";
public static final String ER_UNSUPPORTED_ENCODING ="ER_UNSUPPORTED_ENCODING";
public static final String ER_PROBLEM_IN_DTM_NEXTSIBLING =
"ER_PROBLEM_IN_DTM_NEXTSIBLING";
public static final String ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL =
"ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL";
public static final String ER_SETDOMFACTORY_NOT_SUPPORTED =
"ER_SETDOMFACTORY_NOT_SUPPORTED";
public static final String ER_PREFIX_MUST_RESOLVE = "ER_PREFIX_MUST_RESOLVE";
public static final String ER_PARSE_NOT_SUPPORTED = "ER_PARSE_NOT_SUPPORTED";
public static final String ER_SAX_API_NOT_HANDLED = "ER_SAX_API_NOT_HANDLED";
public static final String ER_IGNORABLE_WHITESPACE_NOT_HANDLED =
"ER_IGNORABLE_WHITESPACE_NOT_HANDLED";
public static final String ER_DTM_CANNOT_HANDLE_NODES =
"ER_DTM_CANNOT_HANDLE_NODES";
public static final String ER_XERCES_CANNOT_HANDLE_NODES =
"ER_XERCES_CANNOT_HANDLE_NODES";
public static final String ER_XERCES_PARSE_ERROR_DETAILS =
"ER_XERCES_PARSE_ERROR_DETAILS";
public static final String ER_XERCES_PARSE_ERROR = "ER_XERCES_PARSE_ERROR";
public static final String ER_INVALID_UTF16_SURROGATE =
"ER_INVALID_UTF16_SURROGATE";
public static final String ER_OIERROR = "ER_OIERROR";
public static final String ER_CANNOT_CREATE_URL = "ER_CANNOT_CREATE_URL";
public static final String ER_XPATH_READOBJECT = "ER_XPATH_READOBJECT";
public static final String ER_FUNCTION_TOKEN_NOT_FOUND =
"ER_FUNCTION_TOKEN_NOT_FOUND";
public static final String ER_CANNOT_DEAL_XPATH_TYPE =
"ER_CANNOT_DEAL_XPATH_TYPE";
public static final String ER_NODESET_NOT_MUTABLE = "ER_NODESET_NOT_MUTABLE";
public static final String ER_NODESETDTM_NOT_MUTABLE =
"ER_NODESETDTM_NOT_MUTABLE";
/** Variable not resolvable: */
public static final String ER_VAR_NOT_RESOLVABLE = "ER_VAR_NOT_RESOLVABLE";
/** Null error handler */
public static final String ER_NULL_ERROR_HANDLER = "ER_NULL_ERROR_HANDLER";
/** Programmer's assertion: unknown opcode */
public static final String ER_PROG_ASSERT_UNKNOWN_OPCODE =
"ER_PROG_ASSERT_UNKNOWN_OPCODE";
/** 0 or 1 */
public static final String ER_ZERO_OR_ONE = "ER_ZERO_OR_ONE";
/** rtf() not supported by XRTreeFragSelectWrapper */
public static final String ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER =
"ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER";
/** asNodeIterator() not supported by XRTreeFragSelectWrapper */
public static final String ER_ASNODEITERATOR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER = "ER_ASNODEITERATOR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER";
/** fsb() not supported for XStringForChars */
public static final String ER_FSB_NOT_SUPPORTED_XSTRINGFORCHARS =
"ER_FSB_NOT_SUPPORTED_XSTRINGFORCHARS";
/** Could not find variable with the name of */
public static final String ER_COULD_NOT_FIND_VAR = "ER_COULD_NOT_FIND_VAR";
/** XStringForChars can not take a string for an argument */
public static final String ER_XSTRINGFORCHARS_CANNOT_TAKE_STRING =
"ER_XSTRINGFORCHARS_CANNOT_TAKE_STRING";
/** The FastStringBuffer argument can not be null */
public static final String ER_FASTSTRINGBUFFER_CANNOT_BE_NULL =
"ER_FASTSTRINGBUFFER_CANNOT_BE_NULL";
/** 2 or 3 */
public static final String ER_TWO_OR_THREE = "ER_TWO_OR_THREE";
/** Variable accessed before it is bound! */
public static final String ER_VARIABLE_ACCESSED_BEFORE_BIND =
"ER_VARIABLE_ACCESSED_BEFORE_BIND";
/** XStringForFSB can not take a string for an argument! */
public static final String ER_FSB_CANNOT_TAKE_STRING =
"ER_FSB_CANNOT_TAKE_STRING";
/** Error! Setting the root of a walker to null! */
public static final String ER_SETTING_WALKER_ROOT_TO_NULL =
"ER_SETTING_WALKER_ROOT_TO_NULL";
/** This NodeSetDTM can not iterate to a previous node! */
public static final String ER_NODESETDTM_CANNOT_ITERATE =
"ER_NODESETDTM_CANNOT_ITERATE";
/** This NodeSet can not iterate to a previous node! */
public static final String ER_NODESET_CANNOT_ITERATE =
"ER_NODESET_CANNOT_ITERATE";
/** This NodeSetDTM can not do indexing or counting functions! */
public static final String ER_NODESETDTM_CANNOT_INDEX =
"ER_NODESETDTM_CANNOT_INDEX";
/** This NodeSet can not do indexing or counting functions! */
public static final String ER_NODESET_CANNOT_INDEX =
"ER_NODESET_CANNOT_INDEX";
/** Can not call setShouldCacheNodes after nextNode has been called! */
public static final String ER_CANNOT_CALL_SETSHOULDCACHENODE =
"ER_CANNOT_CALL_SETSHOULDCACHENODE";
/** {0} only allows {1} arguments */
public static final String ER_ONLY_ALLOWS = "ER_ONLY_ALLOWS";
/** Programmer's assertion in getNextStepPos: unknown stepType: {0} */
public static final String ER_UNKNOWN_STEP = "ER_UNKNOWN_STEP";
/** Problem with RelativeLocationPath */
public static final String ER_EXPECTED_REL_LOC_PATH =
"ER_EXPECTED_REL_LOC_PATH";
/** Problem with LocationPath */
public static final String ER_EXPECTED_LOC_PATH = "ER_EXPECTED_LOC_PATH";
public static final String ER_EXPECTED_LOC_PATH_AT_END_EXPR =
"ER_EXPECTED_LOC_PATH_AT_END_EXPR";
/** Problem with Step */
public static final String ER_EXPECTED_LOC_STEP = "ER_EXPECTED_LOC_STEP";
/** Problem with NodeTest */
public static final String ER_EXPECTED_NODE_TEST = "ER_EXPECTED_NODE_TEST";
/** Expected step pattern */
public static final String ER_EXPECTED_STEP_PATTERN =
"ER_EXPECTED_STEP_PATTERN";
/** Expected relative path pattern */
public static final String ER_EXPECTED_REL_PATH_PATTERN =
"ER_EXPECTED_REL_PATH_PATTERN";
/** ER_CANT_CONVERT_XPATHRESULTTYPE_TO_BOOLEAN */
public static final String ER_CANT_CONVERT_TO_BOOLEAN =
"ER_CANT_CONVERT_TO_BOOLEAN";
/** Field ER_CANT_CONVERT_TO_SINGLENODE */
public static final String ER_CANT_CONVERT_TO_SINGLENODE =
"ER_CANT_CONVERT_TO_SINGLENODE";
/** Field ER_CANT_GET_SNAPSHOT_LENGTH */
public static final String ER_CANT_GET_SNAPSHOT_LENGTH =
"ER_CANT_GET_SNAPSHOT_LENGTH";
/** Field ER_NON_ITERATOR_TYPE */
public static final String ER_NON_ITERATOR_TYPE = "ER_NON_ITERATOR_TYPE";
/** Field ER_DOC_MUTATED */
public static final String ER_DOC_MUTATED = "ER_DOC_MUTATED";
public static final String ER_INVALID_XPATH_TYPE = "ER_INVALID_XPATH_TYPE";
public static final String ER_EMPTY_XPATH_RESULT = "ER_EMPTY_XPATH_RESULT";
public static final String ER_INCOMPATIBLE_TYPES = "ER_INCOMPATIBLE_TYPES";
public static final String ER_NULL_RESOLVER = "ER_NULL_RESOLVER";
public static final String ER_CANT_CONVERT_TO_STRING =
"ER_CANT_CONVERT_TO_STRING";
public static final String ER_NON_SNAPSHOT_TYPE = "ER_NON_SNAPSHOT_TYPE";
public static final String ER_WRONG_DOCUMENT = "ER_WRONG_DOCUMENT";
/* Note to translators: The XPath expression cannot be evaluated with respect
* to this type of node.
*/
/** Field ER_WRONG_NODETYPE */
public static final String ER_WRONG_NODETYPE = "ER_WRONG_NODETYPE";
public static final String ER_XPATH_ERROR = "ER_XPATH_ERROR";
//BEGIN: Keys needed for exception messages of JAXP 1.3 XPath API implementation
public static final String ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED = "ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED";
public static final String ER_RESOLVE_VARIABLE_RETURNS_NULL = "ER_RESOLVE_VARIABLE_RETURNS_NULL";
public static final String ER_UNSUPPORTED_RETURN_TYPE = "ER_UNSUPPORTED_RETURN_TYPE";
public static final String ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL = "ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL";
public static final String ER_ARG_CANNOT_BE_NULL = "ER_ARG_CANNOT_BE_NULL";
public static final String ER_OBJECT_MODEL_NULL = "ER_OBJECT_MODEL_NULL";
public static final String ER_OBJECT_MODEL_EMPTY = "ER_OBJECT_MODEL_EMPTY";
public static final String ER_FEATURE_NAME_NULL = "ER_FEATURE_NAME_NULL";
public static final String ER_FEATURE_UNKNOWN = "ER_FEATURE_UNKNOWN";
public static final String ER_GETTING_NULL_FEATURE = "ER_GETTING_NULL_FEATURE";
public static final String ER_GETTING_UNKNOWN_FEATURE = "ER_GETTING_UNKNOWN_FEATURE";
public static final String ER_SECUREPROCESSING_FEATURE = "ER_SECUREPROCESSING_FEATURE";
public static final String ER_NULL_XPATH_FUNCTION_RESOLVER = "ER_NULL_XPATH_FUNCTION_RESOLVER";
public static final String ER_NULL_XPATH_VARIABLE_RESOLVER = "ER_NULL_XPATH_VARIABLE_RESOLVER";
//END: Keys needed for exception messages of JAXP 1.3 XPath API implementation
public static final String WG_LOCALE_NAME_NOT_HANDLED =
"WG_LOCALE_NAME_NOT_HANDLED";
public static final String WG_PROPERTY_NOT_SUPPORTED =
"WG_PROPERTY_NOT_SUPPORTED";
public static final String WG_DONT_DO_ANYTHING_WITH_NS =
"WG_DONT_DO_ANYTHING_WITH_NS";
public static final String WG_SECURITY_EXCEPTION = "WG_SECURITY_EXCEPTION";
public static final String WG_QUO_NO_LONGER_DEFINED =
"WG_QUO_NO_LONGER_DEFINED";
public static final String WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST =
"WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST";
public static final String WG_FUNCTION_TOKEN_NOT_FOUND =
"WG_FUNCTION_TOKEN_NOT_FOUND";
public static final String WG_COULDNOT_FIND_FUNCTION =
"WG_COULDNOT_FIND_FUNCTION";
public static final String WG_CANNOT_MAKE_URL_FROM ="WG_CANNOT_MAKE_URL_FROM";
public static final String WG_EXPAND_ENTITIES_NOT_SUPPORTED =
"WG_EXPAND_ENTITIES_NOT_SUPPORTED";
public static final String WG_ILLEGAL_VARIABLE_REFERENCE =
"WG_ILLEGAL_VARIABLE_REFERENCE";
public static final String WG_UNSUPPORTED_ENCODING ="WG_UNSUPPORTED_ENCODING";
/** detach() not supported by XRTreeFragSelectWrapper */
public static final String ER_DETACH_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER =
"ER_DETACH_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER";
/** num() not supported by XRTreeFragSelectWrapper */
public static final String ER_NUM_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER =
"ER_NUM_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER";
/** xstr() not supported by XRTreeFragSelectWrapper */
public static final String ER_XSTR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER =
"ER_XSTR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER";
/** str() not supported by XRTreeFragSelectWrapper */
public static final String ER_STR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER =
"ER_STR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER";
// Error messages...
private static final Object[][] _contents = new Object[][]{
{ "ERROR0000" , "{0}" },
{ ER_CURRENT_NOT_ALLOWED_IN_MATCH, "La funci\u00F3n current() no est\u00E1 permitida en un patr\u00F3n de coincidencia." },
{ ER_CURRENT_TAKES_NO_ARGS, "La funci\u00F3n current() no acepta argumentos." },
{ ER_DOCUMENT_REPLACED,
"La implantaci\u00F3n de la funci\u00F3n document() se ha sustituido por com.sun.org.apache.xalan.internal.xslt.FuncDocument!"},
{ ER_CONTEXT_HAS_NO_OWNERDOC,
"El contexto no tiene un documento de propietario."},
{ ER_LOCALNAME_HAS_TOO_MANY_ARGS,
"local-name() tiene demasiados argumentos."},
{ ER_NAMESPACEURI_HAS_TOO_MANY_ARGS,
"namespace-uri() tiene demasiados argumentos."},
{ ER_NORMALIZESPACE_HAS_TOO_MANY_ARGS,
"normalize-space() tiene demasiados argumentos."},
{ ER_NUMBER_HAS_TOO_MANY_ARGS,
"number() tiene demasiados argumentos."},
{ ER_NAME_HAS_TOO_MANY_ARGS,
"name() tiene demasiados argumentos."},
{ ER_STRING_HAS_TOO_MANY_ARGS,
"string() tiene demasiados argumentos."},
{ ER_STRINGLENGTH_HAS_TOO_MANY_ARGS,
"string-length() tiene demasiados argumentos."},
{ ER_TRANSLATE_TAKES_3_ARGS,
"La funci\u00F3n translate() necesita tres argumentos."},
{ ER_UNPARSEDENTITYURI_TAKES_1_ARG,
"La funci\u00F3n unparsed-entity-uri necesita un argumento."},
{ ER_NAMESPACEAXIS_NOT_IMPLEMENTED,
"El eje de espacio de nombres no se ha implantado a\u00FAn."},
{ ER_UNKNOWN_AXIS,
"eje desconocido: {0}"},
{ ER_UNKNOWN_MATCH_OPERATION,
"Operaci\u00F3n de coincidencia desconocida."},
{ ER_INCORRECT_ARG_LENGTH,
"La longitud del argumento de la prueba del nodo processing-instruction() es incorrecta."},
{ ER_CANT_CONVERT_TO_NUMBER,
"No se puede convertir {0} en un n\u00FAmero"},
{ ER_CANT_CONVERT_TO_NODELIST,
"No se puede convertir {0} en una lista de nodos."},
{ ER_CANT_CONVERT_TO_MUTABLENODELIST,
"No se puede convertir {0} en un DTM de juego de nodos."},
{ ER_CANT_CONVERT_TO_TYPE,
"No se puede convertir {0} en el n\u00FAmero de tipo {1}"},
{ ER_EXPECTED_MATCH_PATTERN,
"Patr\u00F3n de coincidencia esperado en getMatchScore."},
{ ER_COULDNOT_GET_VAR_NAMED,
"No se ha encontrado la variable llamada {0}"},
{ ER_UNKNOWN_OPCODE,
"ERROR. C\u00F3digo de operaci\u00F3n desconocido: {0}"},
{ ER_EXTRA_ILLEGAL_TOKENS,
"Tokens no permitidos adicionales: {0}"},
{ ER_EXPECTED_DOUBLE_QUOTE,
"literal con comillas incorrectas... se esperaban comillas dobles"},
{ ER_EXPECTED_SINGLE_QUOTE,
"literal con comillas incorrectas... se esperaban comillas simples"},
{ ER_EMPTY_EXPRESSION,
"Expresi\u00F3n vac\u00EDa"},
{ ER_EXPECTED_BUT_FOUND,
"Se esperaba {0} pero se ha encontrado: {1}"},
{ ER_INCORRECT_PROGRAMMER_ASSERTION,
"La afirmaci\u00F3n del programador es incorrecta - {0}"},
{ ER_BOOLEAN_ARG_NO_LONGER_OPTIONAL,
"El argumento boolean(...) ya no es opcional con el borrador de XPath 19990709."},
{ ER_FOUND_COMMA_BUT_NO_PRECEDING_ARG,
"Se han encontrado ',' pero no va seguido de ning\u00FAn argumento"},
{ ER_FOUND_COMMA_BUT_NO_FOLLOWING_ARG,
"Se han encontrado ',' pero no le sigue ning\u00FAn argumento"},
{ ER_PREDICATE_ILLEGAL_SYNTAX,
"'..[predicate]' o '.[predicate]' es una sintaxis no v\u00E1lida. Utilice 'self::node()[predicate]' en su lugar."},
{ ER_ILLEGAL_AXIS_NAME,
"nombre de eje no permitido: {0}"},
{ ER_UNKNOWN_NODETYPE,
"Tipo de nodo desconocido: {0}"},
{ ER_PATTERN_LITERAL_NEEDS_BE_QUOTED,
"El patr\u00F3n literal ({0}) debe incluirse entre comillas"},
{ ER_COULDNOT_BE_FORMATTED_TO_NUMBER,
"{0} no se ha podido formatear en un n\u00FAmero."},
{ ER_COULDNOT_CREATE_XMLPROCESSORLIAISON,
"No se ha podido crear el enlace TransformerFactory XML: {0}"},
{ ER_DIDNOT_FIND_XPATH_SELECT_EXP,
"Error. No se ha encontrado la expresi\u00F3n de selecci\u00F3n xpath (-select)."},
{ ER_COULDNOT_FIND_ENDOP_AFTER_OPLOCATIONPATH,
"ERROR. No se ha encontrado ENDOP despu\u00E9s de OP_LOCATIONPATH"},
{ ER_ERROR_OCCURED,
"Se ha producido un error."},
{ ER_ILLEGAL_VARIABLE_REFERENCE,
"La referencia de variable proporcionada para la variable est\u00E1 fuera de contexto o no tiene definici\u00F3n. Nombre = {0}"},
{ ER_AXES_NOT_ALLOWED,
"S\u00F3lo los ejes child:: y attribute:: est\u00E1n permitidos en los patrones de coincidencia. Ejes incorrectos = {0}"},
{ ER_KEY_HAS_TOO_MANY_ARGS,
"key() tiene un n\u00FAmero incorrecto de argumentos."},
{ ER_COUNT_TAKES_1_ARG,
"La funci\u00F3n count necesita un argumento."},
{ ER_COULDNOT_FIND_FUNCTION,
"No se ha encontrado la funci\u00F3n: {0}"},
{ ER_UNSUPPORTED_ENCODING,
"Codificaci\u00F3n no soportada: {0}"},
{ ER_PROBLEM_IN_DTM_NEXTSIBLING,
"Se ha producido un problema en DTM en getNextSibling... intentando la recuperaci\u00F3n"},
{ ER_CANNOT_WRITE_TO_EMPTYNODELISTIMPL,
"Error de programador: no se puede escribir en EmptyNodeList."},
{ ER_SETDOMFACTORY_NOT_SUPPORTED,
"setDOMFactory no est\u00E1 soportado por XPathContext."},
{ ER_PREFIX_MUST_RESOLVE,
"El prefijo se debe resolver en un espacio de nombres: {0}"},
{ ER_PARSE_NOT_SUPPORTED,
"El an\u00E1lisis (origen de InputSource) no est\u00E1 soportado en XPathContext. No se puede abrir {0}"},
{ ER_SAX_API_NOT_HANDLED,
"Los caracteres de API SAX (char ch[]... no los gestiona el DTM."},
{ ER_IGNORABLE_WHITESPACE_NOT_HANDLED,
"ignorableWhitespace(char ch[]... no gestionado por DTM."},
{ ER_DTM_CANNOT_HANDLE_NODES,
"DTMLiaison no puede gestionar los nodos de tipo {0}"},
{ ER_XERCES_CANNOT_HANDLE_NODES,
"DOM2Helper no puede gestionar los nodos de tipo {0}"},
{ ER_XERCES_PARSE_ERROR_DETAILS,
"Error de DOM2Helper.parse: identificador de sistema - {0} l\u00EDnea - {1}"},
{ ER_XERCES_PARSE_ERROR,
"Error de DOM2Helper.parse"},
{ ER_INVALID_UTF16_SURROGATE,
"\u00BFSe ha detectado un sustituto UTF-16 no v\u00E1lido: {0}?"},
{ ER_OIERROR,
"Error de ES"},
{ ER_CANNOT_CREATE_URL,
"No se puede crear la URL para: {0}"},
{ ER_XPATH_READOBJECT,
"En XPath.readObject: {0}"},
{ ER_FUNCTION_TOKEN_NOT_FOUND,
"No se ha encontrado el token de funci\u00F3n."},
{ ER_CANNOT_DEAL_XPATH_TYPE,
"No se puede negociar con el tipo de XPath: {0}"},
{ ER_NODESET_NOT_MUTABLE,
"Este juego de nodos no es modificable"},
{ ER_NODESETDTM_NOT_MUTABLE,
"Este DTM de juego de nodos no es modificable"},
{ ER_VAR_NOT_RESOLVABLE,
"La variable no se puede resolver: {0}"},
{ ER_NULL_ERROR_HANDLER,
"Manejador de errores nulo"},
{ ER_PROG_ASSERT_UNKNOWN_OPCODE,
"Afirmaci\u00F3n del programador: c\u00F3digo de operaci\u00F3n desconocido: {0}"},
{ ER_ZERO_OR_ONE,
"0 o 1"},
{ ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER,
"rtf() no soportado por XRTreeFragSelectWrapper"},
{ ER_RTF_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER,
"asNodeIterator() no soportado por XRTreeFragSelectWrapper"},
/** detach() not supported by XRTreeFragSelectWrapper */
{ ER_DETACH_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER,
"detach() no soportado por XRTreeFragSelectWrapper"},
/** num() not supported by XRTreeFragSelectWrapper */
{ ER_NUM_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER,
"num() no soportado por XRTreeFragSelectWrapper"},
/** xstr() not supported by XRTreeFragSelectWrapper */
{ ER_XSTR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER,
"xstr() no soportado por XRTreeFragSelectWrapper"},
/** str() not supported by XRTreeFragSelectWrapper */
{ ER_STR_NOT_SUPPORTED_XRTREEFRAGSELECTWRAPPER,
"str() no soportado por XRTreeFragSelectWrapper"},
{ ER_FSB_NOT_SUPPORTED_XSTRINGFORCHARS,
"fsb() no soportado para XStringForChars"},
{ ER_COULD_NOT_FIND_VAR,
"No se ha encontrado la variable con el nombre de {0}"},
{ ER_XSTRINGFORCHARS_CANNOT_TAKE_STRING,
"XStringForChars no puede utilizar una cadena para un argumento"},
{ ER_FASTSTRINGBUFFER_CANNOT_BE_NULL,
"El argumento FastStringBuffer no puede ser nulo"},
{ ER_TWO_OR_THREE,
"2 o 3"},
{ ER_VARIABLE_ACCESSED_BEFORE_BIND,
"Se ha accedido a la variable antes de que se haya enlazado."},
{ ER_FSB_CANNOT_TAKE_STRING,
"XStringForFSB no puede utilizar una cadena para un argumento."},
{ ER_SETTING_WALKER_ROOT_TO_NULL,
"\n Error. Definici\u00F3n de una ra\u00EDz de un walker como nula."},
{ ER_NODESETDTM_CANNOT_ITERATE,
"Este DTM de juego de nodos no puede iterarse en un nodo anterior."},
{ ER_NODESET_CANNOT_ITERATE,
"Este juego de nodos no se puede iterar en un nodo anterior."},
{ ER_NODESETDTM_CANNOT_INDEX,
"Este DTM de juego de nodos no puede realizar funciones de indexaci\u00F3n o recuento."},
{ ER_NODESET_CANNOT_INDEX,
"Este juego de nodos no puede realizar funciones de indexaci\u00F3n o recuento."},
{ ER_CANNOT_CALL_SETSHOULDCACHENODE,
"No se puede llamar a setShouldCacheNodes despu\u00E9s de haber llamado a nextNode."},
{ ER_ONLY_ALLOWS,
"{0} s\u00F3lo permite {1} argumentos"},
{ ER_UNKNOWN_STEP,
"Afirmaci\u00F3n del programador en getNextStepPos: tipo de paso desconocido: {0}"},
//Note to translators: A relative location path is a form of XPath expression.
// The message indicates that such an expression was expected following the
// characters '/' or '//', but was not found.
{ ER_EXPECTED_REL_LOC_PATH,
"Se esperaba una ruta de acceso de ubicaci\u00F3n relativa despu\u00E9s del token '/' o '//'."},
// Note to translators: A location path is a form of XPath expression.
// The message indicates that syntactically such an expression was expected,but
// the characters specified by the substitution text were encountered instead.
{ ER_EXPECTED_LOC_PATH,
"Se esperaba una ruta de acceso de ubicaci\u00F3n, pero se ha encontrado el siguiente token: {0}"},
// Note to translators: A location path is a form of XPath expression.
// The message indicates that syntactically such a subexpression was expected,
// but no more characters were found in the expression.
{ ER_EXPECTED_LOC_PATH_AT_END_EXPR,
"Se esperaba una ruta de acceso de ubicaci\u00F3n, pero se ha encontrado el final de la expresi\u00F3n XPath en su lugar."},
// Note to translators: A location step is part of an XPath expression.
// The message indicates that syntactically such an expression was expected
// following the specified characters.
{ ER_EXPECTED_LOC_STEP,
"Se esperaba un paso de ubicaci\u00F3n despu\u00E9s del token '/' o '//'."},
// Note to translators: A node test is part of an XPath expression that is
// used to test for particular kinds of nodes. In this case, a node test that
// consists of an NCName followed by a colon and an asterisk or that consists
// of a QName was expected, but was not found.
{ ER_EXPECTED_NODE_TEST,
"Se esperaba una prueba de nodo que coincidiera con el NCName:* o QName."},
// Note to translators: A step pattern is part of an XPath expression.
// The message indicates that syntactically such an expression was expected,
// but the specified character was found in the expression instead.
{ ER_EXPECTED_STEP_PATTERN,
"Se esperaba un patr\u00F3n de paso, pero se ha encontrado '/'."},
// Note to translators: A relative path pattern is part of an XPath expression.
// The message indicates that syntactically such an expression was expected,
// but was not found.
{ ER_EXPECTED_REL_PATH_PATTERN,
"Se esperaba un patr\u00F3n de ruta de acceso relativa."},
// Note to translators: The substitution text is the name of a data type. The
// message indicates that a value of a particular type could not be converted
// to a value of type boolean.
{ ER_CANT_CONVERT_TO_BOOLEAN,
"El valor de XPathResult de la expresi\u00F3n XPath ''{0}'' tiene un valor de XPathResultType de {1} que no se puede convertir en un valor booleano."},
// Note to translators: Do not translate ANY_UNORDERED_NODE_TYPE and
// FIRST_ORDERED_NODE_TYPE.
{ ER_CANT_CONVERT_TO_SINGLENODE,
"El valor de XPathResult de la expresi\u00F3n XPath ''{0}'' tiene un valor de XPathResultType de {1} que no se puede convertir a un nodo \u00FAnico. El m\u00E9todo getSingleNodeValue se aplica s\u00F3lo a los tipos ANY_UNORDERED_NODE_TYPE y FIRST_ORDERED_NODE_TYPE."},
// Note to translators: Do not translate UNORDERED_NODE_SNAPSHOT_TYPE and
// ORDERED_NODE_SNAPSHOT_TYPE.
{ ER_CANT_GET_SNAPSHOT_LENGTH,
"No se puede llamar al m\u00E9todo getSnapshotLength en la expresi\u00F3n XPathResult de XPath ''{0}'' porque el valor de su XPathResultType es {1}. Este m\u00E9todo se aplica s\u00F3lo a los tipos UNORDERED_NODE_SNAPSHOT_TYPE y ORDERED_NODE_SNAPSHOT_TYPE."},
{ ER_NON_ITERATOR_TYPE,
"No se puede llamar al m\u00E9todo iterateNext en el XPathResult de la expresi\u00F3n XPath ''{0}'' porque el valor de su XPathResultType es {1}. Este m\u00E9todo se aplica s\u00F3lo a los tipos UNORDERED_NODE_ITERATOR_TYPE y ORDERED_NODE_ITERATOR_TYPE."},
// Note to translators: This message indicates that the document being operated
// upon changed, so the iterator object that was being used to traverse the
// document has now become invalid.
{ ER_DOC_MUTATED,
"Documento mutado debido a que se ha devuelto el resultado. El iterador no es v\u00E1lido."},
{ ER_INVALID_XPATH_TYPE,
"Argumento de tipo XPath no v\u00E1lido: {0}"},
{ ER_EMPTY_XPATH_RESULT,
"Objeto de resultado XPath vac\u00EDo"},
{ ER_INCOMPATIBLE_TYPES,
"El valor de XPathResult de la expresi\u00F3n XPath ''{0}'' tiene un valor de XPathResultType de {1} que no se puede forzar en el XPathResultType especificado de {2}."},
{ ER_NULL_RESOLVER,
"No se ha podido resolver el prefijo con el sistema de resoluci\u00F3n de prefijos nulo."},
// Note to translators: The substitution text is the name of a data type. The
// message indicates that a value of a particular type could not be converted
// to a value of type string.
{ ER_CANT_CONVERT_TO_STRING,
"El valor de XPathResult de la expresi\u00F3n XPath ''{0}'' tiene un valor de XPathResultType de {1} que no se puede convertir en una cadena."},
// Note to translators: Do not translate snapshotItem,
// UNORDERED_NODE_SNAPSHOT_TYPE and ORDERED_NODE_SNAPSHOT_TYPE.
{ ER_NON_SNAPSHOT_TYPE,
"No se puede llamar al m\u00E9todo snapshotItem en la expresi\u00F3n XPathResult de XPath ''{0}'' porque el valor de su XPathResultType es {1}. Este m\u00E9todo se aplica s\u00F3lo a los tipos UNORDERED_NODE_SNAPSHOT_TYPE y ORDERED_NODE_SNAPSHOT_TYPE."},
// Note to translators: XPathEvaluator is a Java interface name. An
// XPathEvaluator is created with respect to a particular XML document, and in
// this case the expression represented by this object was being evaluated with
// respect to a context node from a different document.
{ ER_WRONG_DOCUMENT,
"El nodo de contexto no pertenece al documento que est\u00E1 enlazado a este XPathEvaluator."},
// Note to translators: The XPath expression cannot be evaluated with respect
// to this type of node.
{ ER_WRONG_NODETYPE,
"El tipo de nodo de contexto no est\u00E1 soportado."},
{ ER_XPATH_ERROR,
"Error desconocido en XPath."},
{ ER_CANT_CONVERT_XPATHRESULTTYPE_TO_NUMBER,
"El valor de XPathResult de la expresi\u00F3n XPath ''{0}'' tiene un valor de XPathResultType de {1} que no se puede convertir en un n\u00FAmero"},
//BEGIN: Definitions of error keys used in exception messages of JAXP 1.3 XPath API implementation
/** Field ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED */
{ ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED,
"Funci\u00F3n de extensi\u00F3n: no se puede llamar a ''{0}'' cuando la funci\u00F3n XMLConstants.FEATURE_SECURE_PROCESSING est\u00E1 definida en true."},
/** Field ER_RESOLVE_VARIABLE_RETURNS_NULL */
{ ER_RESOLVE_VARIABLE_RETURNS_NULL,
"resolveVariable para la variable {0} devuelve un valor nulo"},
/** Field ER_UNSUPPORTED_RETURN_TYPE */
{ ER_UNSUPPORTED_RETURN_TYPE,
"Tipo de retorno no soportado: {0}"},
/** Field ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL */
{ ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL,
"El tipo de origen y/o retorno no puede ser nulo"},
/** Field ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL */
{ ER_SOURCE_RETURN_TYPE_CANNOT_BE_NULL,
"El tipo de origen y/o retorno no puede ser nulo"},
/** Field ER_ARG_CANNOT_BE_NULL */
{ ER_ARG_CANNOT_BE_NULL,
"El argumento {0} no puede ser nulo"},
/** Field ER_OBJECT_MODEL_NULL */
{ ER_OBJECT_MODEL_NULL,
"{0}#isObjectModelSupported( Cadena objectModel ) no se puede llamar con objectModel == null"},
/** Field ER_OBJECT_MODEL_EMPTY */
{ ER_OBJECT_MODEL_EMPTY,
"{0}#isObjectModelSupported( Cadena objectModel ) no se puede llamar con objectModel == \"\""},
/** Field ER_OBJECT_MODEL_EMPTY */
{ ER_FEATURE_NAME_NULL,
"Intentando definir una funci\u00F3n con un nombre nulo: {0}#setFeature( null, {1})"},
/** Field ER_FEATURE_UNKNOWN */
{ ER_FEATURE_UNKNOWN,
"Intentando definir la funci\u00F3n desconocida \"{0}\":{1}#setFeature({0},{2})"},
/** Field ER_GETTING_NULL_FEATURE */
{ ER_GETTING_NULL_FEATURE,
"Intentando obtener una funci\u00F3n con un nombre nulo: {0}#getFeature(null)"},
/** Field ER_GETTING_NULL_FEATURE */
{ ER_GETTING_UNKNOWN_FEATURE,
"Intentando obtener la funci\u00F3n desconocida \"{0}\":{1}#getFeature({0})"},
{ER_SECUREPROCESSING_FEATURE,
"FEATURE_SECURE_PROCESSING: no se puede definir la funci\u00F3n en false cuando est\u00E1 presente el gestor de seguridad: {1}#setFeature({0},{2})"},
/** Field ER_NULL_XPATH_FUNCTION_RESOLVER */
{ ER_NULL_XPATH_FUNCTION_RESOLVER,
"Se est\u00E1 intentando definir un valor de XPathFunctionResolver nulo:{0}#setXPathFunctionResolver(null)"},
/** Field ER_NULL_XPATH_VARIABLE_RESOLVER */
{ ER_NULL_XPATH_VARIABLE_RESOLVER,
"Se est\u00E1 intentando definir un valor XPathVariableResolver nulo:{0}#setXPathVariableResolver(null)"},
//END: Definitions of error keys used in exception messages of JAXP 1.3 XPath API implementation
// Warnings...
{ WG_LOCALE_NAME_NOT_HANDLED,
"El nombre de la configuraci\u00F3n regional en la funci\u00F3n format-number no se ha manejado a\u00FAn."},
{ WG_PROPERTY_NOT_SUPPORTED,
"Propiedad XSL no soportada: {0}"},
{ WG_DONT_DO_ANYTHING_WITH_NS,
"No realice ninguna acci\u00F3n con el espacio de nombres {0} en la propiedad: {1}"},
{ WG_SECURITY_EXCEPTION,
"Excepci\u00F3n de seguridad al intentar acceder a la propiedad del sistema XSL: {0}"},
{ WG_QUO_NO_LONGER_DEFINED,
"Sintaxis anterior: quo(...) ya no se define en XPath."},
{ WG_NEED_DERIVED_OBJECT_TO_IMPLEMENT_NODETEST,
"XPath necesita un objeto derivado para implantar una prueba de nodo."},
{ WG_FUNCTION_TOKEN_NOT_FOUND,
"No se ha encontrado el token de funci\u00F3n."},
{ WG_COULDNOT_FIND_FUNCTION,
"No se ha encontrado la funci\u00F3n: {0}"},
{ WG_CANNOT_MAKE_URL_FROM,
"No se puede crear la URL desde: {0}"},
{ WG_EXPAND_ENTITIES_NOT_SUPPORTED,
"Opci\u00F3n -E no soportada para el analizador DTM"},
{ WG_ILLEGAL_VARIABLE_REFERENCE,
"La referencia de variable proporcionada para la variable est\u00E1 fuera de contexto o no tiene definici\u00F3n. Nombre = {0}"},
{ WG_UNSUPPORTED_ENCODING,
"Codificaci\u00F3n no soportada: {0}"},
// Other miscellaneous text used inside the code...
{ "ui_language", "es"},
{ "help_language", "es"},
{ "language", "es"},
{ "BAD_CODE", "El par\u00E1metro para crear un mensaje est\u00E1 fuera de los l\u00EDmites"},
{ "FORMAT_FAILED", "Se ha emitido una excepci\u00F3n durante la llamada a messageFormat"},
{ "version", ">>>>>>> Versi\u00F3n Xalan "},
{ "version2", "<<<<<<<"},
{ "yes", "s\u00ED"},
{ "line", "N\u00BA de L\u00EDnea"},
{ "column", "N\u00BA de Columna"},
{ "xsldone", "XSLProcessor: listo"},
{ "xpath_option", "Opciones de xpath: "},
{ "optionIN", " [-in inputXMLURL]"},
{ "optionSelect", " [-select expresi\u00F3n xpath]"},
{ "optionMatch", " [-match patr\u00F3n de coincidencia (para diagn\u00F3sticos de coincidencia)]"},
{ "optionAnyExpr", "O s\u00F3lo una expresi\u00F3n xpath realizar\u00E1 un volcado de diagn\u00F3stico"},
{ "noParsermsg1", "El proceso XSL no se ha realizado correctamente."},
{ "noParsermsg2", "** No se ha encontrado el analizador **"},
{ "noParsermsg3", "Compruebe la classpath."},
{ "noParsermsg4", "Si no tiene un analizador XML de IBM para Java, puede descargarlo de"},
{ "noParsermsg5", "AlphaWorks de IBM: http://www.alphaworks.ibm.com/formula/xml"},
{ "gtone", ">1" },
{ "zero", "0" },
{ "one", "1" },
{ "two" , "2" },
{ "three", "3" }
};
/**
* Get the association list.
*
* @return The association list.
*/
public Object[][] getContents()
{
return _contents;
}
// ================= INFRASTRUCTURE ======================
/** Field BAD_CODE */
public static final String BAD_CODE = "BAD_CODE";
/** Field FORMAT_FAILED */
public static final String FORMAT_FAILED = "FORMAT_FAILED";
/** Field ERROR_RESOURCES */
public static final String ERROR_RESOURCES =
"com.sun.org.apache.xpath.internal.res.XPATHErrorResources";
/** Field ERROR_STRING */
public static final String ERROR_STRING = "#error";
/** Field ERROR_HEADER */
public static final String ERROR_HEADER = "Error: ";
/** Field WARNING_HEADER */
public static final String WARNING_HEADER = "Warning: ";
/** Field XSL_HEADER */
public static final String XSL_HEADER = "XSL ";
/** Field XML_HEADER */
public static final String XML_HEADER = "XML ";
/** Field QUERY_HEADER */
public static final String QUERY_HEADER = "PATTERN ";
}
| |
package com.justyoyo.contrast.pdf417;
/**
* Created by tiberiugolaes on 08/11/2016.
*/
import com.justyoyo.contrast.WriterException;
import com.justyoyo.contrast.common.BarcodeMatrix;
import com.justyoyo.contrast.common.BarcodeRow;
import com.justyoyo.contrast.common.Compaction;
import java.nio.charset.Charset;
/**
* Top-level class for the logic part of the PDF417 implementation.
*/
public final class PDF417 {
/**
* The start pattern (17 bits)
*/
private static final int START_PATTERN = 0x1fea8;
/**
* The stop pattern (18 bits)
*/
private static final int STOP_PATTERN = 0x3fa29;
/**
* The codeword table from the Annex A of ISO/IEC 15438:2001(E).
*/
private static final int[][] CODEWORD_TABLE = {
{0x1d5c0, 0x1eaf0, 0x1f57c, 0x1d4e0, 0x1ea78, 0x1f53e,
0x1a8c0, 0x1d470, 0x1a860, 0x15040, 0x1a830, 0x15020,
0x1adc0, 0x1d6f0, 0x1eb7c, 0x1ace0, 0x1d678, 0x1eb3e,
0x158c0, 0x1ac70, 0x15860, 0x15dc0, 0x1aef0, 0x1d77c,
0x15ce0, 0x1ae78, 0x1d73e, 0x15c70, 0x1ae3c, 0x15ef0,
0x1af7c, 0x15e78, 0x1af3e, 0x15f7c, 0x1f5fa, 0x1d2e0,
0x1e978, 0x1f4be, 0x1a4c0, 0x1d270, 0x1e93c, 0x1a460,
0x1d238, 0x14840, 0x1a430, 0x1d21c, 0x14820, 0x1a418,
0x14810, 0x1a6e0, 0x1d378, 0x1e9be, 0x14cc0, 0x1a670,
0x1d33c, 0x14c60, 0x1a638, 0x1d31e, 0x14c30, 0x1a61c,
0x14ee0, 0x1a778, 0x1d3be, 0x14e70, 0x1a73c, 0x14e38,
0x1a71e, 0x14f78, 0x1a7be, 0x14f3c, 0x14f1e, 0x1a2c0,
0x1d170, 0x1e8bc, 0x1a260, 0x1d138, 0x1e89e, 0x14440,
0x1a230, 0x1d11c, 0x14420, 0x1a218, 0x14410, 0x14408,
0x146c0, 0x1a370, 0x1d1bc, 0x14660, 0x1a338, 0x1d19e,
0x14630, 0x1a31c, 0x14618, 0x1460c, 0x14770, 0x1a3bc,
0x14738, 0x1a39e, 0x1471c, 0x147bc, 0x1a160, 0x1d0b8,
0x1e85e, 0x14240, 0x1a130, 0x1d09c, 0x14220, 0x1a118,
0x1d08e, 0x14210, 0x1a10c, 0x14208, 0x1a106, 0x14360,
0x1a1b8, 0x1d0de, 0x14330, 0x1a19c, 0x14318, 0x1a18e,
0x1430c, 0x14306, 0x1a1de, 0x1438e, 0x14140, 0x1a0b0,
0x1d05c, 0x14120, 0x1a098, 0x1d04e, 0x14110, 0x1a08c,
0x14108, 0x1a086, 0x14104, 0x141b0, 0x14198, 0x1418c,
0x140a0, 0x1d02e, 0x1a04c, 0x1a046, 0x14082, 0x1cae0,
0x1e578, 0x1f2be, 0x194c0, 0x1ca70, 0x1e53c, 0x19460,
0x1ca38, 0x1e51e, 0x12840, 0x19430, 0x12820, 0x196e0,
0x1cb78, 0x1e5be, 0x12cc0, 0x19670, 0x1cb3c, 0x12c60,
0x19638, 0x12c30, 0x12c18, 0x12ee0, 0x19778, 0x1cbbe,
0x12e70, 0x1973c, 0x12e38, 0x12e1c, 0x12f78, 0x197be,
0x12f3c, 0x12fbe, 0x1dac0, 0x1ed70, 0x1f6bc, 0x1da60,
0x1ed38, 0x1f69e, 0x1b440, 0x1da30, 0x1ed1c, 0x1b420,
0x1da18, 0x1ed0e, 0x1b410, 0x1da0c, 0x192c0, 0x1c970,
0x1e4bc, 0x1b6c0, 0x19260, 0x1c938, 0x1e49e, 0x1b660,
0x1db38, 0x1ed9e, 0x16c40, 0x12420, 0x19218, 0x1c90e,
0x16c20, 0x1b618, 0x16c10, 0x126c0, 0x19370, 0x1c9bc,
0x16ec0, 0x12660, 0x19338, 0x1c99e, 0x16e60, 0x1b738,
0x1db9e, 0x16e30, 0x12618, 0x16e18, 0x12770, 0x193bc,
0x16f70, 0x12738, 0x1939e, 0x16f38, 0x1b79e, 0x16f1c,
0x127bc, 0x16fbc, 0x1279e, 0x16f9e, 0x1d960, 0x1ecb8,
0x1f65e, 0x1b240, 0x1d930, 0x1ec9c, 0x1b220, 0x1d918,
0x1ec8e, 0x1b210, 0x1d90c, 0x1b208, 0x1b204, 0x19160,
0x1c8b8, 0x1e45e, 0x1b360, 0x19130, 0x1c89c, 0x16640,
0x12220, 0x1d99c, 0x1c88e, 0x16620, 0x12210, 0x1910c,
0x16610, 0x1b30c, 0x19106, 0x12204, 0x12360, 0x191b8,
0x1c8de, 0x16760, 0x12330, 0x1919c, 0x16730, 0x1b39c,
0x1918e, 0x16718, 0x1230c, 0x12306, 0x123b8, 0x191de,
0x167b8, 0x1239c, 0x1679c, 0x1238e, 0x1678e, 0x167de,
0x1b140, 0x1d8b0, 0x1ec5c, 0x1b120, 0x1d898, 0x1ec4e,
0x1b110, 0x1d88c, 0x1b108, 0x1d886, 0x1b104, 0x1b102,
0x12140, 0x190b0, 0x1c85c, 0x16340, 0x12120, 0x19098,
0x1c84e, 0x16320, 0x1b198, 0x1d8ce, 0x16310, 0x12108,
0x19086, 0x16308, 0x1b186, 0x16304, 0x121b0, 0x190dc,
0x163b0, 0x12198, 0x190ce, 0x16398, 0x1b1ce, 0x1638c,
0x12186, 0x16386, 0x163dc, 0x163ce, 0x1b0a0, 0x1d858,
0x1ec2e, 0x1b090, 0x1d84c, 0x1b088, 0x1d846, 0x1b084,
0x1b082, 0x120a0, 0x19058, 0x1c82e, 0x161a0, 0x12090,
0x1904c, 0x16190, 0x1b0cc, 0x19046, 0x16188, 0x12084,
0x16184, 0x12082, 0x120d8, 0x161d8, 0x161cc, 0x161c6,
0x1d82c, 0x1d826, 0x1b042, 0x1902c, 0x12048, 0x160c8,
0x160c4, 0x160c2, 0x18ac0, 0x1c570, 0x1e2bc, 0x18a60,
0x1c538, 0x11440, 0x18a30, 0x1c51c, 0x11420, 0x18a18,
0x11410, 0x11408, 0x116c0, 0x18b70, 0x1c5bc, 0x11660,
0x18b38, 0x1c59e, 0x11630, 0x18b1c, 0x11618, 0x1160c,
0x11770, 0x18bbc, 0x11738, 0x18b9e, 0x1171c, 0x117bc,
0x1179e, 0x1cd60, 0x1e6b8, 0x1f35e, 0x19a40, 0x1cd30,
0x1e69c, 0x19a20, 0x1cd18, 0x1e68e, 0x19a10, 0x1cd0c,
0x19a08, 0x1cd06, 0x18960, 0x1c4b8, 0x1e25e, 0x19b60,
0x18930, 0x1c49c, 0x13640, 0x11220, 0x1cd9c, 0x1c48e,
0x13620, 0x19b18, 0x1890c, 0x13610, 0x11208, 0x13608,
0x11360, 0x189b8, 0x1c4de, 0x13760, 0x11330, 0x1cdde,
0x13730, 0x19b9c, 0x1898e, 0x13718, 0x1130c, 0x1370c,
0x113b8, 0x189de, 0x137b8, 0x1139c, 0x1379c, 0x1138e,
0x113de, 0x137de, 0x1dd40, 0x1eeb0, 0x1f75c, 0x1dd20,
0x1ee98, 0x1f74e, 0x1dd10, 0x1ee8c, 0x1dd08, 0x1ee86,
0x1dd04, 0x19940, 0x1ccb0, 0x1e65c, 0x1bb40, 0x19920,
0x1eedc, 0x1e64e, 0x1bb20, 0x1dd98, 0x1eece, 0x1bb10,
0x19908, 0x1cc86, 0x1bb08, 0x1dd86, 0x19902, 0x11140,
0x188b0, 0x1c45c, 0x13340, 0x11120, 0x18898, 0x1c44e,
0x17740, 0x13320, 0x19998, 0x1ccce, 0x17720, 0x1bb98,
0x1ddce, 0x18886, 0x17710, 0x13308, 0x19986, 0x17708,
0x11102, 0x111b0, 0x188dc, 0x133b0, 0x11198, 0x188ce,
0x177b0, 0x13398, 0x199ce, 0x17798, 0x1bbce, 0x11186,
0x13386, 0x111dc, 0x133dc, 0x111ce, 0x177dc, 0x133ce,
0x1dca0, 0x1ee58, 0x1f72e, 0x1dc90, 0x1ee4c, 0x1dc88,
0x1ee46, 0x1dc84, 0x1dc82, 0x198a0, 0x1cc58, 0x1e62e,
0x1b9a0, 0x19890, 0x1ee6e, 0x1b990, 0x1dccc, 0x1cc46,
0x1b988, 0x19884, 0x1b984, 0x19882, 0x1b982, 0x110a0,
0x18858, 0x1c42e, 0x131a0, 0x11090, 0x1884c, 0x173a0,
0x13190, 0x198cc, 0x18846, 0x17390, 0x1b9cc, 0x11084,
0x17388, 0x13184, 0x11082, 0x13182, 0x110d8, 0x1886e,
0x131d8, 0x110cc, 0x173d8, 0x131cc, 0x110c6, 0x173cc,
0x131c6, 0x110ee, 0x173ee, 0x1dc50, 0x1ee2c, 0x1dc48,
0x1ee26, 0x1dc44, 0x1dc42, 0x19850, 0x1cc2c, 0x1b8d0,
0x19848, 0x1cc26, 0x1b8c8, 0x1dc66, 0x1b8c4, 0x19842,
0x1b8c2, 0x11050, 0x1882c, 0x130d0, 0x11048, 0x18826,
0x171d0, 0x130c8, 0x19866, 0x171c8, 0x1b8e6, 0x11042,
0x171c4, 0x130c2, 0x171c2, 0x130ec, 0x171ec, 0x171e6,
0x1ee16, 0x1dc22, 0x1cc16, 0x19824, 0x19822, 0x11028,
0x13068, 0x170e8, 0x11022, 0x13062, 0x18560, 0x10a40,
0x18530, 0x10a20, 0x18518, 0x1c28e, 0x10a10, 0x1850c,
0x10a08, 0x18506, 0x10b60, 0x185b8, 0x1c2de, 0x10b30,
0x1859c, 0x10b18, 0x1858e, 0x10b0c, 0x10b06, 0x10bb8,
0x185de, 0x10b9c, 0x10b8e, 0x10bde, 0x18d40, 0x1c6b0,
0x1e35c, 0x18d20, 0x1c698, 0x18d10, 0x1c68c, 0x18d08,
0x1c686, 0x18d04, 0x10940, 0x184b0, 0x1c25c, 0x11b40,
0x10920, 0x1c6dc, 0x1c24e, 0x11b20, 0x18d98, 0x1c6ce,
0x11b10, 0x10908, 0x18486, 0x11b08, 0x18d86, 0x10902,
0x109b0, 0x184dc, 0x11bb0, 0x10998, 0x184ce, 0x11b98,
0x18dce, 0x11b8c, 0x10986, 0x109dc, 0x11bdc, 0x109ce,
0x11bce, 0x1cea0, 0x1e758, 0x1f3ae, 0x1ce90, 0x1e74c,
0x1ce88, 0x1e746, 0x1ce84, 0x1ce82, 0x18ca0, 0x1c658,
0x19da0, 0x18c90, 0x1c64c, 0x19d90, 0x1cecc, 0x1c646,
0x19d88, 0x18c84, 0x19d84, 0x18c82, 0x19d82, 0x108a0,
0x18458, 0x119a0, 0x10890, 0x1c66e, 0x13ba0, 0x11990,
0x18ccc, 0x18446, 0x13b90, 0x19dcc, 0x10884, 0x13b88,
0x11984, 0x10882, 0x11982, 0x108d8, 0x1846e, 0x119d8,
0x108cc, 0x13bd8, 0x119cc, 0x108c6, 0x13bcc, 0x119c6,
0x108ee, 0x119ee, 0x13bee, 0x1ef50, 0x1f7ac, 0x1ef48,
0x1f7a6, 0x1ef44, 0x1ef42, 0x1ce50, 0x1e72c, 0x1ded0,
0x1ef6c, 0x1e726, 0x1dec8, 0x1ef66, 0x1dec4, 0x1ce42,
0x1dec2, 0x18c50, 0x1c62c, 0x19cd0, 0x18c48, 0x1c626,
0x1bdd0, 0x19cc8, 0x1ce66, 0x1bdc8, 0x1dee6, 0x18c42,
0x1bdc4, 0x19cc2, 0x1bdc2, 0x10850, 0x1842c, 0x118d0,
0x10848, 0x18426, 0x139d0, 0x118c8, 0x18c66, 0x17bd0,
0x139c8, 0x19ce6, 0x10842, 0x17bc8, 0x1bde6, 0x118c2,
0x17bc4, 0x1086c, 0x118ec, 0x10866, 0x139ec, 0x118e6,
0x17bec, 0x139e6, 0x17be6, 0x1ef28, 0x1f796, 0x1ef24,
0x1ef22, 0x1ce28, 0x1e716, 0x1de68, 0x1ef36, 0x1de64,
0x1ce22, 0x1de62, 0x18c28, 0x1c616, 0x19c68, 0x18c24,
0x1bce8, 0x19c64, 0x18c22, 0x1bce4, 0x19c62, 0x1bce2,
0x10828, 0x18416, 0x11868, 0x18c36, 0x138e8, 0x11864,
0x10822, 0x179e8, 0x138e4, 0x11862, 0x179e4, 0x138e2,
0x179e2, 0x11876, 0x179f6, 0x1ef12, 0x1de34, 0x1de32,
0x19c34, 0x1bc74, 0x1bc72, 0x11834, 0x13874, 0x178f4,
0x178f2, 0x10540, 0x10520, 0x18298, 0x10510, 0x10508,
0x10504, 0x105b0, 0x10598, 0x1058c, 0x10586, 0x105dc,
0x105ce, 0x186a0, 0x18690, 0x1c34c, 0x18688, 0x1c346,
0x18684, 0x18682, 0x104a0, 0x18258, 0x10da0, 0x186d8,
0x1824c, 0x10d90, 0x186cc, 0x10d88, 0x186c6, 0x10d84,
0x10482, 0x10d82, 0x104d8, 0x1826e, 0x10dd8, 0x186ee,
0x10dcc, 0x104c6, 0x10dc6, 0x104ee, 0x10dee, 0x1c750,
0x1c748, 0x1c744, 0x1c742, 0x18650, 0x18ed0, 0x1c76c,
0x1c326, 0x18ec8, 0x1c766, 0x18ec4, 0x18642, 0x18ec2,
0x10450, 0x10cd0, 0x10448, 0x18226, 0x11dd0, 0x10cc8,
0x10444, 0x11dc8, 0x10cc4, 0x10442, 0x11dc4, 0x10cc2,
0x1046c, 0x10cec, 0x10466, 0x11dec, 0x10ce6, 0x11de6,
0x1e7a8, 0x1e7a4, 0x1e7a2, 0x1c728, 0x1cf68, 0x1e7b6,
0x1cf64, 0x1c722, 0x1cf62, 0x18628, 0x1c316, 0x18e68,
0x1c736, 0x19ee8, 0x18e64, 0x18622, 0x19ee4, 0x18e62,
0x19ee2, 0x10428, 0x18216, 0x10c68, 0x18636, 0x11ce8,
0x10c64, 0x10422, 0x13de8, 0x11ce4, 0x10c62, 0x13de4,
0x11ce2, 0x10436, 0x10c76, 0x11cf6, 0x13df6, 0x1f7d4,
0x1f7d2, 0x1e794, 0x1efb4, 0x1e792, 0x1efb2, 0x1c714,
0x1cf34, 0x1c712, 0x1df74, 0x1cf32, 0x1df72, 0x18614,
0x18e34, 0x18612, 0x19e74, 0x18e32, 0x1bef4},
{0x1f560, 0x1fab8, 0x1ea40, 0x1f530, 0x1fa9c, 0x1ea20,
0x1f518, 0x1fa8e, 0x1ea10, 0x1f50c, 0x1ea08, 0x1f506,
0x1ea04, 0x1eb60, 0x1f5b8, 0x1fade, 0x1d640, 0x1eb30,
0x1f59c, 0x1d620, 0x1eb18, 0x1f58e, 0x1d610, 0x1eb0c,
0x1d608, 0x1eb06, 0x1d604, 0x1d760, 0x1ebb8, 0x1f5de,
0x1ae40, 0x1d730, 0x1eb9c, 0x1ae20, 0x1d718, 0x1eb8e,
0x1ae10, 0x1d70c, 0x1ae08, 0x1d706, 0x1ae04, 0x1af60,
0x1d7b8, 0x1ebde, 0x15e40, 0x1af30, 0x1d79c, 0x15e20,
0x1af18, 0x1d78e, 0x15e10, 0x1af0c, 0x15e08, 0x1af06,
0x15f60, 0x1afb8, 0x1d7de, 0x15f30, 0x1af9c, 0x15f18,
0x1af8e, 0x15f0c, 0x15fb8, 0x1afde, 0x15f9c, 0x15f8e,
0x1e940, 0x1f4b0, 0x1fa5c, 0x1e920, 0x1f498, 0x1fa4e,
0x1e910, 0x1f48c, 0x1e908, 0x1f486, 0x1e904, 0x1e902,
0x1d340, 0x1e9b0, 0x1f4dc, 0x1d320, 0x1e998, 0x1f4ce,
0x1d310, 0x1e98c, 0x1d308, 0x1e986, 0x1d304, 0x1d302,
0x1a740, 0x1d3b0, 0x1e9dc, 0x1a720, 0x1d398, 0x1e9ce,
0x1a710, 0x1d38c, 0x1a708, 0x1d386, 0x1a704, 0x1a702,
0x14f40, 0x1a7b0, 0x1d3dc, 0x14f20, 0x1a798, 0x1d3ce,
0x14f10, 0x1a78c, 0x14f08, 0x1a786, 0x14f04, 0x14fb0,
0x1a7dc, 0x14f98, 0x1a7ce, 0x14f8c, 0x14f86, 0x14fdc,
0x14fce, 0x1e8a0, 0x1f458, 0x1fa2e, 0x1e890, 0x1f44c,
0x1e888, 0x1f446, 0x1e884, 0x1e882, 0x1d1a0, 0x1e8d8,
0x1f46e, 0x1d190, 0x1e8cc, 0x1d188, 0x1e8c6, 0x1d184,
0x1d182, 0x1a3a0, 0x1d1d8, 0x1e8ee, 0x1a390, 0x1d1cc,
0x1a388, 0x1d1c6, 0x1a384, 0x1a382, 0x147a0, 0x1a3d8,
0x1d1ee, 0x14790, 0x1a3cc, 0x14788, 0x1a3c6, 0x14784,
0x14782, 0x147d8, 0x1a3ee, 0x147cc, 0x147c6, 0x147ee,
0x1e850, 0x1f42c, 0x1e848, 0x1f426, 0x1e844, 0x1e842,
0x1d0d0, 0x1e86c, 0x1d0c8, 0x1e866, 0x1d0c4, 0x1d0c2,
0x1a1d0, 0x1d0ec, 0x1a1c8, 0x1d0e6, 0x1a1c4, 0x1a1c2,
0x143d0, 0x1a1ec, 0x143c8, 0x1a1e6, 0x143c4, 0x143c2,
0x143ec, 0x143e6, 0x1e828, 0x1f416, 0x1e824, 0x1e822,
0x1d068, 0x1e836, 0x1d064, 0x1d062, 0x1a0e8, 0x1d076,
0x1a0e4, 0x1a0e2, 0x141e8, 0x1a0f6, 0x141e4, 0x141e2,
0x1e814, 0x1e812, 0x1d034, 0x1d032, 0x1a074, 0x1a072,
0x1e540, 0x1f2b0, 0x1f95c, 0x1e520, 0x1f298, 0x1f94e,
0x1e510, 0x1f28c, 0x1e508, 0x1f286, 0x1e504, 0x1e502,
0x1cb40, 0x1e5b0, 0x1f2dc, 0x1cb20, 0x1e598, 0x1f2ce,
0x1cb10, 0x1e58c, 0x1cb08, 0x1e586, 0x1cb04, 0x1cb02,
0x19740, 0x1cbb0, 0x1e5dc, 0x19720, 0x1cb98, 0x1e5ce,
0x19710, 0x1cb8c, 0x19708, 0x1cb86, 0x19704, 0x19702,
0x12f40, 0x197b0, 0x1cbdc, 0x12f20, 0x19798, 0x1cbce,
0x12f10, 0x1978c, 0x12f08, 0x19786, 0x12f04, 0x12fb0,
0x197dc, 0x12f98, 0x197ce, 0x12f8c, 0x12f86, 0x12fdc,
0x12fce, 0x1f6a0, 0x1fb58, 0x16bf0, 0x1f690, 0x1fb4c,
0x169f8, 0x1f688, 0x1fb46, 0x168fc, 0x1f684, 0x1f682,
0x1e4a0, 0x1f258, 0x1f92e, 0x1eda0, 0x1e490, 0x1fb6e,
0x1ed90, 0x1f6cc, 0x1f246, 0x1ed88, 0x1e484, 0x1ed84,
0x1e482, 0x1ed82, 0x1c9a0, 0x1e4d8, 0x1f26e, 0x1dba0,
0x1c990, 0x1e4cc, 0x1db90, 0x1edcc, 0x1e4c6, 0x1db88,
0x1c984, 0x1db84, 0x1c982, 0x1db82, 0x193a0, 0x1c9d8,
0x1e4ee, 0x1b7a0, 0x19390, 0x1c9cc, 0x1b790, 0x1dbcc,
0x1c9c6, 0x1b788, 0x19384, 0x1b784, 0x19382, 0x1b782,
0x127a0, 0x193d8, 0x1c9ee, 0x16fa0, 0x12790, 0x193cc,
0x16f90, 0x1b7cc, 0x193c6, 0x16f88, 0x12784, 0x16f84,
0x12782, 0x127d8, 0x193ee, 0x16fd8, 0x127cc, 0x16fcc,
0x127c6, 0x16fc6, 0x127ee, 0x1f650, 0x1fb2c, 0x165f8,
0x1f648, 0x1fb26, 0x164fc, 0x1f644, 0x1647e, 0x1f642,
0x1e450, 0x1f22c, 0x1ecd0, 0x1e448, 0x1f226, 0x1ecc8,
0x1f666, 0x1ecc4, 0x1e442, 0x1ecc2, 0x1c8d0, 0x1e46c,
0x1d9d0, 0x1c8c8, 0x1e466, 0x1d9c8, 0x1ece6, 0x1d9c4,
0x1c8c2, 0x1d9c2, 0x191d0, 0x1c8ec, 0x1b3d0, 0x191c8,
0x1c8e6, 0x1b3c8, 0x1d9e6, 0x1b3c4, 0x191c2, 0x1b3c2,
0x123d0, 0x191ec, 0x167d0, 0x123c8, 0x191e6, 0x167c8,
0x1b3e6, 0x167c4, 0x123c2, 0x167c2, 0x123ec, 0x167ec,
0x123e6, 0x167e6, 0x1f628, 0x1fb16, 0x162fc, 0x1f624,
0x1627e, 0x1f622, 0x1e428, 0x1f216, 0x1ec68, 0x1f636,
0x1ec64, 0x1e422, 0x1ec62, 0x1c868, 0x1e436, 0x1d8e8,
0x1c864, 0x1d8e4, 0x1c862, 0x1d8e2, 0x190e8, 0x1c876,
0x1b1e8, 0x1d8f6, 0x1b1e4, 0x190e2, 0x1b1e2, 0x121e8,
0x190f6, 0x163e8, 0x121e4, 0x163e4, 0x121e2, 0x163e2,
0x121f6, 0x163f6, 0x1f614, 0x1617e, 0x1f612, 0x1e414,
0x1ec34, 0x1e412, 0x1ec32, 0x1c834, 0x1d874, 0x1c832,
0x1d872, 0x19074, 0x1b0f4, 0x19072, 0x1b0f2, 0x120f4,
0x161f4, 0x120f2, 0x161f2, 0x1f60a, 0x1e40a, 0x1ec1a,
0x1c81a, 0x1d83a, 0x1903a, 0x1b07a, 0x1e2a0, 0x1f158,
0x1f8ae, 0x1e290, 0x1f14c, 0x1e288, 0x1f146, 0x1e284,
0x1e282, 0x1c5a0, 0x1e2d8, 0x1f16e, 0x1c590, 0x1e2cc,
0x1c588, 0x1e2c6, 0x1c584, 0x1c582, 0x18ba0, 0x1c5d8,
0x1e2ee, 0x18b90, 0x1c5cc, 0x18b88, 0x1c5c6, 0x18b84,
0x18b82, 0x117a0, 0x18bd8, 0x1c5ee, 0x11790, 0x18bcc,
0x11788, 0x18bc6, 0x11784, 0x11782, 0x117d8, 0x18bee,
0x117cc, 0x117c6, 0x117ee, 0x1f350, 0x1f9ac, 0x135f8,
0x1f348, 0x1f9a6, 0x134fc, 0x1f344, 0x1347e, 0x1f342,
0x1e250, 0x1f12c, 0x1e6d0, 0x1e248, 0x1f126, 0x1e6c8,
0x1f366, 0x1e6c4, 0x1e242, 0x1e6c2, 0x1c4d0, 0x1e26c,
0x1cdd0, 0x1c4c8, 0x1e266, 0x1cdc8, 0x1e6e6, 0x1cdc4,
0x1c4c2, 0x1cdc2, 0x189d0, 0x1c4ec, 0x19bd0, 0x189c8,
0x1c4e6, 0x19bc8, 0x1cde6, 0x19bc4, 0x189c2, 0x19bc2,
0x113d0, 0x189ec, 0x137d0, 0x113c8, 0x189e6, 0x137c8,
0x19be6, 0x137c4, 0x113c2, 0x137c2, 0x113ec, 0x137ec,
0x113e6, 0x137e6, 0x1fba8, 0x175f0, 0x1bafc, 0x1fba4,
0x174f8, 0x1ba7e, 0x1fba2, 0x1747c, 0x1743e, 0x1f328,
0x1f996, 0x132fc, 0x1f768, 0x1fbb6, 0x176fc, 0x1327e,
0x1f764, 0x1f322, 0x1767e, 0x1f762, 0x1e228, 0x1f116,
0x1e668, 0x1e224, 0x1eee8, 0x1f776, 0x1e222, 0x1eee4,
0x1e662, 0x1eee2, 0x1c468, 0x1e236, 0x1cce8, 0x1c464,
0x1dde8, 0x1cce4, 0x1c462, 0x1dde4, 0x1cce2, 0x1dde2,
0x188e8, 0x1c476, 0x199e8, 0x188e4, 0x1bbe8, 0x199e4,
0x188e2, 0x1bbe4, 0x199e2, 0x1bbe2, 0x111e8, 0x188f6,
0x133e8, 0x111e4, 0x177e8, 0x133e4, 0x111e2, 0x177e4,
0x133e2, 0x177e2, 0x111f6, 0x133f6, 0x1fb94, 0x172f8,
0x1b97e, 0x1fb92, 0x1727c, 0x1723e, 0x1f314, 0x1317e,
0x1f734, 0x1f312, 0x1737e, 0x1f732, 0x1e214, 0x1e634,
0x1e212, 0x1ee74, 0x1e632, 0x1ee72, 0x1c434, 0x1cc74,
0x1c432, 0x1dcf4, 0x1cc72, 0x1dcf2, 0x18874, 0x198f4,
0x18872, 0x1b9f4, 0x198f2, 0x1b9f2, 0x110f4, 0x131f4,
0x110f2, 0x173f4, 0x131f2, 0x173f2, 0x1fb8a, 0x1717c,
0x1713e, 0x1f30a, 0x1f71a, 0x1e20a, 0x1e61a, 0x1ee3a,
0x1c41a, 0x1cc3a, 0x1dc7a, 0x1883a, 0x1987a, 0x1b8fa,
0x1107a, 0x130fa, 0x171fa, 0x170be, 0x1e150, 0x1f0ac,
0x1e148, 0x1f0a6, 0x1e144, 0x1e142, 0x1c2d0, 0x1e16c,
0x1c2c8, 0x1e166, 0x1c2c4, 0x1c2c2, 0x185d0, 0x1c2ec,
0x185c8, 0x1c2e6, 0x185c4, 0x185c2, 0x10bd0, 0x185ec,
0x10bc8, 0x185e6, 0x10bc4, 0x10bc2, 0x10bec, 0x10be6,
0x1f1a8, 0x1f8d6, 0x11afc, 0x1f1a4, 0x11a7e, 0x1f1a2,
0x1e128, 0x1f096, 0x1e368, 0x1e124, 0x1e364, 0x1e122,
0x1e362, 0x1c268, 0x1e136, 0x1c6e8, 0x1c264, 0x1c6e4,
0x1c262, 0x1c6e2, 0x184e8, 0x1c276, 0x18de8, 0x184e4,
0x18de4, 0x184e2, 0x18de2, 0x109e8, 0x184f6, 0x11be8,
0x109e4, 0x11be4, 0x109e2, 0x11be2, 0x109f6, 0x11bf6,
0x1f9d4, 0x13af8, 0x19d7e, 0x1f9d2, 0x13a7c, 0x13a3e,
0x1f194, 0x1197e, 0x1f3b4, 0x1f192, 0x13b7e, 0x1f3b2,
0x1e114, 0x1e334, 0x1e112, 0x1e774, 0x1e332, 0x1e772,
0x1c234, 0x1c674, 0x1c232, 0x1cef4, 0x1c672, 0x1cef2,
0x18474, 0x18cf4, 0x18472, 0x19df4, 0x18cf2, 0x19df2,
0x108f4, 0x119f4, 0x108f2, 0x13bf4, 0x119f2, 0x13bf2,
0x17af0, 0x1bd7c, 0x17a78, 0x1bd3e, 0x17a3c, 0x17a1e,
0x1f9ca, 0x1397c, 0x1fbda, 0x17b7c, 0x1393e, 0x17b3e,
0x1f18a, 0x1f39a, 0x1f7ba, 0x1e10a, 0x1e31a, 0x1e73a,
0x1ef7a, 0x1c21a, 0x1c63a, 0x1ce7a, 0x1defa, 0x1843a,
0x18c7a, 0x19cfa, 0x1bdfa, 0x1087a, 0x118fa, 0x139fa,
0x17978, 0x1bcbe, 0x1793c, 0x1791e, 0x138be, 0x179be,
0x178bc, 0x1789e, 0x1785e, 0x1e0a8, 0x1e0a4, 0x1e0a2,
0x1c168, 0x1e0b6, 0x1c164, 0x1c162, 0x182e8, 0x1c176,
0x182e4, 0x182e2, 0x105e8, 0x182f6, 0x105e4, 0x105e2,
0x105f6, 0x1f0d4, 0x10d7e, 0x1f0d2, 0x1e094, 0x1e1b4,
0x1e092, 0x1e1b2, 0x1c134, 0x1c374, 0x1c132, 0x1c372,
0x18274, 0x186f4, 0x18272, 0x186f2, 0x104f4, 0x10df4,
0x104f2, 0x10df2, 0x1f8ea, 0x11d7c, 0x11d3e, 0x1f0ca,
0x1f1da, 0x1e08a, 0x1e19a, 0x1e3ba, 0x1c11a, 0x1c33a,
0x1c77a, 0x1823a, 0x1867a, 0x18efa, 0x1047a, 0x10cfa,
0x11dfa, 0x13d78, 0x19ebe, 0x13d3c, 0x13d1e, 0x11cbe,
0x13dbe, 0x17d70, 0x1bebc, 0x17d38, 0x1be9e, 0x17d1c,
0x17d0e, 0x13cbc, 0x17dbc, 0x13c9e, 0x17d9e, 0x17cb8,
0x1be5e, 0x17c9c, 0x17c8e, 0x13c5e, 0x17cde, 0x17c5c,
0x17c4e, 0x17c2e, 0x1c0b4, 0x1c0b2, 0x18174, 0x18172,
0x102f4, 0x102f2, 0x1e0da, 0x1c09a, 0x1c1ba, 0x1813a,
0x1837a, 0x1027a, 0x106fa, 0x10ebe, 0x11ebc, 0x11e9e,
0x13eb8, 0x19f5e, 0x13e9c, 0x13e8e, 0x11e5e, 0x13ede,
0x17eb0, 0x1bf5c, 0x17e98, 0x1bf4e, 0x17e8c, 0x17e86,
0x13e5c, 0x17edc, 0x13e4e, 0x17ece, 0x17e58, 0x1bf2e,
0x17e4c, 0x17e46, 0x13e2e, 0x17e6e, 0x17e2c, 0x17e26,
0x10f5e, 0x11f5c, 0x11f4e, 0x13f58, 0x19fae, 0x13f4c,
0x13f46, 0x11f2e, 0x13f6e, 0x13f2c, 0x13f26},
{0x1abe0, 0x1d5f8, 0x153c0, 0x1a9f0, 0x1d4fc, 0x151e0,
0x1a8f8, 0x1d47e, 0x150f0, 0x1a87c, 0x15078, 0x1fad0,
0x15be0, 0x1adf8, 0x1fac8, 0x159f0, 0x1acfc, 0x1fac4,
0x158f8, 0x1ac7e, 0x1fac2, 0x1587c, 0x1f5d0, 0x1faec,
0x15df8, 0x1f5c8, 0x1fae6, 0x15cfc, 0x1f5c4, 0x15c7e,
0x1f5c2, 0x1ebd0, 0x1f5ec, 0x1ebc8, 0x1f5e6, 0x1ebc4,
0x1ebc2, 0x1d7d0, 0x1ebec, 0x1d7c8, 0x1ebe6, 0x1d7c4,
0x1d7c2, 0x1afd0, 0x1d7ec, 0x1afc8, 0x1d7e6, 0x1afc4,
0x14bc0, 0x1a5f0, 0x1d2fc, 0x149e0, 0x1a4f8, 0x1d27e,
0x148f0, 0x1a47c, 0x14878, 0x1a43e, 0x1483c, 0x1fa68,
0x14df0, 0x1a6fc, 0x1fa64, 0x14cf8, 0x1a67e, 0x1fa62,
0x14c7c, 0x14c3e, 0x1f4e8, 0x1fa76, 0x14efc, 0x1f4e4,
0x14e7e, 0x1f4e2, 0x1e9e8, 0x1f4f6, 0x1e9e4, 0x1e9e2,
0x1d3e8, 0x1e9f6, 0x1d3e4, 0x1d3e2, 0x1a7e8, 0x1d3f6,
0x1a7e4, 0x1a7e2, 0x145e0, 0x1a2f8, 0x1d17e, 0x144f0,
0x1a27c, 0x14478, 0x1a23e, 0x1443c, 0x1441e, 0x1fa34,
0x146f8, 0x1a37e, 0x1fa32, 0x1467c, 0x1463e, 0x1f474,
0x1477e, 0x1f472, 0x1e8f4, 0x1e8f2, 0x1d1f4, 0x1d1f2,
0x1a3f4, 0x1a3f2, 0x142f0, 0x1a17c, 0x14278, 0x1a13e,
0x1423c, 0x1421e, 0x1fa1a, 0x1437c, 0x1433e, 0x1f43a,
0x1e87a, 0x1d0fa, 0x14178, 0x1a0be, 0x1413c, 0x1411e,
0x141be, 0x140bc, 0x1409e, 0x12bc0, 0x195f0, 0x1cafc,
0x129e0, 0x194f8, 0x1ca7e, 0x128f0, 0x1947c, 0x12878,
0x1943e, 0x1283c, 0x1f968, 0x12df0, 0x196fc, 0x1f964,
0x12cf8, 0x1967e, 0x1f962, 0x12c7c, 0x12c3e, 0x1f2e8,
0x1f976, 0x12efc, 0x1f2e4, 0x12e7e, 0x1f2e2, 0x1e5e8,
0x1f2f6, 0x1e5e4, 0x1e5e2, 0x1cbe8, 0x1e5f6, 0x1cbe4,
0x1cbe2, 0x197e8, 0x1cbf6, 0x197e4, 0x197e2, 0x1b5e0,
0x1daf8, 0x1ed7e, 0x169c0, 0x1b4f0, 0x1da7c, 0x168e0,
0x1b478, 0x1da3e, 0x16870, 0x1b43c, 0x16838, 0x1b41e,
0x1681c, 0x125e0, 0x192f8, 0x1c97e, 0x16de0, 0x124f0,
0x1927c, 0x16cf0, 0x1b67c, 0x1923e, 0x16c78, 0x1243c,
0x16c3c, 0x1241e, 0x16c1e, 0x1f934, 0x126f8, 0x1937e,
0x1fb74, 0x1f932, 0x16ef8, 0x1267c, 0x1fb72, 0x16e7c,
0x1263e, 0x16e3e, 0x1f274, 0x1277e, 0x1f6f4, 0x1f272,
0x16f7e, 0x1f6f2, 0x1e4f4, 0x1edf4, 0x1e4f2, 0x1edf2,
0x1c9f4, 0x1dbf4, 0x1c9f2, 0x1dbf2, 0x193f4, 0x193f2,
0x165c0, 0x1b2f0, 0x1d97c, 0x164e0, 0x1b278, 0x1d93e,
0x16470, 0x1b23c, 0x16438, 0x1b21e, 0x1641c, 0x1640e,
0x122f0, 0x1917c, 0x166f0, 0x12278, 0x1913e, 0x16678,
0x1b33e, 0x1663c, 0x1221e, 0x1661e, 0x1f91a, 0x1237c,
0x1fb3a, 0x1677c, 0x1233e, 0x1673e, 0x1f23a, 0x1f67a,
0x1e47a, 0x1ecfa, 0x1c8fa, 0x1d9fa, 0x191fa, 0x162e0,
0x1b178, 0x1d8be, 0x16270, 0x1b13c, 0x16238, 0x1b11e,
0x1621c, 0x1620e, 0x12178, 0x190be, 0x16378, 0x1213c,
0x1633c, 0x1211e, 0x1631e, 0x121be, 0x163be, 0x16170,
0x1b0bc, 0x16138, 0x1b09e, 0x1611c, 0x1610e, 0x120bc,
0x161bc, 0x1209e, 0x1619e, 0x160b8, 0x1b05e, 0x1609c,
0x1608e, 0x1205e, 0x160de, 0x1605c, 0x1604e, 0x115e0,
0x18af8, 0x1c57e, 0x114f0, 0x18a7c, 0x11478, 0x18a3e,
0x1143c, 0x1141e, 0x1f8b4, 0x116f8, 0x18b7e, 0x1f8b2,
0x1167c, 0x1163e, 0x1f174, 0x1177e, 0x1f172, 0x1e2f4,
0x1e2f2, 0x1c5f4, 0x1c5f2, 0x18bf4, 0x18bf2, 0x135c0,
0x19af0, 0x1cd7c, 0x134e0, 0x19a78, 0x1cd3e, 0x13470,
0x19a3c, 0x13438, 0x19a1e, 0x1341c, 0x1340e, 0x112f0,
0x1897c, 0x136f0, 0x11278, 0x1893e, 0x13678, 0x19b3e,
0x1363c, 0x1121e, 0x1361e, 0x1f89a, 0x1137c, 0x1f9ba,
0x1377c, 0x1133e, 0x1373e, 0x1f13a, 0x1f37a, 0x1e27a,
0x1e6fa, 0x1c4fa, 0x1cdfa, 0x189fa, 0x1bae0, 0x1dd78,
0x1eebe, 0x174c0, 0x1ba70, 0x1dd3c, 0x17460, 0x1ba38,
0x1dd1e, 0x17430, 0x1ba1c, 0x17418, 0x1ba0e, 0x1740c,
0x132e0, 0x19978, 0x1ccbe, 0x176e0, 0x13270, 0x1993c,
0x17670, 0x1bb3c, 0x1991e, 0x17638, 0x1321c, 0x1761c,
0x1320e, 0x1760e, 0x11178, 0x188be, 0x13378, 0x1113c,
0x17778, 0x1333c, 0x1111e, 0x1773c, 0x1331e, 0x1771e,
0x111be, 0x133be, 0x177be, 0x172c0, 0x1b970, 0x1dcbc,
0x17260, 0x1b938, 0x1dc9e, 0x17230, 0x1b91c, 0x17218,
0x1b90e, 0x1720c, 0x17206, 0x13170, 0x198bc, 0x17370,
0x13138, 0x1989e, 0x17338, 0x1b99e, 0x1731c, 0x1310e,
0x1730e, 0x110bc, 0x131bc, 0x1109e, 0x173bc, 0x1319e,
0x1739e, 0x17160, 0x1b8b8, 0x1dc5e, 0x17130, 0x1b89c,
0x17118, 0x1b88e, 0x1710c, 0x17106, 0x130b8, 0x1985e,
0x171b8, 0x1309c, 0x1719c, 0x1308e, 0x1718e, 0x1105e,
0x130de, 0x171de, 0x170b0, 0x1b85c, 0x17098, 0x1b84e,
0x1708c, 0x17086, 0x1305c, 0x170dc, 0x1304e, 0x170ce,
0x17058, 0x1b82e, 0x1704c, 0x17046, 0x1302e, 0x1706e,
0x1702c, 0x17026, 0x10af0, 0x1857c, 0x10a78, 0x1853e,
0x10a3c, 0x10a1e, 0x10b7c, 0x10b3e, 0x1f0ba, 0x1e17a,
0x1c2fa, 0x185fa, 0x11ae0, 0x18d78, 0x1c6be, 0x11a70,
0x18d3c, 0x11a38, 0x18d1e, 0x11a1c, 0x11a0e, 0x10978,
0x184be, 0x11b78, 0x1093c, 0x11b3c, 0x1091e, 0x11b1e,
0x109be, 0x11bbe, 0x13ac0, 0x19d70, 0x1cebc, 0x13a60,
0x19d38, 0x1ce9e, 0x13a30, 0x19d1c, 0x13a18, 0x19d0e,
0x13a0c, 0x13a06, 0x11970, 0x18cbc, 0x13b70, 0x11938,
0x18c9e, 0x13b38, 0x1191c, 0x13b1c, 0x1190e, 0x13b0e,
0x108bc, 0x119bc, 0x1089e, 0x13bbc, 0x1199e, 0x13b9e,
0x1bd60, 0x1deb8, 0x1ef5e, 0x17a40, 0x1bd30, 0x1de9c,
0x17a20, 0x1bd18, 0x1de8e, 0x17a10, 0x1bd0c, 0x17a08,
0x1bd06, 0x17a04, 0x13960, 0x19cb8, 0x1ce5e, 0x17b60,
0x13930, 0x19c9c, 0x17b30, 0x1bd9c, 0x19c8e, 0x17b18,
0x1390c, 0x17b0c, 0x13906, 0x17b06, 0x118b8, 0x18c5e,
0x139b8, 0x1189c, 0x17bb8, 0x1399c, 0x1188e, 0x17b9c,
0x1398e, 0x17b8e, 0x1085e, 0x118de, 0x139de, 0x17bde,
0x17940, 0x1bcb0, 0x1de5c, 0x17920, 0x1bc98, 0x1de4e,
0x17910, 0x1bc8c, 0x17908, 0x1bc86, 0x17904, 0x17902,
0x138b0, 0x19c5c, 0x179b0, 0x13898, 0x19c4e, 0x17998,
0x1bcce, 0x1798c, 0x13886, 0x17986, 0x1185c, 0x138dc,
0x1184e, 0x179dc, 0x138ce, 0x179ce, 0x178a0, 0x1bc58,
0x1de2e, 0x17890, 0x1bc4c, 0x17888, 0x1bc46, 0x17884,
0x17882, 0x13858, 0x19c2e, 0x178d8, 0x1384c, 0x178cc,
0x13846, 0x178c6, 0x1182e, 0x1386e, 0x178ee, 0x17850,
0x1bc2c, 0x17848, 0x1bc26, 0x17844, 0x17842, 0x1382c,
0x1786c, 0x13826, 0x17866, 0x17828, 0x1bc16, 0x17824,
0x17822, 0x13816, 0x17836, 0x10578, 0x182be, 0x1053c,
0x1051e, 0x105be, 0x10d70, 0x186bc, 0x10d38, 0x1869e,
0x10d1c, 0x10d0e, 0x104bc, 0x10dbc, 0x1049e, 0x10d9e,
0x11d60, 0x18eb8, 0x1c75e, 0x11d30, 0x18e9c, 0x11d18,
0x18e8e, 0x11d0c, 0x11d06, 0x10cb8, 0x1865e, 0x11db8,
0x10c9c, 0x11d9c, 0x10c8e, 0x11d8e, 0x1045e, 0x10cde,
0x11dde, 0x13d40, 0x19eb0, 0x1cf5c, 0x13d20, 0x19e98,
0x1cf4e, 0x13d10, 0x19e8c, 0x13d08, 0x19e86, 0x13d04,
0x13d02, 0x11cb0, 0x18e5c, 0x13db0, 0x11c98, 0x18e4e,
0x13d98, 0x19ece, 0x13d8c, 0x11c86, 0x13d86, 0x10c5c,
0x11cdc, 0x10c4e, 0x13ddc, 0x11cce, 0x13dce, 0x1bea0,
0x1df58, 0x1efae, 0x1be90, 0x1df4c, 0x1be88, 0x1df46,
0x1be84, 0x1be82, 0x13ca0, 0x19e58, 0x1cf2e, 0x17da0,
0x13c90, 0x19e4c, 0x17d90, 0x1becc, 0x19e46, 0x17d88,
0x13c84, 0x17d84, 0x13c82, 0x17d82, 0x11c58, 0x18e2e,
0x13cd8, 0x11c4c, 0x17dd8, 0x13ccc, 0x11c46, 0x17dcc,
0x13cc6, 0x17dc6, 0x10c2e, 0x11c6e, 0x13cee, 0x17dee,
0x1be50, 0x1df2c, 0x1be48, 0x1df26, 0x1be44, 0x1be42,
0x13c50, 0x19e2c, 0x17cd0, 0x13c48, 0x19e26, 0x17cc8,
0x1be66, 0x17cc4, 0x13c42, 0x17cc2, 0x11c2c, 0x13c6c,
0x11c26, 0x17cec, 0x13c66, 0x17ce6, 0x1be28, 0x1df16,
0x1be24, 0x1be22, 0x13c28, 0x19e16, 0x17c68, 0x13c24,
0x17c64, 0x13c22, 0x17c62, 0x11c16, 0x13c36, 0x17c76,
0x1be14, 0x1be12, 0x13c14, 0x17c34, 0x13c12, 0x17c32,
0x102bc, 0x1029e, 0x106b8, 0x1835e, 0x1069c, 0x1068e,
0x1025e, 0x106de, 0x10eb0, 0x1875c, 0x10e98, 0x1874e,
0x10e8c, 0x10e86, 0x1065c, 0x10edc, 0x1064e, 0x10ece,
0x11ea0, 0x18f58, 0x1c7ae, 0x11e90, 0x18f4c, 0x11e88,
0x18f46, 0x11e84, 0x11e82, 0x10e58, 0x1872e, 0x11ed8,
0x18f6e, 0x11ecc, 0x10e46, 0x11ec6, 0x1062e, 0x10e6e,
0x11eee, 0x19f50, 0x1cfac, 0x19f48, 0x1cfa6, 0x19f44,
0x19f42, 0x11e50, 0x18f2c, 0x13ed0, 0x19f6c, 0x18f26,
0x13ec8, 0x11e44, 0x13ec4, 0x11e42, 0x13ec2, 0x10e2c,
0x11e6c, 0x10e26, 0x13eec, 0x11e66, 0x13ee6, 0x1dfa8,
0x1efd6, 0x1dfa4, 0x1dfa2, 0x19f28, 0x1cf96, 0x1bf68,
0x19f24, 0x1bf64, 0x19f22, 0x1bf62, 0x11e28, 0x18f16,
0x13e68, 0x11e24, 0x17ee8, 0x13e64, 0x11e22, 0x17ee4,
0x13e62, 0x17ee2, 0x10e16, 0x11e36, 0x13e76, 0x17ef6,
0x1df94, 0x1df92, 0x19f14, 0x1bf34, 0x19f12, 0x1bf32,
0x11e14, 0x13e34, 0x11e12, 0x17e74, 0x13e32, 0x17e72,
0x1df8a, 0x19f0a, 0x1bf1a, 0x11e0a, 0x13e1a, 0x17e3a,
0x1035c, 0x1034e, 0x10758, 0x183ae, 0x1074c, 0x10746,
0x1032e, 0x1076e, 0x10f50, 0x187ac, 0x10f48, 0x187a6,
0x10f44, 0x10f42, 0x1072c, 0x10f6c, 0x10726, 0x10f66,
0x18fa8, 0x1c7d6, 0x18fa4, 0x18fa2, 0x10f28, 0x18796,
0x11f68, 0x18fb6, 0x11f64, 0x10f22, 0x11f62, 0x10716,
0x10f36, 0x11f76, 0x1cfd4, 0x1cfd2, 0x18f94, 0x19fb4,
0x18f92, 0x19fb2, 0x10f14, 0x11f34, 0x10f12, 0x13f74,
0x11f32, 0x13f72, 0x1cfca, 0x18f8a, 0x19f9a, 0x10f0a,
0x11f1a, 0x13f3a, 0x103ac, 0x103a6, 0x107a8, 0x183d6,
0x107a4, 0x107a2, 0x10396, 0x107b6, 0x187d4, 0x187d2,
0x10794, 0x10fb4, 0x10792, 0x10fb2, 0x1c7ea}};
private static final float PREFERRED_RATIO = 3.0f;
private static final float DEFAULT_MODULE_WIDTH = 0.357f; //1px in mm
private static final float HEIGHT = 2.0f; //mm
private BarcodeMatrix barcodeMatrix;
private boolean compact;
private Compaction compaction;
private Charset encoding;
private int minCols;
private int maxCols;
private int maxRows;
private int minRows;
public PDF417() {
this(false);
}
public PDF417(boolean compact) {
this.compact = compact;
compaction = Compaction.AUTO;
encoding = null; // Use default
minCols = 2;
maxCols = 30;
maxRows = 30;
minRows = 2;
}
public BarcodeMatrix getBarcodeMatrix() {
return barcodeMatrix;
}
/**
* Calculates the necessary number of rows as described in annex Q of ISO/IEC 15438:2001(E).
*
* @param m the number of source codewords prior to the additional of the Symbol Length
* Descriptor and any pad codewords
* @param k the number of error correction codewords
* @param c the number of columns in the symbol in the data region (excluding start, stop and
* row indicator codewords)
* @return the number of rows in the symbol (r)
*/
private static int calculateNumberOfRows(int m, int k, int c) {
int r = ((m + 1 + k) / c) + 1;
if (c * r >= (m + 1 + k + c)) {
r--;
}
return r;
}
/**
* Calculates the number of pad codewords as described in 4.9.2 of ISO/IEC 15438:2001(E).
*
* @param m the number of source codewords prior to the additional of the Symbol Length
* Descriptor and any pad codewords
* @param k the number of error correction codewords
* @param c the number of columns in the symbol in the data region (excluding start, stop and
* row indicator codewords)
* @param r the number of rows in the symbol
* @return the number of pad codewords
*/
private static int getNumberOfPadCodewords(int m, int k, int c, int r) {
int n = c * r - k;
return n > m + 1 ? n - m - 1 : 0;
}
private static void encodeChar(int pattern, int len, BarcodeRow logic) {
int map = 1 << len - 1;
boolean last = (pattern & map) != 0; //Initialize to inverse of first bit
int width = 0;
for (int i = 0; i < len; i++) {
boolean black = (pattern & map) != 0;
if (last == black) {
width++;
} else {
logic.addBar(last, width);
last = black;
width = 1;
}
map >>= 1;
}
logic.addBar(last, width);
}
private void encodeLowLevel(CharSequence fullCodewords,
int c,
int r,
int errorCorrectionLevel,
BarcodeMatrix logic) {
int idx = 0;
for (int y = 0; y < r; y++) {
int cluster = y % 3;
logic.startRow();
encodeChar(START_PATTERN, 17, logic.getCurrentRow());
int left;
int right;
if (cluster == 0) {
left = (30 * (y / 3)) + ((r - 1) / 3);
right = (30 * (y / 3)) + (c - 1);
} else if (cluster == 1) {
left = (30 * (y / 3)) + (errorCorrectionLevel * 3) + ((r - 1) % 3);
right = (30 * (y / 3)) + ((r - 1) / 3);
} else {
left = (30 * (y / 3)) + (c - 1);
right = (30 * (y / 3)) + (errorCorrectionLevel * 3) + ((r - 1) % 3);
}
int pattern = CODEWORD_TABLE[cluster][left];
encodeChar(pattern, 17, logic.getCurrentRow());
for (int x = 0; x < c; x++) {
pattern = CODEWORD_TABLE[cluster][fullCodewords.charAt(idx)];
encodeChar(pattern, 17, logic.getCurrentRow());
idx++;
}
if (compact) {
encodeChar(STOP_PATTERN, 1, logic.getCurrentRow()); // encodes stop line for compact pdf417
} else {
pattern = CODEWORD_TABLE[cluster][right];
encodeChar(pattern, 17, logic.getCurrentRow());
encodeChar(STOP_PATTERN, 18, logic.getCurrentRow());
}
}
}
/**
* @param msg message to encode
* @param errorCorrectionLevel PDF417 error correction level to use
* @throws if the contents cannot be encoded in this format
*/
public void generateBarcodeLogic(String msg, int errorCorrectionLevel) throws WriterException {
//1. step: High-level encoding
int errorCorrectionCodeWords = PDF417ErrorCorrection.getErrorCorrectionCodewordCount(errorCorrectionLevel);
String highLevel = PDF417HighLevelEncoder.encodeHighLevel(msg, compaction, encoding);
int sourceCodeWords = highLevel.length();
int[] dimension = determineDimensions(sourceCodeWords, errorCorrectionCodeWords);
int cols = dimension[0];
int rows = dimension[1];
int pad = getNumberOfPadCodewords(sourceCodeWords, errorCorrectionCodeWords, cols, rows);
//2. step: construct data codewords
if (sourceCodeWords + errorCorrectionCodeWords + 1 > 929) { // +1 for symbol length CW
throw new WriterException(
"Encoded message contains too many code words, message too big (" + msg.length() + " bytes)")
;
}
int n = sourceCodeWords + pad + 1;
StringBuilder sb = new StringBuilder(n);
sb.append((char) n);
sb.append(highLevel);
for (int i = 0; i < pad; i++) {
sb.append((char) 900); //PAD characters
}
String dataCodewords = sb.toString();
//3. step: Error correction
String ec = PDF417ErrorCorrection.generateErrorCorrection(dataCodewords, errorCorrectionLevel);
//4. step: low-level encoding
barcodeMatrix = new BarcodeMatrix(rows, cols);
encodeLowLevel(dataCodewords + ec, cols, rows, errorCorrectionLevel, barcodeMatrix);
}
/**
* Determine optimal nr of columns and rows for the specified number of
* codewords.
*
* @param sourceCodeWords number of code words
* @param errorCorrectionCodeWords number of error correction code words
* @return dimension object containing cols as width and rows as height
*/
private int[] determineDimensions(int sourceCodeWords, int errorCorrectionCodeWords) throws WriterException {
float ratio = 0.0f;
int[] dimension = null;
for (int cols = minCols; cols <= maxCols; cols++) {
int rows = calculateNumberOfRows(sourceCodeWords, errorCorrectionCodeWords, cols);
if (rows < minRows) {
break;
}
if (rows > maxRows) {
continue;
}
float newRatio = ((17 * cols + 69) * DEFAULT_MODULE_WIDTH) / (rows * HEIGHT);
// ignore if previous ratio is closer to preferred ratio
if (dimension != null && Math.abs(newRatio - PREFERRED_RATIO) > Math.abs(ratio - PREFERRED_RATIO)) {
continue;
}
ratio = newRatio;
dimension = new int[]{cols, rows};
}
// Handle case when min values were larger than necessary
if (dimension == null) {
int rows = calculateNumberOfRows(sourceCodeWords, errorCorrectionCodeWords, minCols);
if (rows < minRows) {
dimension = new int[]{minCols, minRows};
}
}
if (dimension == null) {
throw new WriterException("Unable to fit message in columns");
}
return dimension;
}
/**
* Sets max/min row/col values
*
* @param maxCols maximum allowed columns
* @param minCols minimum allowed columns
* @param maxRows maximum allowed rows
* @param minRows minimum allowed rows
*/
public void setDimensions(int maxCols, int minCols, int maxRows, int minRows) {
this.maxCols = maxCols;
this.minCols = minCols;
this.maxRows = maxRows;
this.minRows = minRows;
}
/**
* @param compaction compaction mode to use
*/
public void setCompaction(Compaction compaction) {
this.compaction = compaction;
}
/**
* @param compact if true, enables compaction
*/
public void setCompact(boolean compact) {
this.compact = compact;
}
/**
* @param encoding sets character encoding to use
*/
public void setEncoding(Charset encoding) {
this.encoding = encoding;
}
}
| |
package dulleh.akhyou.Models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import dulleh.akhyou.MainApplication;
public class Anime implements Parcelable{
public static final int ANIME_RUSH = 0;
public static final CharSequence ANIME_RUSH_TITLE = "ANIMERUSH";
public static final int ANIME_RAM = 1;
public static final CharSequence ANIME_RAM_TITLE = "ANIMERAM";
// has to be here cos conflicts with V
public Anime () {}
private Anime(Parcel in) {
providerType = in.readInt();
title = in.readString();
desc = in.readString();
url = in.readString();
imageUrl = in.readString();
status = in.readString();
alternateTitle = in.readString();
date = in.readString();
genres = in.createStringArray();
genresString = in.readString();
episodes = new ArrayList<>();
in.readList(episodes, null);
majorColour = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(providerType);
parcel.writeString(title);
parcel.writeString(desc);
parcel.writeString(url);
parcel.writeString(imageUrl);
parcel.writeString(status);
parcel.writeString(alternateTitle);
parcel.writeString(date);
parcel.writeStringArray(genres);
parcel.writeString(genresString);
parcel.writeList(episodes);
parcel.writeInt(majorColour);
}
public static final Creator<Anime> CREATOR = new Creator<Anime>() {
@Override
public Anime createFromParcel(Parcel in) {
return new Anime(in);
}
@Override
public Anime[] newArray(int size) {
return new Anime[size];
}
};
// ---------------------------------------------------------------------------------- //
private Integer providerType; // if null: GeneralUtils.determineProviderType()
private String title;
private String desc;
private String url;
private String imageUrl;
private String status;
private String alternateTitle;
private String date;
private String[] genres;
private String genresString;
private List<Episode> episodes;
// default to accent color
private int majorColour = MainApplication.RED_ACCENT_RGB;
public Integer getProviderType() {
return providerType;
}
public Anime setProviderType(int providerType) {
this.providerType = providerType;
return this;
}
public String getTitle() {
return title;
}
public Anime setTitle(String title) {
this.title = title;
return this;
}
public String getDesc() {
return desc;
}
public Anime setDesc(String desc) {
this.desc = desc.trim();
return this;
}
public String getUrl() {
return url;
}
public Anime setUrl(String url) {
this.url = url.trim();
return this;
}
public String getImageUrl() {
return imageUrl;
}
public Anime setImageUrl(String imageUrl) {
this.imageUrl = imageUrl.trim();
return this;
}
public String[] getGenres() {
return genres;
}
public Anime setGenres(String[] genres) {
this.genres = genres;
return this;
}
public String getGenresString() {
return genresString;
}
public Anime setGenresString(String genresString) {
this.genresString = genresString.trim();
return this;
}
public List<Episode> getEpisodes() {
return episodes;
}
public Anime setEpisodes(List<Episode> episodes) {
this.episodes = episodes;
return this;
}
public String getDate() {
return date;
}
public Anime setDate(String date) {
this.date = date.trim();
return this;
}
public String getAlternateTitle() {
return alternateTitle;
}
public Anime setAlternateTitle(String alternateTitle) {
this.alternateTitle = alternateTitle.trim();
return this;
}
public String getStatus() {
return status;
}
public Anime setStatus(String status) {
this.status = status.trim();
return this;
}
public int getMajorColour() {
return majorColour;
}
public Anime setMajorColour(int majorColour) {
this.majorColour = majorColour;
return this;
}
public void inheritWatchedFrom (List<Episode> oldEpisodes) {
if (episodes != null) {
List<String> episodeTitles = new LinkedList<>();
for (Episode oldEpisode : oldEpisodes) {
episodeTitles.add(oldEpisode.getTitle());
}
for (int i = 0; i < episodes.size(); i++) {
Episode episode = episodes.get(i);
if (episodeTitles.contains(episode.getTitle())) {
episodes.set(i, episode.setWatched(oldEpisodes.get(episodeTitles.indexOf(episode.getTitle())).isWatched()));
}
}
}
}
}
| |
/*
* Copyright 2015 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marklogic.jena.functionaltests;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.util.Iterator;
import org.apache.jena.riot.RDFDataMgr;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.NodeFactory;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.query.ReadWrite;
import com.hp.hpl.jena.shared.Lock;
import com.hp.hpl.jena.shared.LockNone;
import com.hp.hpl.jena.sparql.core.Quad;
import com.hp.hpl.jena.sparql.util.Context;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.query.QueryDefinition;
import com.marklogic.client.semantics.Capability;
import com.marklogic.client.semantics.GraphPermissions;
import com.marklogic.client.semantics.SPARQLQueryDefinition;
import com.marklogic.client.semantics.SPARQLRuleset;
import com.marklogic.semantics.jena.MarkLogicDatasetGraph;
import com.marklogic.semantics.jena.MarkLogicDatasetGraphFactory;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class JenaGraphTests extends ConnectedRESTQA {
private static String dbName = "Jena-JavaAPI-Functional";
private static String[] fNames = { "Jena-JavaAPI-Functional-1" };
private static String restServerName = "REST-Java-Client-JenaAPI-Server";
private static int restPort = 8014;
private static int uberPort = 8000;
private DatabaseClient adminClient = null;
private DatabaseClient writerClient = null;
private DatabaseClient readerClient = null;
private DatabaseClient evalClient = null;
private static String datasource = "src/test/java/com/marklogic/jena/functionaltest/data/";
private static MarkLogicDatasetGraph markLogicDatasetGraphWriter;
private static MarkLogicDatasetGraph markLogicDatasetGraphReader;
private static MarkLogicDatasetGraph markLogicDatasetGraphAdmin;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("In setup");
setupJavaRESTServer(dbName, fNames[0], restServerName, restPort);
setupAppServicesConstraint(dbName);
enableCollectionLexicon(dbName);
enableTripleIndex(dbName);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("In tear down");
// Delete database first. Otherwise axis and collection cannot be
// deleted
tearDownJavaRESTServer(dbName, fNames, restServerName);
deleteRESTUser("eval-user");
deleteUserRole("test-eval");
}
@After
public void testCleanUp() throws Exception {
if(markLogicDatasetGraphAdmin.getDatabaseClient() != null){
markLogicDatasetGraphAdmin.close();
}
if(markLogicDatasetGraphWriter.getDatabaseClient() != null){
markLogicDatasetGraphWriter.close();
}
if(markLogicDatasetGraphReader.getDatabaseClient() != null){
markLogicDatasetGraphReader.close();
}
clearDB(restPort);
adminClient.release();
writerClient.release();
readerClient.release();
System.out.println("Running clear script");
}
@Before
public void setUp() throws Exception {
createUserRolesWithPrevilages("test-eval", "xdbc:eval", "xdbc:eval-in", "xdmp:eval-in", "any-uri", "xdbc:invoke");
createRESTUser("eval-user", "x", "test-eval", "rest-admin", "rest-writer", "rest-reader");
adminClient = DatabaseClientFactory.newClient("localhost", restPort, dbName, "rest-admin", "x", Authentication.DIGEST);
writerClient = DatabaseClientFactory.newClient("localhost", restPort, dbName, "rest-writer", "x", Authentication.DIGEST);
readerClient = DatabaseClientFactory.newClient("localhost", restPort, dbName, "rest-reader", "x", Authentication.DIGEST);
evalClient = DatabaseClientFactory.newClient("localhost", uberPort, dbName, "eval-user", "x", Authentication.DIGEST);
markLogicDatasetGraphWriter = MarkLogicDatasetGraphFactory.createDatasetGraph(writerClient);
markLogicDatasetGraphReader = MarkLogicDatasetGraphFactory.createDatasetGraph(readerClient);
markLogicDatasetGraphAdmin = MarkLogicDatasetGraphFactory.createDatasetGraph("localhost", 8014, "rest-admin", "x",
Authentication.DIGEST);
}
/*
* With AdminUser Get Default Graph , Add Triples into Graph and validate
* the Triples Add Named Graph and validate Clear Data and Validate Close
* Dataset
*/
@Test
public void testCrud_admin() {
// Insert Triples into Graph
markLogicDatasetGraphAdmin.clear();
Graph g1 = markLogicDatasetGraphAdmin.getDefaultGraph();
assertTrue(g1.isEmpty());
assertNotNull(g1);
Triple triple = new Triple(NodeFactory.createURI("s5"), NodeFactory.createURI("p5"), NodeFactory.createURI("o5"));
g1.add(triple);
Node n1 = NodeFactory.createURI("http://example.org/jenaAdd");
Quad quad = new Quad(n1, triple);
// Add Named Graph and validate triples
markLogicDatasetGraphAdmin.addGraph(n1, g1);
Graph g2 = markLogicDatasetGraphAdmin.getGraph(n1);
assertTrue("did not match Triples", g2.contains(triple));
// Get Permissions of the named Graph and Validate
GraphPermissions permissions = markLogicDatasetGraphAdmin.getPermissions(n1);
assertTrue("Didnot have expected permissions, returned " + permissions, permissions.get("rest-writer").contains(Capability.UPDATE)
&& permissions.get("rest-reader").contains(Capability.READ));
// Remove all data and validate
markLogicDatasetGraphAdmin.clear();
Graph g3 = markLogicDatasetGraphAdmin.getGraph(n1);
assertTrue("Expecting empty graph, received " + g3.toString(), g3.toString().contains("{}"));
// AFTER CLEAR add new graph and Quad with same triple and Graph node
markLogicDatasetGraphAdmin.addGraph(n1, g1);
markLogicDatasetGraphAdmin.add(quad);
Iterator<Quad> quads = markLogicDatasetGraphAdmin.find(null, null, null, null);
while (quads.hasNext()) {
Quad quad1 = quads.next();
assertTrue(quad1.equals(quad));
}
Iterator<Quad> quads1 = markLogicDatasetGraphAdmin.find(Node.ANY, Node.ANY, Node.ANY, Node.ANY);
while (quads1.hasNext()) {
Quad quad1 = quads1.next();
assertTrue(quad1.equals(quad));
}
// Delete All triples in Named Graph and verify
markLogicDatasetGraphAdmin.deleteAny(n1, null, null, null);
assertFalse(markLogicDatasetGraphAdmin.getGraph(n1).contains(triple));
// Get Size on DataSet and Catch UnSupported Exception
Exception exp = null;
try{
markLogicDatasetGraphAdmin.size();
}catch(Exception e){
exp =e;
}
assertTrue("Size not supported",exp.toString().contains("UnsupportedOperationException") && exp != null);
// Get Lock on DataSet and and verify LockNone
Lock lck = markLogicDatasetGraphAdmin.getLock();
System.out.println(lck.toString());
assertTrue("getLock not supported",lck != null);
markLogicDatasetGraphAdmin.close();
exp = null;
try {
markLogicDatasetGraphAdmin.addGraph(n1, g1);
} catch (Exception e) {
System.out.println("EXCEPTION AFTER CLOSE" + e);
exp = e;
}
assertTrue("Should Throw DatabaseGraph is closed Exception", exp.toString().contains("DatabaseGraph is closed"));
}
/*
* List All the Graph using rest write user
*/
@Test
public void testListGraphs_WriteUser() throws FileNotFoundException {
// Write New graph with ntriples mimetype & Validate
String file = datasource + "relative1.nt";
// Read triples into dataset
RDFDataMgr.read(markLogicDatasetGraphWriter, file);
markLogicDatasetGraphWriter.sync();
// Add Triples into Named Graph
Graph g = markLogicDatasetGraphWriter.getDefaultGraph();
Node newgraph = NodeFactory.createURI("http://jena.example.org/fileWrite");
markLogicDatasetGraphWriter.addGraph(newgraph, g);
// Get the list of graphs and validate
Iterator<Node> markLogicGraphs = markLogicDatasetGraphWriter.listGraphNodes();
while (markLogicGraphs.hasNext()) {
Node graphs = markLogicGraphs.next();
assertTrue(
"did not find Node in :: " + graphs.toString(),
graphs.toString().contains("http://jena.example.org/fileWrite")
|| graphs.toString().contains(MarkLogicDatasetGraph.DEFAULT_GRAPH_URI)
|| graphs.toString().contains("http://marklogic.com/semantics#graphs"));
}
}
@Test
public void test002Add_Quads() throws Exception {
// Add and validate Quad
markLogicDatasetGraphWriter.add(NodeFactory.createURI("testing/quad_add"), NodeFactory.createURI("testing/subject_1"),
NodeFactory.createURI("testing/predicate_1"), NodeFactory.createLiteral("testing/Object_1"));
Node graphNode = NodeFactory.createURI("testing/quad_add");
Boolean found = markLogicDatasetGraphWriter.containsGraph(graphNode);
assertTrue("Did not find the Graph Node ::" + graphNode + "Returned" + found, found);
markLogicDatasetGraphWriter.deleteAny(NodeFactory.createURI("testing/quad_add"), Node.ANY, Node.ANY, Node.ANY);
// Add and Validate Quad
Quad quad = new Quad(NodeFactory.createURI("http://originalGraph"), NodeFactory.createURI("#electricVehicle2"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
NodeFactory.createURI("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle"));
Quad quad2 = new Quad(NodeFactory.createURI("http://originalGraph"), NodeFactory.createURI("#electricVehicle21"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createURI("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1"));
markLogicDatasetGraphWriter.add(quad);
// Validate quad using contains node's
found = markLogicDatasetGraphWriter.contains(NodeFactory.createURI("http://originalGraph"),
NodeFactory.createURI("#electricVehicle2"), NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
NodeFactory.createURI("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle"));
assertTrue("Did not find the Quad Node ::" + quad + "Returned" + found, found);
Iterator<Quad> quads = markLogicDatasetGraphWriter.find(quad);
while (quads.hasNext()) {
Quad quad1 = quads.next();
assertTrue(quad1.equals(quad));
}
// Delete Non existing quad and validate Inserted quad exists
markLogicDatasetGraphWriter.delete(quad2);
quads = markLogicDatasetGraphWriter.find();
while (quads.hasNext()) {
Quad quad1 = quads.next();
assertTrue(quad1.equals(quad));
}
// Delete existing Quad and validate
markLogicDatasetGraphWriter.delete(NodeFactory.createURI("http://originalGraph"), NodeFactory.createURI("#electricVehicle2"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
NodeFactory.createURI("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle"));
assertFalse(markLogicDatasetGraphWriter.contains(NodeFactory.createURI("http://originalGraph"),
NodeFactory.createURI("#electricVehicle2"), NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
NodeFactory.createURI("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle")));
// Find and validate Quad doesnot exist
Iterator<Quad> quads1 = markLogicDatasetGraphWriter.find(quad);
Boolean quads1has = quads1.hasNext();
assertFalse(quads1.hasNext());
quads1 = markLogicDatasetGraphWriter.find();
assertFalse(quads1.hasNext());
// Merge Graphs and Validate triples
String file = datasource + "semantics.nq";
RDFDataMgr.read(markLogicDatasetGraphWriter, file);
markLogicDatasetGraphWriter.sync();
Graph g = markLogicDatasetGraphWriter.getGraph(NodeFactory
.createURI("http://en.wikipedia.org/wiki/Apollo_13?oldid=495374925#absolute-line=6"));
markLogicDatasetGraphWriter.mergeGraph(graphNode, g);
Graph mergedgraph = markLogicDatasetGraphWriter.getGraph(graphNode);
int size = mergedgraph.size();
assertTrue("Merged graph dpes not have expected number of triples", mergedgraph.size() == 4);
// Remove Graph and validate
markLogicDatasetGraphWriter.removeGraph(graphNode);
assertTrue("The graph Shold not Exist after delete", !(markLogicDatasetGraphWriter.containsGraph(graphNode)));
// Delete non existing graph, expected to throw ResourceNotfound
// Exception
Exception exp = null;
try {
markLogicDatasetGraphWriter.removeGraph(graphNode);
} catch (Exception e) {
exp = e;
}
assertTrue("Deleting non Existing Grpah should throw ResourceNot found exception, but it did not",
exp.toString().contains("ResourceNotFoundException"));
markLogicDatasetGraphWriter.close();
}
/*
* Add Quad with Read User and Catch ForbiddenUser Exception
*/
@Test
public void testAdd_ReadUser() throws FileNotFoundException {
Exception exp = null;
try {
Quad quad = new Quad(NodeFactory.createURI("http://originalGraph1"), new Triple(NodeFactory.createURI("#electricVehicle3"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1")));
markLogicDatasetGraphReader.add(quad);
markLogicDatasetGraphReader.sync();
assertFalse(markLogicDatasetGraphReader.contains(quad));
} catch (Exception e) {
exp = e;
}
assertTrue("Should catch ForbiddenUserException ", exp.toString().contains("ForbiddenUserException") && exp != null);
}
/*
* Add Quad with Admin User and Read with Read user and validate using find,
* findNG with null and ANY, contains
*/
@Test
public void testAddRead_AdminUser() throws Exception {
Quad quad = new Quad(NodeFactory.createURI("http://originalGraph1"), new Triple(NodeFactory.createURI("#electricVehicle3"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1")));
markLogicDatasetGraphAdmin.add(quad);
markLogicDatasetGraphAdmin.sync();
// Contains Node of type quad
assertTrue(
"Did not find Quad in Dataset, Received " + markLogicDatasetGraphReader.contains(quad),
markLogicDatasetGraphReader.contains(NodeFactory.createURI("http://originalGraph1"),
NodeFactory.createURI("#electricVehicle3"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1")));
// find node
Iterator<Quad> result = markLogicDatasetGraphReader.find(NodeFactory.createURI("http://originalGraph1"),
NodeFactory.createURI("#electricVehicle3"), NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1"));
while (result.hasNext()) {
Quad quad1 = result.next();
assertTrue(
"returned" + quad1,
quad1.matches(NodeFactory.createURI("http://originalGraph1"), NodeFactory.createURI("#electricVehicle3"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1")));
}
// find node with pattern null and any
Iterator<Quad> result1 = markLogicDatasetGraphReader.find(null, NodeFactory.createURI("#electricVehicle3"), Node.ANY,
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1"));
while (result1.hasNext()) {
Quad quad1 = result1.next();
assertTrue(
"returned" + quad1,
quad1.matches(NodeFactory.createURI("http://originalGraph1"), NodeFactory.createURI("#electricVehicle3"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1")));
}
// findNG with any and null
Iterator<Quad> result2 = markLogicDatasetGraphReader.findNG(NodeFactory.createURI("http://originalGraph1"), Node.ANY,
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"), null);
while (result2.hasNext()) {
Quad quad1 = result2.next();
assertTrue(
"returned" + quad1,
quad1.matches(NodeFactory.createURI("http://originalGraph1"), NodeFactory.createURI("#electricVehicle3"),
NodeFactory.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type1"),
NodeFactory.createLiteral("http://people.aifb.kit.edu/awa/2011/smartgrid/schema/smartgrid#ElectricVehicle1")));
}
Node n1 = NodeFactory.createURI("http://originalGraph1");
markLogicDatasetGraphAdmin.clearPermissions(n1);
GraphPermissions permissions = markLogicDatasetGraphAdmin.getPermissions(n1);
assertTrue("Didnot have expected permissions, returned " + permissions, permissions.get("rest-writer").contains(Capability.UPDATE)
&& permissions.get("rest-reader").contains(Capability.READ));
}
@Test
public void testSetDefaultGraph_admin() {
String file = datasource + "relative1.nt";
// Read triples into dataset
RDFDataMgr.read(markLogicDatasetGraphWriter, file);
markLogicDatasetGraphWriter.sync();
Graph g1 = markLogicDatasetGraphWriter.getDefaultGraph();
assertTrue("did not match Triples", g1.toString().contains("#electricVehicle2"));
// Create New graph and add triples from defaultgraph to new graph
Triple triple = new Triple(NodeFactory.createURI("s5"), NodeFactory.createURI("p5"), NodeFactory.createURI("o5"));
Quad quad = new Quad(NodeFactory.createURI("new-graph-fordefault"), triple);
Node n1 = NodeFactory.createURI("new-graph-fordefault");
markLogicDatasetGraphWriter.add(quad);
markLogicDatasetGraphWriter.sync();
Graph g2 = markLogicDatasetGraphWriter.getGraph(n1);
assertTrue("did not match Triples", g2.contains(triple));
// Set DefaultGraph to be NamedGraph
markLogicDatasetGraphWriter.setDefaultGraph(g2);
Graph defaultG = markLogicDatasetGraphWriter.getDefaultGraph();
assertTrue("did not match Triples", defaultG.contains(triple));
}
/*
* Delete triple and quad and set empty graph as default graph
*/
@Test
public void testDelete_admin() {
Triple triple = new Triple(NodeFactory.createURI("s5"), NodeFactory.createURI("p5"), NodeFactory.createURI("o5"));
Quad quad = new Quad(NodeFactory.createURI("new-graph-fordefault2"), triple);
Node n2 = NodeFactory.createURI("new-graph-fordefault2");
markLogicDatasetGraphWriter.add(quad);
markLogicDatasetGraphWriter.sync();
Graph g3 = markLogicDatasetGraphWriter.getGraph(n2);
g3.delete(triple);
markLogicDatasetGraphWriter.sync();
assertTrue("did not match Triples", g3.size() == 0);
markLogicDatasetGraphWriter.delete(quad);
assertTrue("Quad Should be deleted , but looks like its not", !markLogicDatasetGraphWriter.contains(quad));
markLogicDatasetGraphWriter.setDefaultGraph(g3);
Graph defaultG = markLogicDatasetGraphWriter.getDefaultGraph();
assertTrue("did not match Triples", defaultG.size() == 0);
}
@Test
public void test001AddDelete_permissions() {
String file = datasource + "rdfxml1.rdf";
// Read triples into dataset
RDFDataMgr.read(markLogicDatasetGraphWriter, file);
markLogicDatasetGraphWriter.sync();
// Add Triples into Named Graph
Graph g = markLogicDatasetGraphWriter.getDefaultGraph();
Node newgraph = NodeFactory.createURI("http://jena.example.org/perm");
// Add Graph and Validate
markLogicDatasetGraphWriter.addGraph(newgraph, g);
markLogicDatasetGraphWriter.sync();
markLogicDatasetGraphWriter.clearPermissions(newgraph);//
assertTrue(markLogicDatasetGraphWriter.containsGraph(newgraph));
GraphPermissions permissions = markLogicDatasetGraphAdmin.getPermissions(newgraph);
markLogicDatasetGraphWriter.addPermissions(newgraph, permissions.permission("test-eval", Capability.EXECUTE));
permissions = markLogicDatasetGraphWriter.getPermissions(newgraph);
System.out.println(markLogicDatasetGraphWriter.getPermissions(newgraph));
assertTrue("Did not have permission looking for", permissions.get("test-eval").contains(Capability.EXECUTE));
//
markLogicDatasetGraphWriter.addPermissions(newgraph, permissions.permission("test-eval", Capability.UPDATE));
System.out.println(" added one more capability ===="+markLogicDatasetGraphWriter.getPermissions(newgraph));
assertTrue(permissions.get("test-eval").size() == 2);
//
markLogicDatasetGraphWriter.clearPermissions(newgraph);
markLogicDatasetGraphWriter.sync();
permissions = markLogicDatasetGraphWriter.getPermissions(newgraph);
System.out.println(permissions);
assertTrue("Should not have Execute for test-eval", !(permissions.containsValue("test-eval")));
// Set Execute permissions and validate
permissions = permissions.permission("test-eval", Capability.EXECUTE);
markLogicDatasetGraphWriter.writePermissions(newgraph, permissions);
assertTrue("Did not have permission looking for", permissions.get("test-eval").contains(Capability.EXECUTE));
// Set UPDATE permissions and validate
permissions.clear();
permissions = permissions.permission("test-eval", Capability.UPDATE);
markLogicDatasetGraphWriter.writePermissions(newgraph, permissions);
System.out.println(" added one more capability ===="+markLogicDatasetGraphWriter.getPermissions(newgraph));
permissions = markLogicDatasetGraphWriter.getPermissions(newgraph);
assertTrue(permissions.get("test-eval").size() == 1);
assertTrue("Did not have permission looking for", permissions.get("test-eval").contains(Capability.UPDATE));
// Set the same permission for the same graph
markLogicDatasetGraphWriter.writePermissions(newgraph, permissions);
assertTrue(permissions.get("test-eval").size() == 1);
}
@Test
public void testAddDelete_permissions_inTrx() throws Exception {
String file = datasource + "rdfxml1.rdf";
try {
// Read triples into dataset
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
RDFDataMgr.read(markLogicDatasetGraphWriter, file);
markLogicDatasetGraphWriter.sync();
// Add Triples into Named Graph
Graph g = markLogicDatasetGraphWriter.getDefaultGraph();
Node newgraph = NodeFactory.createURI("http://jena.example.org/perm");
markLogicDatasetGraphWriter.addGraph(newgraph, g);
markLogicDatasetGraphWriter.commit();
assertFalse(markLogicDatasetGraphWriter.isInTransaction());
GraphPermissions permissions = markLogicDatasetGraphAdmin.getPermissions(newgraph);
// Add Permission and validate
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
markLogicDatasetGraphWriter.addPermissions(newgraph, permissions.permission("test-eval", Capability.EXECUTE));
markLogicDatasetGraphWriter.commit();
permissions = markLogicDatasetGraphWriter.getPermissions(newgraph);
System.out.println(markLogicDatasetGraphWriter.getPermissions(newgraph));
assertTrue("Did not have permission looking for", permissions.get("test-eval").contains(Capability.EXECUTE));
// Clear Permission and Abort and validate permission exist
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
markLogicDatasetGraphWriter.clearPermissions(newgraph);
markLogicDatasetGraphWriter.end();
assertFalse(markLogicDatasetGraphWriter.isInTransaction());
permissions = markLogicDatasetGraphWriter.getPermissions(newgraph);
assertTrue("Did not have permission looking for", permissions.get("test-eval").contains(Capability.EXECUTE));
// Clear Permission And validate
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
markLogicDatasetGraphWriter.clearPermissions(newgraph);
markLogicDatasetGraphWriter.commit();
assertFalse(markLogicDatasetGraphWriter.isInTransaction());
System.out.println(markLogicDatasetGraphWriter.getPermissions(newgraph));
permissions = markLogicDatasetGraphWriter.getPermissions(newgraph);
assertTrue("Should not contain test-eval=[EXECUTE]", !(permissions.toString().contains("test-eval=[EXECUTE]")));
} catch (Exception e) {
System.out.println(e);
} finally {
if (markLogicDatasetGraphWriter.isInTransaction())
markLogicDatasetGraphWriter.end();
}
}
/*
* Add/Delete Quad and graph within Transaction
*/
@Test
public void testCRUD_InTrx() throws Exception {
String file = datasource + "rdfxml1.rdf";
try {
Node newgraph = NodeFactory.createURI("http://jena.example.org/perm");
// Read triples into dataset & Add to named graph
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
RDFDataMgr.read(markLogicDatasetGraphWriter, file);
markLogicDatasetGraphWriter.sync();
Graph g = markLogicDatasetGraphWriter.getDefaultGraph();
markLogicDatasetGraphWriter.addGraph(newgraph, g);
markLogicDatasetGraphWriter.commit();
// Delete one Triple and Validate
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
markLogicDatasetGraphWriter.deleteAny(newgraph, Node.ANY, NodeFactory.createURI("http://example.org/kennedy/sameAs"), Node.ANY);
markLogicDatasetGraphWriter.commit();
markLogicDatasetGraphWriter.sync();
Quad quad = new Quad(newgraph, Node.ANY, NodeFactory.createURI("http://example.org/kennedy/sameAs"), Node.ANY);
assertFalse(markLogicDatasetGraphWriter.contains(quad));
// Merge Graphs and validate
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
markLogicDatasetGraphWriter.mergeGraph(newgraph, g);
assertTrue(markLogicDatasetGraphWriter.contains(quad));
markLogicDatasetGraphWriter.commit();
// Delete Graph , Abort trx and Validate graph exists
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
markLogicDatasetGraphWriter.removeGraph(newgraph);
markLogicDatasetGraphWriter.abort();
assertFalse(markLogicDatasetGraphWriter.isInTransaction());
assertTrue(markLogicDatasetGraphWriter.contains(newgraph, Node.ANY, Node.ANY, Node.ANY));
// Delete Graph and Validate
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
markLogicDatasetGraphWriter.removeGraph(newgraph);
markLogicDatasetGraphWriter.commit();
assertFalse(markLogicDatasetGraphWriter.containsGraph(newgraph));
// Add Graph and Find Quads
markLogicDatasetGraphWriter.begin(ReadWrite.WRITE);
Node newgraph1 = NodeFactory.createURI("http://jena.example.org/perm1");
markLogicDatasetGraphWriter.addGraph(newgraph1, g);
Iterator<Quad> quads = markLogicDatasetGraphWriter.find();
assertTrue(quads.hasNext());
while (quads.hasNext()) {
Quad quad1 = quads.next();
System.out.println(quad1.getSubject());
assertTrue(quad1.getSubject().matches(NodeFactory.createURI("http://example.org/kennedy/person1")));
}
// Commit and validate outside trx
markLogicDatasetGraphWriter.commit();
quads = markLogicDatasetGraphWriter.find();
assertTrue(quads.hasNext());
while (quads.hasNext()) {
Quad quad1 = quads.next();
System.out.println(quad1.getSubject());
assertTrue(quad1.getSubject().matches(NodeFactory.createURI("http://example.org/kennedy/person1")));
}
// READ trx
Exception exp = null;
try {
markLogicDatasetGraphWriter.begin(ReadWrite.READ);
Iterator<Quad> quadsRead = markLogicDatasetGraphWriter.find();
assertTrue(quads.hasNext());
while (quadsRead.hasNext()) {
Quad quad1 = quadsRead.next();
System.out.println(quad1.getSubject());
assertTrue(quad1.getSubject().matches(NodeFactory.createURI("http://example.org/kennedy/person1")));
}
} catch (Exception e) {
exp = e;
System.out.println(e);
}
assertTrue("should throw:: MarkLogic only supports write transactions",
exp.toString().contains(" MarkLogic only supports write transactions"));
markLogicDatasetGraphWriter.end();
} catch (Exception e) {
} finally {
if (markLogicDatasetGraphWriter.isInTransaction())
markLogicDatasetGraphWriter.end();
}
}
/*
* -ve parsing with wrong format
*/
@Test
public void testCRUD_triplexml() {
String file = datasource + "triplexml1.xml";
Exception exp = null;
// Read triples into dataset
try {
RDFDataMgr.read(markLogicDatasetGraphWriter, file);
markLogicDatasetGraphWriter.sync();
Graph g1 = markLogicDatasetGraphWriter.getDefaultGraph();
assertTrue("did not match Triples", g1.toString().contains("Anna's Homepage"));
} catch (Exception e) {
exp = e;
}
assertTrue(exp.toString().contains("RiotException") && exp != null);
}
}
| |
/*
* Copyright (C) 2012 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.okhttp;
import com.squareup.okhttp.internal.Util;
import com.squareup.okhttp.internal.http.HttpAuthenticator;
import com.squareup.okhttp.internal.http.HttpURLConnectionImpl;
import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl;
import com.squareup.okhttp.internal.http.OkResponseCacheAdapter;
import com.squareup.okhttp.internal.tls.OkHostnameVerifier;
import java.net.CookieHandler;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.ResponseCache;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
/** Configures and creates HTTP connections. */
public final class OkHttpClient implements URLStreamHandlerFactory {
private static final List<String> DEFAULT_TRANSPORTS
= Util.immutableList(Arrays.asList("spdy/3", "http/1.1"));
private final RouteDatabase routeDatabase;
private final Dispatcher dispatcher;
private Proxy proxy;
private List<String> transports;
private ProxySelector proxySelector;
private CookieHandler cookieHandler;
private ResponseCache responseCache;
private SSLSocketFactory sslSocketFactory;
private HostnameVerifier hostnameVerifier;
private OkAuthenticator authenticator;
private ConnectionPool connectionPool;
private boolean followProtocolRedirects = true;
private int connectTimeout;
private int readTimeout;
public OkHttpClient() {
routeDatabase = new RouteDatabase();
dispatcher = new Dispatcher();
}
private OkHttpClient(OkHttpClient copyFrom) {
routeDatabase = copyFrom.routeDatabase;
dispatcher = copyFrom.dispatcher;
}
/**
* Sets the default connect timeout for new connections. A value of 0 means no timeout.
*
* @see URLConnection#setConnectTimeout(int)
*/
public void setConnectTimeout(long timeout, TimeUnit unit) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout < 0");
}
if (unit == null) {
throw new IllegalArgumentException("unit == null");
}
long millis = unit.toMillis(timeout);
if (millis > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Timeout too large.");
}
connectTimeout = (int) millis;
}
/** Default connect timeout (in milliseconds). */
public int getConnectTimeout() {
return connectTimeout;
}
/**
* Sets the default read timeout for new connections. A value of 0 means no timeout.
*
* @see URLConnection#setReadTimeout(int)
*/
public void setReadTimeout(long timeout, TimeUnit unit) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout < 0");
}
if (unit == null) {
throw new IllegalArgumentException("unit == null");
}
long millis = unit.toMillis(timeout);
if (millis > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Timeout too large.");
}
readTimeout = (int) millis;
}
/** Default read timeout (in milliseconds). */
public int getReadTimeout() {
return readTimeout;
}
/**
* Sets the HTTP proxy that will be used by connections created by this
* client. This takes precedence over {@link #setProxySelector}, which is
* only honored when this proxy is null (which it is by default). To disable
* proxy use completely, call {@code setProxy(Proxy.NO_PROXY)}.
*/
public OkHttpClient setProxy(Proxy proxy) {
this.proxy = proxy;
return this;
}
public Proxy getProxy() {
return proxy;
}
/**
* Sets the proxy selection policy to be used if no {@link #setProxy proxy}
* is specified explicitly. The proxy selector may return multiple proxies;
* in that case they will be tried in sequence until a successful connection
* is established.
*
* <p>If unset, the {@link ProxySelector#getDefault() system-wide default}
* proxy selector will be used.
*/
public OkHttpClient setProxySelector(ProxySelector proxySelector) {
this.proxySelector = proxySelector;
return this;
}
public ProxySelector getProxySelector() {
return proxySelector;
}
/**
* Sets the cookie handler to be used to read outgoing cookies and write
* incoming cookies.
*
* <p>If unset, the {@link CookieHandler#getDefault() system-wide default}
* cookie handler will be used.
*/
public OkHttpClient setCookieHandler(CookieHandler cookieHandler) {
this.cookieHandler = cookieHandler;
return this;
}
public CookieHandler getCookieHandler() {
return cookieHandler;
}
/**
* Sets the response cache to be used to read and write cached responses.
*
* <p>If unset, the {@link ResponseCache#getDefault() system-wide default}
* response cache will be used.
*/
public OkHttpClient setResponseCache(ResponseCache responseCache) {
this.responseCache = responseCache;
return this;
}
public ResponseCache getResponseCache() {
return responseCache;
}
public OkResponseCache getOkResponseCache() {
if (responseCache instanceof HttpResponseCache) {
return ((HttpResponseCache) responseCache).okResponseCache;
} else if (responseCache != null) {
return new OkResponseCacheAdapter(responseCache);
} else {
return null;
}
}
/**
* Sets the socket factory used to secure HTTPS connections.
*
* <p>If unset, the {@link HttpsURLConnection#getDefaultSSLSocketFactory()
* system-wide default} SSL socket factory will be used.
*/
public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
return this;
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
/**
* Sets the verifier used to confirm that response certificates apply to
* requested hostnames for HTTPS connections.
*
* <p>If unset, the {@link HttpsURLConnection#getDefaultHostnameVerifier()
* system-wide default} hostname verifier will be used.
*/
public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
return this;
}
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
/**
* Sets the authenticator used to respond to challenges from the remote web
* server or proxy server.
*
* <p>If unset, the {@link java.net.Authenticator#setDefault system-wide default}
* authenticator will be used.
*/
public OkHttpClient setAuthenticator(OkAuthenticator authenticator) {
this.authenticator = authenticator;
return this;
}
public OkAuthenticator getAuthenticator() {
return authenticator;
}
/**
* Sets the connection pool used to recycle HTTP and HTTPS connections.
*
* <p>If unset, the {@link ConnectionPool#getDefault() system-wide
* default} connection pool will be used.
*/
public OkHttpClient setConnectionPool(ConnectionPool connectionPool) {
this.connectionPool = connectionPool;
return this;
}
public ConnectionPool getConnectionPool() {
return connectionPool;
}
/**
* Configure this client to follow redirects from HTTPS to HTTP and from HTTP
* to HTTPS.
*
* <p>If unset, protocol redirects will be followed. This is different than
* the built-in {@code HttpURLConnection}'s default.
*/
public OkHttpClient setFollowProtocolRedirects(boolean followProtocolRedirects) {
this.followProtocolRedirects = followProtocolRedirects;
return this;
}
public boolean getFollowProtocolRedirects() {
return followProtocolRedirects;
}
public RouteDatabase getRoutesDatabase() {
return routeDatabase;
}
/**
* Configure the transports used by this client to communicate with remote
* servers. By default this client will prefer the most efficient transport
* available, falling back to more ubiquitous transports. Applications should
* only call this method to avoid specific compatibility problems, such as web
* servers that behave incorrectly when SPDY is enabled.
*
* <p>The following transports are currently supported:
* <ul>
* <li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">http/1.1</a>
* <li><a href="http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3">spdy/3</a>
* </ul>
*
* <p><strong>This is an evolving set.</strong> Future releases may drop
* support for transitional transports (like spdy/3), in favor of their
* successors (spdy/4 or http/2.0). The http/1.1 transport will never be
* dropped.
*
* <p>If multiple protocols are specified, <a
* href="https://technotes.googlecode.com/git/nextprotoneg.html">NPN</a> will
* be used to negotiate a transport. Future releases may use another mechanism
* (such as <a href="http://tools.ietf.org/html/draft-friedl-tls-applayerprotoneg-02">ALPN</a>)
* to negotiate a transport.
*
* @param transports the transports to use, in order of preference. The list
* must contain "http/1.1". It must not contain null.
*/
public OkHttpClient setTransports(List<String> transports) {
transports = Util.immutableList(transports);
if (!transports.contains("http/1.1")) {
throw new IllegalArgumentException("transports doesn't contain http/1.1: " + transports);
}
if (transports.contains(null)) {
throw new IllegalArgumentException("transports must not contain null");
}
if (transports.contains("")) {
throw new IllegalArgumentException("transports contains an empty string");
}
this.transports = transports;
return this;
}
public List<String> getTransports() {
return transports;
}
/**
* Schedules {@code request} to be executed.
*/
/* OkHttp 2.0: public */ void enqueue(Request request, Response.Receiver responseReceiver) {
// Create the HttpURLConnection immediately so the enqueued job gets the current settings of
// this client. Otherwise changes to this client (socket factory, redirect policy, etc.) may
// incorrectly be reflected in the request when it is dispatched later.
dispatcher.enqueue(open(request.url()), request, responseReceiver);
}
/**
* Cancels all scheduled tasks tagged with {@code tag}. Requests that are already
* in flight might not be canceled.
*/
/* OkHttp 2.0: public */ void cancel(Object tag) {
dispatcher.cancel(tag);
}
public HttpURLConnection open(URL url) {
return open(url, proxy);
}
HttpURLConnection open(URL url, Proxy proxy) {
String protocol = url.getProtocol();
OkHttpClient copy = copyWithDefaults();
copy.proxy = proxy;
if (protocol.equals("http")) return new HttpURLConnectionImpl(url, copy);
if (protocol.equals("https")) return new HttpsURLConnectionImpl(url, copy);
throw new IllegalArgumentException("Unexpected protocol: " + protocol);
}
/**
* Returns a shallow copy of this OkHttpClient that uses the system-wide default for
* each field that hasn't been explicitly configured.
*/
private OkHttpClient copyWithDefaults() {
OkHttpClient result = new OkHttpClient(this);
result.proxy = proxy;
result.proxySelector = proxySelector != null ? proxySelector : ProxySelector.getDefault();
result.cookieHandler = cookieHandler != null ? cookieHandler : CookieHandler.getDefault();
result.responseCache = responseCache != null ? responseCache : ResponseCache.getDefault();
result.sslSocketFactory = sslSocketFactory != null
? sslSocketFactory
: HttpsURLConnection.getDefaultSSLSocketFactory();
result.hostnameVerifier = hostnameVerifier != null
? hostnameVerifier
: OkHostnameVerifier.INSTANCE;
result.authenticator = authenticator != null
? authenticator
: HttpAuthenticator.SYSTEM_DEFAULT;
result.connectionPool = connectionPool != null ? connectionPool : ConnectionPool.getDefault();
result.followProtocolRedirects = followProtocolRedirects;
result.transports = transports != null ? transports : DEFAULT_TRANSPORTS;
result.connectTimeout = connectTimeout;
result.readTimeout = readTimeout;
return result;
}
/**
* Creates a URLStreamHandler as a {@link URL#setURLStreamHandlerFactory}.
*
* <p>This code configures OkHttp to handle all HTTP and HTTPS connections
* created with {@link URL#openConnection()}: <pre> {@code
*
* OkHttpClient okHttpClient = new OkHttpClient();
* URL.setURLStreamHandlerFactory(okHttpClient);
* }</pre>
*/
public URLStreamHandler createURLStreamHandler(final String protocol) {
if (!protocol.equals("http") && !protocol.equals("https")) return null;
return new URLStreamHandler() {
@Override protected URLConnection openConnection(URL url) {
return open(url);
}
@Override protected URLConnection openConnection(URL url, Proxy proxy) {
return open(url, proxy);
}
@Override protected int getDefaultPort() {
if (protocol.equals("http")) return 80;
if (protocol.equals("https")) return 443;
throw new AssertionError();
}
};
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.idea.maven.project;
import com.intellij.CommonBundle;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.notification.*;
import com.intellij.notification.impl.NotificationSettings;
import com.intellij.notification.impl.NotificationsConfigurationImpl;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.compiler.CompileContext;
import com.intellij.openapi.compiler.CompileTask;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.SettingsSavingComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProviderImpl;
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.ui.AppUIUtil;
import com.intellij.util.Alarm;
import com.intellij.util.EventDispatcher;
import com.intellij.util.NullableConsumer;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.update.Update;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.concurrency.AsyncPromise;
import org.jetbrains.concurrency.Promise;
import org.jetbrains.idea.maven.importing.MavenFoldersImporter;
import org.jetbrains.idea.maven.importing.MavenProjectImporter;
import org.jetbrains.idea.maven.model.*;
import org.jetbrains.idea.maven.server.MavenEmbedderWrapper;
import org.jetbrains.idea.maven.server.NativeMavenProjectHolder;
import org.jetbrains.idea.maven.utils.*;
import javax.swing.event.HyperlinkEvent;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
@State(name = "MavenProjectsManager")
public class MavenProjectsManager extends MavenSimpleProjectComponent
implements PersistentStateComponent<MavenProjectsManagerState>, SettingsSavingComponent {
private static final int IMPORT_DELAY = 1000;
private static final String NON_MANAGED_POM_NOTIFICATION_GROUP_ID = "Maven: non-managed pom.xml";
private static final NotificationGroup NON_MANAGED_POM_NOTIFICATION_GROUP =
NotificationGroup.balloonGroup(NON_MANAGED_POM_NOTIFICATION_GROUP_ID);
private final AtomicBoolean isInitialized = new AtomicBoolean();
private MavenProjectsManagerState myState = new MavenProjectsManagerState();
private final Alarm myInitializationAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD, myProject);
private final MavenEmbeddersManager myEmbeddersManager;
private MavenProjectsTree myProjectsTree;
private MavenProjectsManagerWatcher myWatcher;
private MavenProjectsProcessor myReadingProcessor;
private MavenProjectsProcessor myResolvingProcessor;
private MavenProjectsProcessor myPluginsResolvingProcessor;
private MavenProjectsProcessor myFoldersResolvingProcessor;
private MavenProjectsProcessor myArtifactsDownloadingProcessor;
private MavenProjectsProcessor myPostProcessor;
private MavenMergingUpdateQueue myImportingQueue;
private final Object myImportingDataLock = new Object();
private final Map<MavenProject, MavenProjectChanges> myProjectsToImport = new LinkedHashMap<MavenProject, MavenProjectChanges>();
private final Set<MavenProject> myProjectsToResolve = new LinkedHashSet<MavenProject>();
private boolean myImportModuleGroupsRequired = false;
private final EventDispatcher<MavenProjectsTree.Listener> myProjectsTreeDispatcher =
EventDispatcher.create(MavenProjectsTree.Listener.class);
private final List<Listener> myManagerListeners = ContainerUtil.createLockFreeCopyOnWriteList();
private ModificationTracker myModificationTracker;
private MavenWorkspaceSettings myWorkspaceSettings;
public static MavenProjectsManager getInstance(Project p) {
return p.getComponent(MavenProjectsManager.class);
}
public MavenProjectsManager(Project project) {
super(project);
myEmbeddersManager = new MavenEmbeddersManager(myProject);
myModificationTracker = new MavenModificationTracker(this);
}
public MavenProjectsManagerState getState() {
if (isInitialized()) {
applyTreeToState();
}
return myState;
}
public void loadState(MavenProjectsManagerState state) {
myState = state;
if (isInitialized()) {
applyStateToTree();
scheduleUpdateAllProjects(false);
}
}
public ModificationTracker getModificationTracker() {
return myModificationTracker;
}
public MavenGeneralSettings getGeneralSettings() {
return getWorkspaceSettings().generalSettings;
}
public MavenImportingSettings getImportingSettings() {
return getWorkspaceSettings().importingSettings;
}
private MavenWorkspaceSettings getWorkspaceSettings() {
if (myWorkspaceSettings == null) {
myWorkspaceSettings = MavenWorkspaceSettingsComponent.getInstance(myProject).getSettings();
}
return myWorkspaceSettings;
}
public File getLocalRepository() {
return getGeneralSettings().getEffectiveLocalRepository();
}
@Override
public void initComponent() {
if (!isNormalProject()) return;
StartupManagerEx startupManager = StartupManagerEx.getInstanceEx(myProject);
startupManager.registerStartupActivity(new Runnable() {
public void run() {
boolean wasMavenized = !myState.originalFiles.isEmpty();
if (!wasMavenized) return;
initMavenized();
}
});
startupManager.registerPostStartupActivity(new Runnable() {
@Override
public void run() {
if (!isMavenizedProject()) {
showNotificationOrphanMavenProject(myProject);
}
CompilerManager.getInstance(myProject).addBeforeTask(new CompileTask() {
@Override
public boolean execute(CompileContext context) {
AccessToken token = ReadAction.start();
try {
new MavenResourceCompilerConfigurationGenerator(myProject, myProjectsTree).generateBuildConfiguration(context.isRebuild());
}
finally {
token.finish();
}
return true;
}
});
}
});
}
private void showNotificationOrphanMavenProject(final Project project) {
final NotificationSettings notificationSettings = NotificationsConfigurationImpl.getSettings(NON_MANAGED_POM_NOTIFICATION_GROUP_ID);
if (!notificationSettings.isShouldLog() && notificationSettings.getDisplayType().equals(NotificationDisplayType.NONE)) {
return;
}
File baseDir = VfsUtilCore.virtualToIoFile(project.getBaseDir());
File pomXml = new File(baseDir, "pom.xml");
if (pomXml.exists()) {
final VirtualFile file = VfsUtil.findFileByIoFile(pomXml, true);
if (file == null) return;
showBalloon(
ProjectBundle.message("maven.orphan.notification.title"),
ProjectBundle.message("maven.orphan.notification.msg", file.getPresentableUrl()),
NON_MANAGED_POM_NOTIFICATION_GROUP, NotificationType.INFORMATION, new NotificationListener.Adapter() {
@Override
protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) {
if ("#add".equals(e.getDescription())) {
addManagedFilesOrUnignore(ContainerUtil.list(file));
notification.expire();
}
else if ("#disable".equals(e.getDescription())) {
final int result = Messages.showYesNoDialog(
myProject,
"Notification will be disabled for all projects.\n\n" +
"Settings | Appearance & Behavior | Notifications | " +
NON_MANAGED_POM_NOTIFICATION_GROUP_ID +
"\ncan be used to configure the notification.",
"Non-Managed Maven Project Detection",
"Disable Notification", CommonBundle.getCancelButtonText(), Messages.getWarningIcon());
if (result == Messages.YES) {
NotificationsConfigurationImpl.getInstanceImpl().changeSettings(
NON_MANAGED_POM_NOTIFICATION_GROUP_ID, NotificationDisplayType.NONE, false, false);
notification.expire();
}
else {
notification.hideBalloon();
}
}
}
}
);
}
}
public void showBalloon(@NotNull final String title,
@NotNull final String message,
@NotNull final NotificationGroup group,
@NotNull final NotificationType type,
@Nullable final NotificationListener listener) {
AppUIUtil.invokeLaterIfProjectAlive(myProject, new Runnable() {
@Override
public void run() {
group.createNotification(title, message, type, listener).notify(myProject);
}
});
}
private void initMavenized() {
doInit(false);
}
private void initNew(List<VirtualFile> files, MavenExplicitProfiles explicitProfiles) {
myState.originalFiles = MavenUtil.collectPaths(files);
getWorkspaceSettings().setEnabledProfiles(explicitProfiles.getEnabledProfiles());
getWorkspaceSettings().setDisabledProfiles(explicitProfiles.getDisabledProfiles());
doInit(true);
}
@TestOnly
public void initForTests() {
doInit(false);
}
private void doInit(final boolean isNew) {
synchronized (isInitialized) {
if (isInitialized.getAndSet(true)) return;
initProjectsTree(!isNew);
initWorkers();
listenForSettingsChanges();
listenForProjectsTreeChanges();
MavenUtil.runWhenInitialized(myProject, new DumbAwareRunnable() {
public void run() {
if (!isUnitTestMode()) {
fireActivated();
listenForExternalChanges();
}
scheduleUpdateAllProjects(isNew);
}
});
}
}
private void initProjectsTree(boolean tryToLoadExisting) {
if (tryToLoadExisting) {
File file = getProjectsTreeFile();
try {
if (file.exists()) {
myProjectsTree = MavenProjectsTree.read(file);
}
}
catch (IOException e) {
MavenLog.LOG.info(e);
}
}
if (myProjectsTree == null) myProjectsTree = new MavenProjectsTree();
applyStateToTree();
myProjectsTree.addListener(myProjectsTreeDispatcher.getMulticaster());
}
private void applyTreeToState() {
myState.originalFiles = myProjectsTree.getManagedFilesPaths();
myState.ignoredFiles = new THashSet<String>(myProjectsTree.getIgnoredFilesPaths());
myState.ignoredPathMasks = myProjectsTree.getIgnoredFilesPatterns();
}
private void applyStateToTree() {
MavenWorkspaceSettings settings = getWorkspaceSettings();
MavenExplicitProfiles explicitProfiles = new MavenExplicitProfiles(settings.enabledProfiles, settings.disabledProfiles);
myProjectsTree.resetManagedFilesPathsAndProfiles(myState.originalFiles, explicitProfiles);
myProjectsTree.setIgnoredFilesPaths(new ArrayList<String>(myState.ignoredFiles));
myProjectsTree.setIgnoredFilesPatterns(myState.ignoredPathMasks);
}
public void save() {
if (myProjectsTree != null) {
try {
myProjectsTree.save(getProjectsTreeFile());
}
catch (IOException e) {
MavenLog.LOG.info(e);
}
}
}
private File getProjectsTreeFile() {
return new File(getProjectsTreesDir(), myProject.getLocationHash() + "/tree.dat");
}
private static File getProjectsTreesDir() {
return MavenUtil.getPluginSystemDir("Projects");
}
private void initWorkers() {
myReadingProcessor = new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.reading"), false, myEmbeddersManager);
myResolvingProcessor = new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.resolving"), true, myEmbeddersManager);
myPluginsResolvingProcessor =
new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.downloading.plugins"), true, myEmbeddersManager);
myFoldersResolvingProcessor =
new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.updating.folders"), true, myEmbeddersManager);
myArtifactsDownloadingProcessor =
new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.downloading"), true, myEmbeddersManager);
myPostProcessor = new MavenProjectsProcessor(myProject, ProjectBundle.message("maven.post.processing"), true, myEmbeddersManager);
myWatcher =
new MavenProjectsManagerWatcher(myProject, this, myProjectsTree, getGeneralSettings(), myReadingProcessor, myEmbeddersManager);
myImportingQueue = new MavenMergingUpdateQueue(getComponentName() + ": Importing queue", IMPORT_DELAY, !isUnitTestMode(), myProject);
myImportingQueue.setPassThrough(false);
myImportingQueue.makeUserAware(myProject);
myImportingQueue.makeDumbAware(myProject);
myImportingQueue.makeModalAware(myProject);
}
private void listenForSettingsChanges() {
getImportingSettings().addListener(new MavenImportingSettings.Listener() {
public void autoImportChanged() {
if (myProject.isDisposed()) return;
if (getImportingSettings().isImportAutomatically()) {
scheduleImportAndResolve();
}
}
public void createModuleGroupsChanged() {
scheduleImportSettings(true);
}
public void createModuleForAggregatorsChanged() {
scheduleImportSettings();
}
});
}
private void listenForProjectsTreeChanges() {
myProjectsTree.addListener(new MavenProjectsTree.ListenerAdapter() {
@Override
public void projectsIgnoredStateChanged(List<MavenProject> ignored, List<MavenProject> unignored, boolean fromImport) {
if (!fromImport) scheduleImport();
}
@Override
public void projectsUpdated(List<Pair<MavenProject, MavenProjectChanges>> updated, List<MavenProject> deleted) {
myEmbeddersManager.clearCaches();
unscheduleAllTasks(deleted);
List<MavenProject> updatedProjects = MavenUtil.collectFirsts(updated);
// import only updated projects and dependents of them (we need to update faced-deps, packaging etc);
List<Pair<MavenProject, MavenProjectChanges>> toImport = new ArrayList<Pair<MavenProject, MavenProjectChanges>>(updated);
for (MavenProject eachDependent : myProjectsTree.getDependentProjects(updatedProjects)) {
toImport.add(Pair.create(eachDependent, MavenProjectChanges.DEPENDENCIES));
}
// resolve updated, theirs dependents, and dependents of deleted
Set<MavenProject> toResolve = new THashSet<MavenProject>(updatedProjects);
toResolve.addAll(myProjectsTree.getDependentProjects(ContainerUtil.concat(updatedProjects, deleted)));
// do not try to resolve projects with syntactic errors
Iterator<MavenProject> it = toResolve.iterator();
while (it.hasNext()) {
MavenProject each = it.next();
if (each.hasReadingProblems()) it.remove();
}
if (haveChanges(toImport) || !deleted.isEmpty()) {
scheduleForNextImport(toImport);
}
if (!deleted.isEmpty() && !hasScheduledProjects()) {
MavenProject project = ObjectUtils.chooseNotNull(ContainerUtil.getFirstItem(toResolve),
ContainerUtil.getFirstItem(getNonIgnoredProjects()));
if (project != null) {
scheduleForNextImport(Pair.create(project, MavenProjectChanges.ALL));
scheduleForNextResolve(ContainerUtil.list(project));
}
}
scheduleForNextResolve(toResolve);
fireProjectScheduled();
}
private boolean haveChanges(List<Pair<MavenProject, MavenProjectChanges>> projectsWithChanges) {
for (MavenProjectChanges each : MavenUtil.collectSeconds(projectsWithChanges)) {
if (each.hasChanges()) return true;
}
return false;
}
@Override
public void projectResolved(Pair<MavenProject, MavenProjectChanges> projectWithChanges,
@Nullable NativeMavenProjectHolder nativeMavenProject) {
if (nativeMavenProject != null) {
if (shouldScheduleProject(projectWithChanges)) {
scheduleForNextImport(projectWithChanges);
MavenImportingSettings importingSettings;
AccessToken token = ReadAction.start();
try {
if (myProject.isDisposed()) return;
importingSettings = getImportingSettings();
}
finally {
token.finish();
}
scheduleArtifactsDownloading(Collections.singleton(projectWithChanges.first),
null,
importingSettings.isDownloadSourcesAutomatically(),
importingSettings.isDownloadDocsAutomatically(),
null);
}
if (!projectWithChanges.first.hasReadingProblems() && projectWithChanges.first.hasUnresolvedPlugins()) {
schedulePluginsResolve(projectWithChanges.first, nativeMavenProject);
}
}
}
@Override
public void foldersResolved(Pair<MavenProject, MavenProjectChanges> projectWithChanges) {
if (shouldScheduleProject(projectWithChanges)) {
scheduleForNextImport(projectWithChanges);
}
}
private boolean shouldScheduleProject(Pair<MavenProject, MavenProjectChanges> projectWithChanges) {
return !projectWithChanges.first.hasReadingProblems() && projectWithChanges.second.hasChanges();
}
});
}
public void listenForExternalChanges() {
myWatcher.start();
}
@Override
public void projectClosed() {
synchronized (isInitialized) {
if (!isInitialized.getAndSet(false)) return;
Disposer.dispose(myImportingQueue);
myWatcher.stop();
myReadingProcessor.stop();
myResolvingProcessor.stop();
myPluginsResolvingProcessor.stop();
myFoldersResolvingProcessor.stop();
myArtifactsDownloadingProcessor.stop();
myPostProcessor.stop();
if (isUnitTestMode()) {
FileUtil.delete(getProjectsTreesDir());
}
}
}
public MavenEmbeddersManager getEmbeddersManager() {
return myEmbeddersManager;
}
private boolean isInitialized() {
return isInitialized.get();
}
public boolean isMavenizedProject() {
return isInitialized();
}
public boolean isMavenizedModule(final Module m) {
AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock();
try {
return !m.isDisposed() && "true".equals(m.getOptionValue(getMavenizedModuleOptionName()));
}
finally {
accessToken.finish();
}
}
public void setMavenizedModules(Collection<Module> modules, boolean mavenized) {
ApplicationManager.getApplication().assertWriteAccessAllowed();
for (Module m : modules) {
if (m.isDisposed()) continue;
if (mavenized) {
m.setOption(getMavenizedModuleOptionName(), "true");
// clear external system API options
// see com.intellij.openapi.externalSystem.service.project.manage.ModuleDataService#setModuleOptions
m.clearOption(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
m.clearOption(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
m.clearOption(ExternalSystemConstants.ROOT_PROJECT_PATH_KEY);
m.clearOption(ExternalSystemConstants.EXTERNAL_SYSTEM_MODULE_GROUP_KEY);
m.clearOption(ExternalSystemConstants.EXTERNAL_SYSTEM_MODULE_VERSION_KEY);
}
else {
m.clearOption(getMavenizedModuleOptionName());
}
}
}
private static String getMavenizedModuleOptionName() {
return "org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule";
}
@TestOnly
public void resetManagedFilesAndProfilesInTests(List<VirtualFile> files, MavenExplicitProfiles profiles) {
myWatcher.resetManagedFilesAndProfilesInTests(files, profiles);
}
public void addManagedFilesWithProfiles(final List<VirtualFile> files, MavenExplicitProfiles profiles) {
if (!isInitialized()) {
initNew(files, profiles);
}
else {
myWatcher.addManagedFilesWithProfiles(files, profiles);
}
MavenUtil.invokeLater(myProject, new Runnable() {
@Override
public void run() {
if (myProject == null || !myProject.isDefault() && !myProject.isDisposed()) {
for (Notification notification : EventLog.getLogModel(myProject).getNotifications()) {
if (NON_MANAGED_POM_NOTIFICATION_GROUP_ID.equals(notification.getGroupId())) {
for (VirtualFile file : files) {
if (StringUtil.startsWith(notification.getContent(), file.getPresentableUrl())) {
notification.expire();
}
}
}
}
}
}
});
}
public void addManagedFiles(@NotNull List<VirtualFile> files) {
addManagedFilesWithProfiles(files, MavenExplicitProfiles.NONE);
}
public void addManagedFilesOrUnignore(@NotNull List<VirtualFile> files) {
removeIgnoredFilesPaths(MavenUtil.collectPaths(files));
addManagedFiles(files);
}
public void removeManagedFiles(@NotNull List<VirtualFile> files) {
myWatcher.removeManagedFiles(files);
}
public boolean isManagedFile(@NotNull VirtualFile f) {
if (!isInitialized()) return false;
return myProjectsTree.isManagedFile(f);
}
@NotNull
public MavenExplicitProfiles getExplicitProfiles() {
if (!isInitialized()) return MavenExplicitProfiles.NONE;
return myProjectsTree.getExplicitProfiles();
}
public void setExplicitProfiles(@NotNull MavenExplicitProfiles profiles) {
myWatcher.setExplicitProfiles(profiles);
}
@NotNull
public Collection<String> getAvailableProfiles() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getAvailableProfiles();
}
@NotNull
public Collection<Pair<String, MavenProfileKind>> getProfilesWithStates() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getProfilesWithStates();
}
public boolean hasProjects() {
if (!isInitialized()) return false;
return myProjectsTree.hasProjects();
}
@NotNull
public List<MavenProject> getProjects() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getProjects();
}
@NotNull
public List<MavenProject> getRootProjects() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getRootProjects();
}
@NotNull
public List<MavenProject> getNonIgnoredProjects() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getNonIgnoredProjects();
}
@NotNull
public List<VirtualFile> getProjectsFiles() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getProjectsFiles();
}
@Nullable
public MavenProject findProject(@NotNull VirtualFile f) {
if (!isInitialized()) return null;
return myProjectsTree.findProject(f);
}
@Nullable
public MavenProject findProject(@NotNull MavenId id) {
if (!isInitialized()) return null;
return myProjectsTree.findProject(id);
}
@Nullable
public MavenProject findProject(@NotNull MavenArtifact artifact) {
if (!isInitialized()) return null;
return myProjectsTree.findProject(artifact);
}
@Nullable
public MavenProject findProject(@NotNull Module module) {
VirtualFile f = findPomFile(module, new MavenModelsProvider() {
public Module[] getModules() {
throw new UnsupportedOperationException();
}
public VirtualFile[] getContentRoots(Module module) {
return ModuleRootManager.getInstance(module).getContentRoots();
}
});
return f == null ? null : findProject(f);
}
@Nullable
public Module findModule(@NotNull MavenProject project) {
if (!isInitialized()) return null;
return ProjectRootManager.getInstance(myProject).getFileIndex().getModuleForFile(project.getFile());
}
@NotNull
public Collection<MavenProject> findInheritors(@Nullable MavenProject parent) {
if (parent == null || !isInitialized()) return Collections.emptyList();
return myProjectsTree.findInheritors(parent);
}
@Nullable
public MavenProject findContainingProject(@NotNull VirtualFile file) {
if (!isInitialized()) return null;
Module module = ProjectRootManager.getInstance(myProject).getFileIndex().getModuleForFile(file);
return module == null ? null : findProject(module);
}
@Nullable
private static VirtualFile findPomFile(@NotNull Module module, @NotNull MavenModelsProvider modelsProvider) {
for (VirtualFile root : modelsProvider.getContentRoots(module)) {
final VirtualFile virtualFile = root.findChild(MavenConstants.POM_XML);
if (virtualFile != null) {
return virtualFile;
}
}
return null;
}
@Nullable
public MavenProject findAggregator(@NotNull MavenProject mavenProject) {
if (!isInitialized()) return null;
return myProjectsTree.findAggregator(mavenProject);
}
@Nullable
public MavenProject findRootProject(@NotNull MavenProject mavenProject) {
if (!isInitialized()) return null;
return myProjectsTree.findRootProject(mavenProject);
}
@NotNull
public List<MavenProject> getModules(@NotNull MavenProject aggregator) {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getModules(aggregator);
}
@NotNull
public List<String> getIgnoredFilesPaths() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getIgnoredFilesPaths();
}
public void setIgnoredFilesPaths(@NotNull List<String> paths) {
if (!isInitialized()) return;
myProjectsTree.setIgnoredFilesPaths(paths);
}
public void removeIgnoredFilesPaths(final Collection<String> paths) {
if (!isInitialized()) return;
myProjectsTree.removeIgnoredFilesPaths(paths);
}
public boolean getIgnoredState(@NotNull MavenProject project) {
if (!isInitialized()) return false;
return myProjectsTree.getIgnoredState(project);
}
public void setIgnoredState(@NotNull List<MavenProject> projects, boolean ignored) {
if (!isInitialized()) return;
myProjectsTree.setIgnoredState(projects, ignored);
}
@NotNull
public List<String> getIgnoredFilesPatterns() {
if (!isInitialized()) return Collections.emptyList();
return myProjectsTree.getIgnoredFilesPatterns();
}
public void setIgnoredFilesPatterns(@NotNull List<String> patterns) {
if (!isInitialized()) return;
myProjectsTree.setIgnoredFilesPatterns(patterns);
}
public boolean isIgnored(@NotNull MavenProject project) {
if (!isInitialized()) return false;
return myProjectsTree.isIgnored(project);
}
public Set<MavenRemoteRepository> getRemoteRepositories() {
Set<MavenRemoteRepository> result = new THashSet<MavenRemoteRepository>();
for (MavenProject each : getProjects()) {
for (MavenRemoteRepository eachRepository : each.getRemoteRepositories()) {
result.add(eachRepository);
}
}
return result;
}
@TestOnly
public MavenProjectsTree getProjectsTreeForTests() {
return myProjectsTree;
}
private void scheduleUpdateAllProjects(boolean forceImportAndResolve) {
doScheduleUpdateProjects(null, false, forceImportAndResolve);
}
public AsyncPromise<Void> forceUpdateProjects(@NotNull Collection<MavenProject> projects) {
return doScheduleUpdateProjects(projects, true, true);
}
public void forceUpdateAllProjectsOrFindAllAvailablePomFiles() {
if (!isMavenizedProject()) {
addManagedFiles(collectAllAvailablePomFiles());
}
doScheduleUpdateProjects(null, true, true);
}
private AsyncPromise<Void> doScheduleUpdateProjects(final Collection<MavenProject> projects,
final boolean forceUpdate,
final boolean forceImportAndResolve) {
final AsyncPromise<Void> promise = new AsyncPromise<Void>();
MavenUtil.runWhenInitialized(myProject, new DumbAwareRunnable() {
public void run() {
if (projects == null) {
myWatcher.scheduleUpdateAll(forceUpdate, forceImportAndResolve).processed(promise);
}
else {
myWatcher.scheduleUpdate(MavenUtil.collectFiles(projects),
Collections.<VirtualFile>emptyList(),
forceUpdate,
forceImportAndResolve).processed(promise);
}
}
});
return promise;
}
/**
* Returned {@link Promise} instance isn't guarantied to be marked as rejected in all cases where importing wasn't performed (e.g.
* if project is closed)
*/
public Promise<List<Module>> scheduleImportAndResolve() {
AsyncPromise<List<Module>> promise = scheduleResolve();// scheduleImport will be called after the scheduleResolve process has finished
fireImportAndResolveScheduled();
return promise;
}
private AsyncPromise<List<Module>> scheduleResolve() {
final AsyncPromise<List<Module>> result = new AsyncPromise<List<Module>>();
runWhenFullyOpen(new Runnable() {
public void run() {
LinkedHashSet<MavenProject> toResolve;
synchronized (myImportingDataLock) {
toResolve = new LinkedHashSet<MavenProject>(myProjectsToResolve);
myProjectsToResolve.clear();
}
if(toResolve.isEmpty()) return;
final ResolveContext context = new ResolveContext();
Runnable onCompletion = new Runnable() {
@Override
public void run() {
if (hasScheduledProjects()) {
scheduleImport().processed(result);
}
else {
result.setResult(Collections.<Module>emptyList());
}
}
};
final boolean useSinglePomResolver = Boolean.getBoolean("idea.maven.use.single.pom.resolver");
if (useSinglePomResolver) {
Iterator<MavenProject> it = toResolve.iterator();
while (it.hasNext()) {
MavenProject each = it.next();
myResolvingProcessor.scheduleTask(new MavenProjectsProcessorResolvingTask(
Collections.singleton(each), myProjectsTree, getGeneralSettings(), it.hasNext() ? null : onCompletion, context));
}
}
else {
myResolvingProcessor.scheduleTask(
new MavenProjectsProcessorResolvingTask(toResolve, myProjectsTree, getGeneralSettings(), onCompletion, context));
}
}
});
return result;
}
public void evaluateEffectivePom(@NotNull final MavenProject mavenProject, @NotNull final NullableConsumer<String> consumer) {
runWhenFullyOpen(new Runnable() {
@Override
public void run() {
myResolvingProcessor.scheduleTask(new MavenProjectsProcessorTask() {
@Override
public void perform(Project project,
MavenEmbeddersManager embeddersManager,
MavenConsole console,
MavenProgressIndicator indicator)
throws MavenProcessCanceledException {
indicator.setText("Evaluating effective POM");
myProjectsTree.executeWithEmbedder(mavenProject,
getEmbeddersManager(),
MavenEmbeddersManager.FOR_DEPENDENCIES_RESOLVE,
console,
indicator,
new MavenProjectsTree.EmbedderTask() {
@Override
public void run(MavenEmbedderWrapper embedder) throws MavenProcessCanceledException {
try {
MavenExplicitProfiles profiles = mavenProject.getActivatedProfilesIds();
String res =
embedder.evaluateEffectivePom(mavenProject.getFile(), profiles.getEnabledProfiles(),
profiles.getDisabledProfiles());
consumer.consume(res);
}
catch (UnsupportedOperationException e) {
consumer.consume(null); // null means UnsupportedOperationException
}
}
});
}
});
}
});
}
@TestOnly
public void scheduleResolveInTests(Collection<MavenProject> projects) {
scheduleForNextResolve(projects);
scheduleResolve();
}
@TestOnly
public void scheduleResolveAllInTests() {
scheduleResolveInTests(getProjects());
}
public void scheduleFoldersResolve(final Collection<MavenProject> projects) {
runWhenFullyOpen(new Runnable() {
public void run() {
Iterator<MavenProject> it = projects.iterator();
while (it.hasNext()) {
MavenProject each = it.next();
Runnable onCompletion = it.hasNext() ? null : new Runnable() {
@Override
public void run() {
if (hasScheduledProjects()) scheduleImport();
}
};
myFoldersResolvingProcessor.scheduleTask(
new MavenProjectsProcessorFoldersResolvingTask(each, getImportingSettings(), myProjectsTree, onCompletion));
}
}
});
}
public void scheduleFoldersResolveForAllProjects() {
scheduleFoldersResolve(getProjects());
}
private void schedulePluginsResolve(final MavenProject project, final NativeMavenProjectHolder nativeMavenProject) {
runWhenFullyOpen(new Runnable() {
public void run() {
myPluginsResolvingProcessor
.scheduleTask(new MavenProjectsProcessorPluginsResolvingTask(project, nativeMavenProject, myProjectsTree));
}
});
}
public void scheduleArtifactsDownloading(final Collection<MavenProject> projects,
@Nullable final Collection<MavenArtifact> artifacts,
final boolean sources, final boolean docs,
@Nullable final AsyncResult<MavenArtifactDownloader.DownloadResult> result) {
if (!sources && !docs) return;
runWhenFullyOpen(new Runnable() {
public void run() {
myArtifactsDownloadingProcessor
.scheduleTask(new MavenProjectsProcessorArtifactsDownloadingTask(projects, artifacts, myProjectsTree, sources, docs, result));
}
});
}
private void scheduleImportSettings() {
scheduleImportSettings(false);
}
private void scheduleImportSettings(boolean importModuleGroupsRequired) {
synchronized (myImportingDataLock) {
myImportModuleGroupsRequired = importModuleGroupsRequired;
}
scheduleImport();
}
private Promise<List<Module>> scheduleImport() {
final AsyncPromise<List<Module>> result = new AsyncPromise<List<Module>>();
runWhenFullyOpen(new Runnable() {
public void run() {
myImportingQueue.queue(new Update(MavenProjectsManager.this) {
public void run() {
result.setResult(importProjects());
}
});
}
});
return result;
}
@TestOnly
public void scheduleImportInTests(List<VirtualFile> projectFiles) {
List<Pair<MavenProject, MavenProjectChanges>> toImport = new ArrayList<Pair<MavenProject, MavenProjectChanges>>();
for (VirtualFile each : projectFiles) {
MavenProject project = findProject(each);
if (project != null) {
toImport.add(Pair.create(project, MavenProjectChanges.ALL));
}
}
scheduleForNextImport(toImport);
scheduleImport();
}
private void scheduleForNextImport(Pair<MavenProject, MavenProjectChanges> projectWithChanges) {
scheduleForNextImport(Collections.singletonList(projectWithChanges));
}
private void scheduleForNextImport(Collection<Pair<MavenProject, MavenProjectChanges>> projectsWithChanges) {
synchronized (myImportingDataLock) {
for (Pair<MavenProject, MavenProjectChanges> each : projectsWithChanges) {
MavenProjectChanges changes = each.second.mergedWith(myProjectsToImport.get(each.first));
myProjectsToImport.put(each.first, changes);
}
}
}
private void scheduleForNextResolve(Collection<MavenProject> projects) {
synchronized (myImportingDataLock) {
myProjectsToResolve.addAll(projects);
}
}
public boolean hasScheduledProjects() {
if (!isInitialized()) return false;
synchronized (myImportingDataLock) {
return !myProjectsToImport.isEmpty() || !myProjectsToResolve.isEmpty();
}
}
@TestOnly
public boolean hasScheduledImportsInTests() {
if (!isInitialized()) return false;
return !myImportingQueue.isEmpty();
}
@TestOnly
public void performScheduledImportInTests() {
if (!isInitialized()) return;
runWhenFullyOpen(new Runnable() {
public void run() {
myImportingQueue.flush();
}
});
}
private void runWhenFullyOpen(final Runnable runnable) {
if (!isInitialized()) return; // may be called from scheduleImport after project started closing and before it is closed.
if (isNoBackgroundMode()) {
runnable.run();
return;
}
final Ref<Runnable> wrapper = new Ref<Runnable>();
wrapper.set(new Runnable() {
public void run() {
if (!StartupManagerEx.getInstanceEx(myProject).postStartupActivityPassed()) {
myInitializationAlarm.addRequest(new Runnable() { // should not remove previously schedules tasks
public void run() {
wrapper.get().run();
}
}, 1000);
return;
}
runnable.run();
}
});
MavenUtil.runWhenInitialized(myProject, wrapper.get());
}
private void schedulePostImportTasks(List<MavenProjectsProcessorTask> postTasks) {
for (MavenProjectsProcessorTask each : postTasks) {
myPostProcessor.scheduleTask(each);
}
}
private void unscheduleAllTasks(List<MavenProject> projects) {
for (MavenProject each : projects) {
MavenProjectsProcessorEmptyTask dummyTask = new MavenProjectsProcessorEmptyTask(each);
synchronized (myImportingDataLock) {
myProjectsToImport.remove(each);
myProjectsToResolve.remove(each);
}
myResolvingProcessor.removeTask(dummyTask);
myPluginsResolvingProcessor.removeTask(dummyTask);
myFoldersResolvingProcessor.removeTask(dummyTask);
myPostProcessor.removeTask(dummyTask);
}
}
@TestOnly
public void unscheduleAllTasksInTests() {
unscheduleAllTasks(getProjects());
}
public void waitForReadingCompletion() {
waitForTasksCompletion(null);
}
public void waitForResolvingCompletion() {
waitForTasksCompletion(myResolvingProcessor);
}
public void waitForFoldersResolvingCompletion() {
waitForTasksCompletion(myFoldersResolvingProcessor);
}
public void waitForPluginsResolvingCompletion() {
waitForTasksCompletion(myPluginsResolvingProcessor);
}
public void waitForArtifactsDownloadingCompletion() {
waitForTasksCompletion(myArtifactsDownloadingProcessor);
}
public void waitForPostImportTasksCompletion() {
myPostProcessor.waitForCompletion();
}
private void waitForTasksCompletion(MavenProjectsProcessor processor) {
FileDocumentManager.getInstance().saveAllDocuments();
myReadingProcessor.waitForCompletion();
if (processor != null) processor.waitForCompletion();
}
public void updateProjectTargetFolders() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
if (myProject.isDisposed()) return;
MavenFoldersImporter.updateProjectFolders(myProject, true);
VirtualFileManager.getInstance().asyncRefresh(null);
}
});
}
public List<Module> importProjects() {
return importProjects(new IdeModifiableModelsProviderImpl(myProject));
}
public List<Module> importProjects(final IdeModifiableModelsProvider modelsProvider) {
final Map<MavenProject, MavenProjectChanges> projectsToImportWithChanges;
final boolean importModuleGroupsRequired;
synchronized (myImportingDataLock) {
projectsToImportWithChanges = new LinkedHashMap<MavenProject, MavenProjectChanges>(myProjectsToImport);
myProjectsToImport.clear();
importModuleGroupsRequired = myImportModuleGroupsRequired;
myImportModuleGroupsRequired = false;
}
final Ref<MavenProjectImporter> importer = new Ref<MavenProjectImporter>();
final Ref<List<MavenProjectsProcessorTask>> postTasks = new Ref<List<MavenProjectsProcessorTask>>();
final Runnable r = new Runnable() {
public void run() {
MavenProjectImporter projectImporter = new MavenProjectImporter(myProject,
myProjectsTree,
getFileToModuleMapping(new MavenModelsProvider() {
@Override
public Module[] getModules() {
return modelsProvider.getModules();
}
@Override
public VirtualFile[] getContentRoots(Module module) {
return modelsProvider.getContentRoots(module);
}
}),
projectsToImportWithChanges,
importModuleGroupsRequired,
modelsProvider,
getImportingSettings());
importer.set(projectImporter);
postTasks.set(projectImporter.importProject());
}
};
// called from wizard or ui
if (ApplicationManager.getApplication().isDispatchThread()) {
r.run();
}
else {
MavenUtil.runInBackground(myProject, ProjectBundle.message("maven.project.importing"), false, new MavenTask() {
public void run(MavenProgressIndicator indicator) throws MavenProcessCanceledException {
r.run();
}
}).waitFor();
}
VirtualFileManager fm = VirtualFileManager.getInstance();
if (isNormalProject()) {
fm.asyncRefresh(null);
}
else {
fm.syncRefresh();
}
if (postTasks.get() != null /*may be null if importing is cancelled*/) {
schedulePostImportTasks(postTasks.get());
}
// do not block user too often
myImportingQueue.restartTimer();
MavenProjectImporter projectImporter = importer.get();
if (projectImporter == null) return Collections.emptyList();
return projectImporter.getCreatedModules();
}
private static Map<VirtualFile, Module> getFileToModuleMapping(MavenModelsProvider modelsProvider) {
Map<VirtualFile, Module> result = new THashMap<VirtualFile, Module>();
for (Module each : modelsProvider.getModules()) {
VirtualFile f = findPomFile(each, modelsProvider);
if (f != null) result.put(f, each);
}
return result;
}
private List<VirtualFile> collectAllAvailablePomFiles() {
List<VirtualFile> result = new ArrayList<VirtualFile>(getFileToModuleMapping(new MavenDefaultModelsProvider(myProject)).keySet());
VirtualFile pom = myProject.getBaseDir().findChild(MavenConstants.POM_XML);
if (pom != null) result.add(pom);
return result;
}
public void addManagerListener(Listener listener) {
myManagerListeners.add(listener);
}
public void addProjectsTreeListener(MavenProjectsTree.Listener listener) {
myProjectsTreeDispatcher.addListener(listener);
}
@TestOnly
public void fireActivatedInTests() {
fireActivated();
}
private void fireActivated() {
for (Listener each : myManagerListeners) {
each.activated();
}
}
private void fireProjectScheduled() {
for (Listener each : myManagerListeners) {
each.projectsScheduled();
}
}
private void fireImportAndResolveScheduled() {
for (Listener each : myManagerListeners) {
each.importAndResolveScheduled();
}
}
public interface Listener {
void activated();
void projectsScheduled();
void importAndResolveScheduled();
}
}
| |
package com.fasterxml.jackson.databind.ser;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.introspect.ClassIntrospector;
/**
* Unit tests for checking handling of SerializationConfig.
*/
public class TestConfig
extends BaseMapTest
{
/*
/**********************************************************
/* Helper beans
/**********************************************************
*/
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
@JsonSerialize(typing=JsonSerialize.Typing.STATIC)
final static class Config { }
final static class ConfigNone { }
static class AnnoBean {
public int getX() { return 1; }
@JsonProperty("y")
private int getY() { return 2; }
}
static class Indentable {
public int a = 3;
}
public static class SimpleBean {
public int x = 1;
}
/*
/**********************************************************
/* Main tests
/**********************************************************
*/
final static ObjectMapper MAPPER = new ObjectMapper();
/* Test to verify that we don't overflow number of features; if we
* hit the limit, need to change implementation -- this test just
* gives low-water mark
*/
public void testEnumIndexes()
{
int max = 0;
for (SerializationFeature f : SerializationFeature.values()) {
max = Math.max(max, f.ordinal());
}
if (max >= 31) { // 31 is actually ok; 32 not
fail("Max number of SerializationFeature enums reached: "+max);
}
}
public void testDefaults()
{
SerializationConfig cfg = MAPPER.getSerializationConfig();
// First, defaults:
assertTrue(cfg.isEnabled(MapperFeature.USE_ANNOTATIONS));
assertTrue(cfg.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
assertTrue(cfg.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS));
assertTrue(cfg.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS));
assertFalse(cfg.isEnabled(SerializationFeature.INDENT_OUTPUT));
assertFalse(cfg.isEnabled(MapperFeature.USE_STATIC_TYPING));
// since 1.3:
assertTrue(cfg.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS));
// since 1.4
assertTrue(cfg.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
// since 1.5
assertTrue(cfg.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
}
public void testOverrideIntrospectors()
{
SerializationConfig cfg = MAPPER.getSerializationConfig();
// and finally, ensure we could override introspectors
cfg = cfg.with((ClassIntrospector) null); // no way to verify tho
cfg = cfg.with((AnnotationIntrospector) null);
assertNull(cfg.getAnnotationIntrospector());
}
public void testMisc()
{
ObjectMapper m = new ObjectMapper();
m.setDateFormat(null); // just to execute the code path
assertNotNull(m.getSerializationConfig().toString()); // ditto
}
public void testIndentation() throws Exception
{
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("a", Integer.valueOf(2));
String result = MAPPER.writer().with(SerializationFeature.INDENT_OUTPUT)
.writeValueAsString(map);
// 02-Jun-2009, tatu: not really a clean way but...
String lf = getLF();
assertEquals("{"+lf+" \"a\" : 2"+lf+"}", result);
}
public void testAnnotationsDisabled() throws Exception
{
// first: verify that annotation introspection is enabled by default
assertTrue(MAPPER.isEnabled(MapperFeature.USE_ANNOTATIONS));
Map<String,Object> result = writeAndMap(MAPPER, new AnnoBean());
assertEquals(2, result.size());
ObjectMapper m2 = jsonMapperBuilder()
.configure(MapperFeature.USE_ANNOTATIONS, false)
.build();
result = writeAndMap(m2, new AnnoBean());
assertEquals(1, result.size());
}
/**
* Test for verifying working of [JACKSON-191]
*/
public void testProviderConfig() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
DefaultSerializerProvider prov = (DefaultSerializerProvider) mapper.getSerializerProvider();
assertEquals(0, prov.cachedSerializersCount());
// and then should get one constructed for:
Map<String,Object> result = this.writeAndMap(mapper, new AnnoBean());
assertEquals(2, result.size());
assertEquals(Integer.valueOf(1), result.get("x"));
assertEquals(Integer.valueOf(2), result.get("y"));
/* Note: it is 2 because we'll also get serializer for basic 'int', not
* just AnnoBean
*/
/* 12-Jan-2010, tatus: Actually, probably more, if and when we typing
* aspects are considered (depending on what is cached)
*/
int count = prov.cachedSerializersCount();
if (count < 2) {
fail("Should have at least 2 cached serializers, got "+count);
}
prov.flushCachedSerializers();
assertEquals(0, prov.cachedSerializersCount());
}
// Test for [Issue#12]
public void testIndentWithPassedGenerator() throws Exception
{
Indentable input = new Indentable();
assertEquals("{\"a\":3}", MAPPER.writeValueAsString(input));
String LF = getLF();
String INDENTED = "{"+LF+" \"a\" : 3"+LF+"}";
final ObjectWriter indentWriter = MAPPER.writer().with(SerializationFeature.INDENT_OUTPUT);
assertEquals(INDENTED, indentWriter.writeValueAsString(input));
// [Issue#12]
StringWriter sw = new StringWriter();
JsonGenerator jgen = MAPPER.createGenerator(sw);
indentWriter.writeValue(jgen, input);
jgen.close();
assertEquals(INDENTED, sw.toString());
// and also with ObjectMapper itself
sw = new StringWriter();
ObjectMapper m2 = new ObjectMapper();
m2.enable(SerializationFeature.INDENT_OUTPUT);
jgen = m2.createGenerator(sw);
m2.writeValue(jgen, input);
jgen.close();
assertEquals(INDENTED, sw.toString());
}
public void testNoAccessOverrides() throws Exception
{
ObjectMapper m = jsonMapperBuilder()
.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)
.build();
assertEquals("{\"x\":1}", m.writeValueAsString(new SimpleBean()));
}
public void testDateFormatConfig() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
TimeZone tz1 = TimeZone.getTimeZone("America/Los_Angeles");
TimeZone tz2 = TimeZone.getTimeZone("US/Central");
// sanity checks
assertEquals(tz1, tz1);
assertEquals(tz2, tz2);
if (tz1.equals(tz2)) {
fail();
}
mapper.setTimeZone(tz1);
assertEquals(tz1, mapper.getSerializationConfig().getTimeZone());
assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone());
// also better stick via reader/writer as well
assertEquals(tz1, mapper.writer().getConfig().getTimeZone());
assertEquals(tz1, mapper.reader().getConfig().getTimeZone());
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
f.setTimeZone(tz2);
mapper.setDateFormat(f);
// should not change the timezone tho
assertEquals(tz1, mapper.getSerializationConfig().getTimeZone());
assertEquals(tz1, mapper.getDeserializationConfig().getTimeZone());
assertEquals(tz1, mapper.writer().getConfig().getTimeZone());
assertEquals(tz1, mapper.reader().getConfig().getTimeZone());
}
private final static String getLF() {
return System.getProperty("line.separator");
}
}
| |
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.component.factory.master;
import java.util.LinkedHashMap;
import java.util.Map;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.component.ComponentInfo;
import com.opengamma.component.ComponentRepository;
import com.opengamma.component.factory.AbstractComponentFactory;
import com.opengamma.component.factory.ComponentInfoAttributes;
import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster;
import com.opengamma.master.marketdatasnapshot.impl.DataMarketDataSnapshotMasterResource;
import com.opengamma.master.marketdatasnapshot.impl.InMemorySnapshotMaster;
import com.opengamma.master.marketdatasnapshot.impl.RemoteMarketDataSnapshotMaster;
/**
* Component factory for an in-memory snapshot master.
*/
@BeanDefinition
public class InMemorySnapshotMasterComponentFactory extends AbstractComponentFactory {
/**
* The classifier that the factory should publish under.
*/
@PropertyDefinition(validate = "notNull")
private String _classifier;
/**
* The flag determining whether the component should be published by REST (default true).
*/
@PropertyDefinition
private boolean _publishRest = true;
@Override
public void init(final ComponentRepository repo, final LinkedHashMap<String, String> configuration) {
final MarketDataSnapshotMaster master = new InMemorySnapshotMaster();
final ComponentInfo info = new ComponentInfo(MarketDataSnapshotMaster.class, getClassifier());
info.addAttribute(ComponentInfoAttributes.LEVEL, 1);
if (isPublishRest()) {
info.addAttribute(ComponentInfoAttributes.REMOTE_CLIENT_JAVA, RemoteMarketDataSnapshotMaster.class);
}
info.addAttribute(ComponentInfoAttributes.UNIQUE_ID_SCHEME, InMemorySnapshotMaster.DEFAULT_OID_SCHEME);
repo.registerComponent(info, master);
// publish
if (isPublishRest()) {
repo.getRestComponents().publish(info, new DataMarketDataSnapshotMasterResource(master));
}
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code InMemorySnapshotMasterComponentFactory}.
* @return the meta-bean, not null
*/
public static InMemorySnapshotMasterComponentFactory.Meta meta() {
return InMemorySnapshotMasterComponentFactory.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(InMemorySnapshotMasterComponentFactory.Meta.INSTANCE);
}
@Override
public InMemorySnapshotMasterComponentFactory.Meta metaBean() {
return InMemorySnapshotMasterComponentFactory.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the classifier that the factory should publish under.
* @return the value of the property, not null
*/
public String getClassifier() {
return _classifier;
}
/**
* Sets the classifier that the factory should publish under.
* @param classifier the new value of the property, not null
*/
public void setClassifier(String classifier) {
JodaBeanUtils.notNull(classifier, "classifier");
this._classifier = classifier;
}
/**
* Gets the the {@code classifier} property.
* @return the property, not null
*/
public final Property<String> classifier() {
return metaBean().classifier().createProperty(this);
}
//-----------------------------------------------------------------------
/**
* Gets the flag determining whether the component should be published by REST (default true).
* @return the value of the property
*/
public boolean isPublishRest() {
return _publishRest;
}
/**
* Sets the flag determining whether the component should be published by REST (default true).
* @param publishRest the new value of the property
*/
public void setPublishRest(boolean publishRest) {
this._publishRest = publishRest;
}
/**
* Gets the the {@code publishRest} property.
* @return the property, not null
*/
public final Property<Boolean> publishRest() {
return metaBean().publishRest().createProperty(this);
}
//-----------------------------------------------------------------------
@Override
public InMemorySnapshotMasterComponentFactory clone() {
return JodaBeanUtils.cloneAlways(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
InMemorySnapshotMasterComponentFactory other = (InMemorySnapshotMasterComponentFactory) obj;
return JodaBeanUtils.equal(getClassifier(), other.getClassifier()) &&
(isPublishRest() == other.isPublishRest()) &&
super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = hash * 31 + JodaBeanUtils.hashCode(getClassifier());
hash = hash * 31 + JodaBeanUtils.hashCode(isPublishRest());
return hash ^ super.hashCode();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(96);
buf.append("InMemorySnapshotMasterComponentFactory{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
@Override
protected void toString(StringBuilder buf) {
super.toString(buf);
buf.append("classifier").append('=').append(JodaBeanUtils.toString(getClassifier())).append(',').append(' ');
buf.append("publishRest").append('=').append(JodaBeanUtils.toString(isPublishRest())).append(',').append(' ');
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code InMemorySnapshotMasterComponentFactory}.
*/
public static class Meta extends AbstractComponentFactory.Meta {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code classifier} property.
*/
private final MetaProperty<String> _classifier = DirectMetaProperty.ofReadWrite(
this, "classifier", InMemorySnapshotMasterComponentFactory.class, String.class);
/**
* The meta-property for the {@code publishRest} property.
*/
private final MetaProperty<Boolean> _publishRest = DirectMetaProperty.ofReadWrite(
this, "publishRest", InMemorySnapshotMasterComponentFactory.class, Boolean.TYPE);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, (DirectMetaPropertyMap) super.metaPropertyMap(),
"classifier",
"publishRest");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return _classifier;
case -614707837: // publishRest
return _publishRest;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends InMemorySnapshotMasterComponentFactory> builder() {
return new DirectBeanBuilder<InMemorySnapshotMasterComponentFactory>(new InMemorySnapshotMasterComponentFactory());
}
@Override
public Class<? extends InMemorySnapshotMasterComponentFactory> beanType() {
return InMemorySnapshotMasterComponentFactory.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code classifier} property.
* @return the meta-property, not null
*/
public final MetaProperty<String> classifier() {
return _classifier;
}
/**
* The meta-property for the {@code publishRest} property.
* @return the meta-property, not null
*/
public final MetaProperty<Boolean> publishRest() {
return _publishRest;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return ((InMemorySnapshotMasterComponentFactory) bean).getClassifier();
case -614707837: // publishRest
return ((InMemorySnapshotMasterComponentFactory) bean).isPublishRest();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
((InMemorySnapshotMasterComponentFactory) bean).setClassifier((String) newValue);
return;
case -614707837: // publishRest
((InMemorySnapshotMasterComponentFactory) bean).setPublishRest((Boolean) newValue);
return;
}
super.propertySet(bean, propertyName, newValue, quiet);
}
@Override
protected void validate(Bean bean) {
JodaBeanUtils.notNull(((InMemorySnapshotMasterComponentFactory) bean)._classifier, "classifier");
super.validate(bean);
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common.util;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ListenableActionFuture;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.util.concurrent.AbstractRefCounted;
import org.elasticsearch.tasks.TaskCancelledException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BooleanSupplier;
/**
* A cache of a single object whose refresh process can be cancelled. The cached value is computed lazily on the first retrieval, and
* associated with a key which is used to determine its freshness for subsequent retrievals.
* <p>
* This is useful for things like computing stats over cluster metadata: the first time stats are requested they are computed, but
* subsequent calls re-use the computed value as long as they pertain to the same metadata version. If stats are requested for a different
* metadata version then the cached value is dropped and a new one is computed.
* <p>
* Retrievals happen via the async {@link #get} method. If a retrieval is cancelled (e.g. the channel on which to return the stats is
* closed) then the computation carries on running in case another retrieval for the same key arrives in future. However if all of the
* retrievals for a key are cancelled <i>and</i> a retrieval occurs for a fresher key then the computation itself is cancelled.
* <p>
* Cancellation is based on polling: the {@link #refresh} method checks whether it should abort whenever it is convenient to do so, which in
* turn checks all the pending retrievals to see whether they have been cancelled.
*
* @param <Input> The type of the input to the computation of the cached value.
* @param <Key> The key type. The cached value is associated with a key, and subsequent {@link #get} calls compare keys of the given input
* value to determine whether the cached value is fresh or not. See {@link #isFresh}.
* @param <Value> The type of the cached value.
*/
public abstract class CancellableSingleObjectCache<Input, Key, Value> {
private final AtomicReference<CachedItem> currentCachedItemRef = new AtomicReference<>();
/**
* Compute a new value for the cache.
* <p>
* If an exception is thrown, or passed to the {@code listener}, then it is passed on to all waiting listeners but it is not cached so
* that subsequent retrievals will trigger subsequent calls to this method.
* <p>
* Implementations of this method should poll for cancellation by running {@code ensureNotCancelled} whenever appropriate. The
* computation is cancelled if all of the corresponding retrievals have been cancelled <i>and</i> a retrieval has since happened for a
* fresher key.
*
* @param input The input to this computation, which will be converted to a key and used to determine whether it is
* suitably fresh for future requests too.
* @param ensureNotCancelled A {@link Runnable} which throws a {@link TaskCancelledException} if the result of the computation is no
* longer needed. On cancellation, notifying the {@code listener} is optional.
* @param listener A {@link ActionListener} which should be notified when the computation completes. If the computation fails
* by calling {@link ActionListener#onFailure} then the result is returned to the pending listeners but is not
* cached.
*/
protected abstract void refresh(Input input, Runnable ensureNotCancelled, ActionListener<Value> listener);
/**
* Compute the key for the given input value.
*/
protected abstract Key getKey(Input input);
/**
* Compute whether the {@code currentKey} is fresh enough for a retrieval associated with {@code newKey}.
*
* @param currentKey The key of the current (cached or pending) value.
* @param newKey The key associated with a new retrival.
* @return {@code true} if a value computed for {@code currentKey} is fresh enough to satisfy a retrieval for {@code newKey}.
*/
protected boolean isFresh(Key currentKey, Key newKey) {
return currentKey.equals(newKey);
}
/**
* Start a retrieval for the value associated with the given {@code input}, and pass it to the given {@code listener}.
* <p>
* If a fresh-enough result is available when this method is called then the {@code listener} is notified immediately, on this thread.
* If a fresh-enough result is already being computed then the {@code listener} is captured and will be notified when the result becomes
* available, on the thread on which the refresh completes. If no fresh-enough result is either pending or available then this method
* starts to compute one by calling {@link #refresh} on this thread.
*
* @param input The input to compute the desired value, converted to a {@link Key} to determine if the value that's currently
* cached or pending is fresh enough.
* @param isCancelled Returns {@code true} if the listener no longer requires the value being computed.
* @param listener The listener to notify when the desired value becomes available.
*/
public final void get(Input input, BooleanSupplier isCancelled, ActionListener<Value> listener) {
final Key key = getKey(input);
CachedItem newCachedItem = null;
do {
if (isCancelled.getAsBoolean()) {
listener.onFailure(new TaskCancelledException("task cancelled"));
return;
}
final CachedItem currentCachedItem = currentCachedItemRef.get();
if (currentCachedItem != null && isFresh(currentCachedItem.getKey(), key)) {
final boolean listenerAdded = currentCachedItem.addListener(listener, isCancelled);
if (listenerAdded) {
return;
}
assert currentCachedItem.refCount() == 0 : currentCachedItem.refCount();
assert currentCachedItemRef.get() != currentCachedItem;
// Our item was only just released, possibly cancelled, by another get() with a fresher key. We don't simply retry
// since that would evict the new item. Instead let's see if it was cancelled or whether it completed properly.
if (currentCachedItem.getFuture().isDone()) {
try {
listener.onResponse(currentCachedItem.getFuture().actionGet(0L));
return;
} catch (TaskCancelledException e) {
// previous task was cancelled before completion, therefore we must perform our own one-shot refresh
} catch (Exception e) {
// either the refresh completed exceptionally or the listener threw an exception; call onFailure() either way
listener.onFailure(e);
return;
}
} // else it's just about to be cancelled, so we can just retry knowing that it will be removed very soon
continue;
}
if (newCachedItem == null) {
newCachedItem = new CachedItem(key);
}
if (currentCachedItemRef.compareAndSet(currentCachedItem, newCachedItem)) {
if (currentCachedItem != null) {
currentCachedItem.decRef();
}
startRefresh(input, newCachedItem);
final boolean listenerAdded = newCachedItem.addListener(listener, isCancelled);
assert listenerAdded;
newCachedItem.decRef();
return;
}
// else the CAS failed because we lost a race to a concurrent retrieval; try again from the top since we expect the race winner
// to be fresh enough for us and therefore we can just wait for its result.
} while (true);
}
private void startRefresh(Input input, CachedItem cachedItem) {
try {
refresh(input, cachedItem::ensureNotCancelled, cachedItem.getFuture());
} catch (Exception e) {
cachedItem.getFuture().onFailure(e);
}
}
/**
* An item in the cache, representing a single invocation of {@link #refresh}.
* <p>
* This item is ref-counted so that it can be cancelled if it becomes irrelevant. References are held by:
* <ul>
* <li>Every listener that is waiting for the result, released on cancellation. There's no need to release on completion because
* there's nothing to cancel once the refresh has completed.</li>
* <li>The cache itself, released once this item is no longer the current one in the cache, either because it failed or because a
* fresher computation was started.</li>
* <li>The process that adds the first listener, released once the first listener is added.</li>
* </ul>
*/
private final class CachedItem extends AbstractRefCounted {
private final Key key;
private final ListenableActionFuture<Value> future = new ListenableActionFuture<>();
private final CancellationChecks cancellationChecks = new CancellationChecks();
CachedItem(Key key) {
super("cached item");
this.key = key;
incRef(); // start with a refcount of 2 so we're not closed while adding the first listener
this.future.addListener(new ActionListener<>() {
@Override
public void onResponse(Value value) {
cancellationChecks.clear();
}
@Override
public void onFailure(Exception e) {
cancellationChecks.clear();
// Do not cache this failure
if (currentCachedItemRef.compareAndSet(CachedItem.this, null)) {
// Release reference held by the cache, so that concurrent calls to addListener() fail and retry. Not totally
// necessary, we could also fail those listeners as if they'd been added slightly sooner, but it makes the ref
// counting easier to document.
decRef();
}
}
});
}
Key getKey() {
return key;
}
ListenableActionFuture<Value> getFuture() {
return future;
}
boolean addListener(ActionListener<Value> listener, BooleanSupplier isCancelled) {
if (tryIncRef()) {
if (future.isDone()) {
// No need to bother with ref counting & cancellation any more, just complete the listener.
// We know it wasn't cancelled because there are still references.
ActionListener.completeWith(listener, () -> future.actionGet(0L));
} else {
// Refresh is still pending; it's not cancelled because there are still references.
future.addListener(listener);
final AtomicBoolean released = new AtomicBoolean();
cancellationChecks.add(() -> {
if (released.get() == false && isCancelled.getAsBoolean() && released.compareAndSet(false, true)) {
decRef();
}
});
}
return true;
} else {
return false;
}
}
void ensureNotCancelled() {
cancellationChecks.runAll();
if (refCount() == 0) {
throw new TaskCancelledException("task cancelled");
}
}
@Override
protected void closeInternal() {
// Complete the future (and hence all its listeners) with an exception if it hasn't already been completed.
future.onFailure(new TaskCancelledException("task cancelled"));
}
}
private static final class CancellationChecks {
@Nullable // if cleared
private ArrayList<Runnable> checks = new ArrayList<>();
synchronized void clear() {
checks = null;
}
synchronized void add(Runnable check) {
if (checks != null) {
checks.add(check);
}
}
void runAll() {
// It's ok not to run all the checks so there's no need for a completely synchronized iteration.
final int count;
synchronized (this) {
if (checks == null) {
return;
}
count = checks.size();
}
for (int i = 0; i < count; i++) {
final Runnable cancellationCheck;
synchronized (this) {
if (checks == null) {
return;
}
cancellationCheck = checks.get(i);
}
cancellationCheck.run();
}
}
}
}
| |
package de.ids_mannheim.korap.query.serialize;
import java.util.AbstractMap.SimpleEntry;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Joachim Bingel (bingel@ids-mannheim.de),
* Michael Hanl (hanl@ids-mannheim.de)
* @version 0.3.0
* @date 10/12/2013
* @since 0.1.0
*/
public class QueryUtils {
public static SimpleEntry<String, Integer> checkUnbalancedPars (String q) {
Map<Character, Character> brackets = new HashMap<Character, Character>();
brackets.put('[', ']');
brackets.put('{', '}');
brackets.put('(', ')');
Set<Character> allChars = new HashSet<Character>();
allChars.addAll(brackets.keySet());
allChars.addAll(brackets.values());
int lastOpenBracket = 0;
final Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < q.length(); i++) {
if (!allChars.contains(q.charAt(i)))
continue;
if (brackets.containsKey(q.charAt(i))) {
stack.push(q.charAt(i));
lastOpenBracket = i;
}
else if (stack.empty()
|| (q.charAt(i) != brackets.get(stack.pop()))) {
return new SimpleEntry<String, Integer>(
"Parantheses/brackets unbalanced.", i);
}
}
if (!stack.empty())
return new SimpleEntry<String, Integer>(
"Parantheses/brackets unbalanced.", lastOpenBracket);
return null;
}
public static List<String> parseMorph (String stringTree) {
ArrayList<String> morph = new ArrayList<String>();
return morph;
}
public static String buildCypherQuery (String cypher, String ctypel,
String ctyper, int cl, int cr, int page, int limit) {
// todo: implies that there is only one type allowed!
String sctypel = "", sctyper = "";
switch (ctypel) {
case "C":
sctypel = "chars";
break;
case "T":
sctypel = "tokens";
break;
}
switch (ctyper) {
case "C":
sctyper = "chars";
break;
case "T":
sctyper = "tokens";
break;
}
return new StringBuffer()
.append("<query><cypher><![CDATA[")
.append(cypher)
.append("]]></cypher>")
.append("<wordAliasPrefix>wtok_</wordAliasPrefix>")
.append("<contextColumn>sent</contextColumn>")
.append("<contextIdColumn>sid</contextIdColumn>")
.append("<textColumn>txt</textColumn>")
.append("<startIndex>")
.append(page)
.append("</startIndex>")
.append("<itemsPerPage>")
.append(limit)
.append("</itemsPerPage>")
.append("<context>")
.append("<left>")
.append("<").append(sctypel).append(">")
.append(cl)
.append("</").append(sctypel).append(">")
.append("</left>")
.append("<right>")
.append("<").append(sctyper).append(">")
.append(cr)
.append("</").append(sctyper).append(">")
.append("</right>")
.append("</context>")
.append("</query>")
.toString();
}
public static String buildDotQuery (long sid, String graphdb_id) {
return new StringBuffer()
.append("<query>")
.append("<sentenceId>")
.append(sid)
.append("</sentenceId>")
.append("<gdbId>")
.append(graphdb_id)
.append("</gdbId>")
.append("<hls>")
.append("<hl>")
.append(40857)
.append("</hl>")
.append("<hl>")
.append(40856)
.append("</hl>")
.append("</hls>")
.append("</query>")
.toString();
}
public String buildaggreQuery (String query) {
return new StringBuffer()
.append("<query><cypher><![CDATA[")
.append(query)
.append("]]></cypher>")
.append("<columns>")
.append("<column agg='true' sum='false'>")
.append("<cypherAlias>")
.append("aggBy")
.append("</cypherAlias>")
.append("<displayName>")
.append("Aggregate")
.append("</displayName>")
.append("</column>")
.append("<column agg='fals' sum='true'>")
.append("<cypherAlias>")
.append("cnt")
.append("</cypherAlias>")
.append("<displayName>")
.append("Count")
.append("</displayName>")
.append("</column>")
.append("</columns>")
.append("</query>")
.toString();
}
@Deprecated
public static Map addParameters (Map request, int page, int num,
String cli, String cri, int cls, int crs, boolean cutoff) {
Map ctx = new LinkedHashMap();
List left = new ArrayList();
left.add(cli);
left.add(cls);
List right = new ArrayList();
right.add(cri);
right.add(crs);
ctx.put("left", left);
ctx.put("right", right);
request.put("startPage", page);
request.put("count", num);
request.put("context", ctx);
request.put("cutOff", cutoff);
return request;
}
/**
* Checks if value is a date
*
* @param value
* @return
*/
public static boolean checkDateValidity (String value) {
Pattern p = Pattern.compile("^[0-9]{4}(-([0-9]{2})(-([0-9]{2}))?)?$");
Matcher m = p.matcher(value);
if (!m.find())
return false;
String month = m.group(2);
String day = m.group(4);
if (month != null) {
if (Integer.parseInt(month) > 12) {
return false;
}
else if (day != null) {
if (Integer.parseInt(day) > 31) {
return false;
}
}
}
return true;
}
public static String escapeRegexSpecialChars (String key) {
key.replace("\\", "\\\\");
Pattern p = Pattern
.compile("[.^$|?*+()\\[\\]{}]");
Matcher m = p.matcher(key);
while (m.find()) {
String match = m.group();
key = m.replaceAll("\\\\" + match);
}
return key;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache;
import org.apache.geode.cache.*;
import org.apache.geode.cache.partition.PartitionRegionHelper;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.internal.cache.partitioned.PartitionedRegionObserverAdapter;
import org.apache.geode.internal.cache.partitioned.PartitionedRegionObserverHolder;
import org.apache.geode.test.junit.categories.IntegrationTest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.*;
/**
* This test checks functionality of the PartitionedRegionDatastore on a sinle node.
*
* Created on Dec 23, 2005
*
*
*/
@Category(IntegrationTest.class)
public class PartitionedRegionDataStoreJUnitTest {
static DistributedSystem sys;
static Cache cache;
byte obj[] = new byte[10240];
String regionName = "DataStoreRegion";
@Before
public void setUp() {
Properties dsProps = new Properties();
dsProps.setProperty(MCAST_PORT, "0");
// Connect to a DS and create a Cache.
sys = DistributedSystem.connect(dsProps);
cache = CacheFactory.create(sys);
}
@After
public void tearDown() {
sys.disconnect();
}
@Test
public void testRemoveBrokenNode() throws Exception {
PartitionAttributesFactory paf = new PartitionAttributesFactory();
PartitionAttributes pa = paf.setRedundantCopies(0).setLocalMaxMemory(0).create();
AttributesFactory af = new AttributesFactory();
af.setPartitionAttributes(pa);
RegionAttributes ra = af.create();
PartitionedRegion pr = null;
pr = (PartitionedRegion) cache.createRegion("PR2", ra);
paf.setLocalProperties(null).create();
/* PartitionedRegionDataStore prDS = */ new PartitionedRegionDataStore(pr);
/*
* PartitionedRegionHelper.removeGlobalMetadataForFailedNode(PartitionedRegion.node,
* prDS.partitionedRegion.getRegionIdentifier(), prDS.partitionedRegion.cache);
*/
}
@Test
public void testLocalPut() throws Exception {
PartitionAttributesFactory paf = new PartitionAttributesFactory();
Properties globalProps = new Properties();
globalProps.put(PartitionAttributesFactory.GLOBAL_MAX_BUCKETS_PROPERTY, "100");
PartitionAttributes pa = paf.setRedundantCopies(0).setLocalMaxMemory(100).create();
AttributesFactory af = new AttributesFactory();
af.setPartitionAttributes(pa);
RegionAttributes ra = af.create();
PartitionedRegion pr = null;
pr = (PartitionedRegion) cache.createRegion("PR3", ra);
String key = "User";
String value = "1";
pr.put(key, value);
assertEquals(pr.get(key), value);
}
@Test
public void testChangeCacheLoaderDuringBucketCreation() throws Exception {
final PartitionedRegion pr =
(PartitionedRegion) cache.createRegionFactory(RegionShortcut.PARTITION)
.create("testChangeCacheLoaderDuringBucketCreation");
// Add an observer which will block bucket creation and wait for a loader to be added
final CountDownLatch loaderAdded = new CountDownLatch(1);
final CountDownLatch bucketCreated = new CountDownLatch(1);
PartitionedRegionObserverHolder.setInstance(new PartitionedRegionObserverAdapter() {
@Override
public void beforeAssignBucket(PartitionedRegion partitionedRegion, int bucketId) {
try {
// Indicate that the bucket has been created
bucketCreated.countDown();
// Wait for the loader to be added. if the synchronization
// is correct, this would wait for ever because setting the
// cache loader will wait for this method. So time out after
// 1 second, which should be good enough to cause a failure
// if the synchronization is broken.
loaderAdded.await(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted");
}
}
});
Thread createBuckets = new Thread() {
public void run() {
PartitionRegionHelper.assignBucketsToPartitions(pr);
}
};
createBuckets.start();
CacheLoader loader = new CacheLoader() {
@Override
public void close() {}
@Override
public Object load(LoaderHelper helper) throws CacheLoaderException {
return null;
}
};
bucketCreated.await();
pr.getAttributesMutator().setCacheLoader(loader);
loaderAdded.countDown();
createBuckets.join();
// Assert that all buckets have received the cache loader
for (BucketRegion bucket : pr.getDataStore().getAllLocalBucketRegions()) {
assertEquals(loader, bucket.getCacheLoader());
}
}
/**
* This method checks whether the canAccomodateMoreBytesSafely returns false after reaching the
* localMax memory.
*
*/
@Test
public void testCanAccommodateMoreBytesSafely() throws Exception {
int key = 0;
final int numMBytes = 5;
final PartitionedRegion regionAck = (PartitionedRegion) new RegionFactory()
.setPartitionAttributes(new PartitionAttributesFactory().setRedundantCopies(0)
.setLocalMaxMemory(numMBytes).create())
.create(this.regionName);
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(0));
int numk = numMBytes * 1024;
int num = numk * 1024;
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(num - 1));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(num));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(num + 1));
final int OVERHEAD = CachedDeserializableFactory.getByteSize(new byte[0]);
for (key = 0; key < numk; key++) {
regionAck.put(new Integer(key), new byte[1024 - OVERHEAD]);
}
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(-1));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(0));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(1));
regionAck.invalidate(new Integer(--key));
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(1023));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(1024));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(1025));
regionAck.put(new Integer(key), new byte[1024 - OVERHEAD]);
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(-1));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(0));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(1));
regionAck.destroy(new Integer(key));
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(1023));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(1024));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(1025));
regionAck.put(new Integer(key), new byte[1023 - OVERHEAD]);
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(0));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(1));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(2));
for (key = 0; key < numk; key++) {
regionAck.destroy(new Integer(key));
}
assertEquals(0, regionAck.size());
assertTrue(regionAck.getDataStore().canAccommodateMoreBytesSafely(num - 1));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(num));
assertFalse(regionAck.getDataStore().canAccommodateMoreBytesSafely(num + 1));
for (key = 0; key < numk; key++) {
regionAck.put(new Integer(key), "foo");
}
}
@Test
public void doesNotCreateBucketIfOverMemoryLimit() {
final int numMBytes = 5;
final PartitionedRegion regionAck = (PartitionedRegion) new RegionFactory()
.setPartitionAttributes(new PartitionAttributesFactory().setRedundantCopies(0)
.setLocalMaxMemory(numMBytes).create())
.create(this.regionName);
boolean createdBucket =
regionAck.getDataStore().handleManageBucketRequest(1, Integer.MAX_VALUE, null, false);
assertFalse(createdBucket);
}
@Test
public void createsBucketWhenForcedIfOverMemoryLimit() {
final int numMBytes = 5;
final PartitionedRegion regionAck = (PartitionedRegion) new RegionFactory()
.setPartitionAttributes(new PartitionAttributesFactory().setRedundantCopies(0)
.setLocalMaxMemory(numMBytes).create())
.create(this.regionName);
boolean createdBucket =
regionAck.getDataStore().handleManageBucketRequest(1, Integer.MAX_VALUE, null, true);
assertTrue(createdBucket);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/pubsub/v1/pubsub.proto
package com.google.pubsub.v1;
/**
* <pre>
* Request for the `CreateSnapshot` method.
* </pre>
*
* Protobuf type {@code google.pubsub.v1.CreateSnapshotRequest}
*/
public final class CreateSnapshotRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.pubsub.v1.CreateSnapshotRequest)
CreateSnapshotRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateSnapshotRequest.newBuilder() to construct.
private CreateSnapshotRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateSnapshotRequest() {
name_ = "";
subscription_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CreateSnapshotRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
subscription_ = s;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.pubsub.v1.PubsubProto.internal_static_google_pubsub_v1_CreateSnapshotRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.pubsub.v1.PubsubProto.internal_static_google_pubsub_v1_CreateSnapshotRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.pubsub.v1.CreateSnapshotRequest.class, com.google.pubsub.v1.CreateSnapshotRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
* <pre>
* Optional user-provided name for this snapshot.
* If the name is not provided in the request, the server will assign a random
* name for this snapshot on the same project as the subscription.
* Note that for REST API requests, you must specify a name.
* Format is `projects/{project}/snapshots/{snap}`.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
* <pre>
* Optional user-provided name for this snapshot.
* If the name is not provided in the request, the server will assign a random
* name for this snapshot on the same project as the subscription.
* Note that for REST API requests, you must specify a name.
* Format is `projects/{project}/snapshots/{snap}`.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SUBSCRIPTION_FIELD_NUMBER = 2;
private volatile java.lang.Object subscription_;
/**
* <pre>
* The subscription whose backlog the snapshot retains.
* Specifically, the created snapshot is guaranteed to retain:
* (a) The existing backlog on the subscription. More precisely, this is
* defined as the messages in the subscription's backlog that are
* unacknowledged upon the successful completion of the
* `CreateSnapshot` request; as well as:
* (b) Any messages published to the subscription's topic following the
* successful completion of the CreateSnapshot request.
* Format is `projects/{project}/subscriptions/{sub}`.
* </pre>
*
* <code>string subscription = 2;</code>
*/
public java.lang.String getSubscription() {
java.lang.Object ref = subscription_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
subscription_ = s;
return s;
}
}
/**
* <pre>
* The subscription whose backlog the snapshot retains.
* Specifically, the created snapshot is guaranteed to retain:
* (a) The existing backlog on the subscription. More precisely, this is
* defined as the messages in the subscription's backlog that are
* unacknowledged upon the successful completion of the
* `CreateSnapshot` request; as well as:
* (b) Any messages published to the subscription's topic following the
* successful completion of the CreateSnapshot request.
* Format is `projects/{project}/subscriptions/{sub}`.
* </pre>
*
* <code>string subscription = 2;</code>
*/
public com.google.protobuf.ByteString
getSubscriptionBytes() {
java.lang.Object ref = subscription_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
subscription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!getSubscriptionBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, subscription_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!getSubscriptionBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, subscription_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.pubsub.v1.CreateSnapshotRequest)) {
return super.equals(obj);
}
com.google.pubsub.v1.CreateSnapshotRequest other = (com.google.pubsub.v1.CreateSnapshotRequest) obj;
boolean result = true;
result = result && getName()
.equals(other.getName());
result = result && getSubscription()
.equals(other.getSubscription());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + SUBSCRIPTION_FIELD_NUMBER;
hash = (53 * hash) + getSubscription().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.pubsub.v1.CreateSnapshotRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.pubsub.v1.CreateSnapshotRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Request for the `CreateSnapshot` method.
* </pre>
*
* Protobuf type {@code google.pubsub.v1.CreateSnapshotRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.pubsub.v1.CreateSnapshotRequest)
com.google.pubsub.v1.CreateSnapshotRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.pubsub.v1.PubsubProto.internal_static_google_pubsub_v1_CreateSnapshotRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.pubsub.v1.PubsubProto.internal_static_google_pubsub_v1_CreateSnapshotRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.pubsub.v1.CreateSnapshotRequest.class, com.google.pubsub.v1.CreateSnapshotRequest.Builder.class);
}
// Construct using com.google.pubsub.v1.CreateSnapshotRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
name_ = "";
subscription_ = "";
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.pubsub.v1.PubsubProto.internal_static_google_pubsub_v1_CreateSnapshotRequest_descriptor;
}
public com.google.pubsub.v1.CreateSnapshotRequest getDefaultInstanceForType() {
return com.google.pubsub.v1.CreateSnapshotRequest.getDefaultInstance();
}
public com.google.pubsub.v1.CreateSnapshotRequest build() {
com.google.pubsub.v1.CreateSnapshotRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.pubsub.v1.CreateSnapshotRequest buildPartial() {
com.google.pubsub.v1.CreateSnapshotRequest result = new com.google.pubsub.v1.CreateSnapshotRequest(this);
result.name_ = name_;
result.subscription_ = subscription_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.pubsub.v1.CreateSnapshotRequest) {
return mergeFrom((com.google.pubsub.v1.CreateSnapshotRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.pubsub.v1.CreateSnapshotRequest other) {
if (other == com.google.pubsub.v1.CreateSnapshotRequest.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (!other.getSubscription().isEmpty()) {
subscription_ = other.subscription_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.pubsub.v1.CreateSnapshotRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.pubsub.v1.CreateSnapshotRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
* <pre>
* Optional user-provided name for this snapshot.
* If the name is not provided in the request, the server will assign a random
* name for this snapshot on the same project as the subscription.
* Note that for REST API requests, you must specify a name.
* Format is `projects/{project}/snapshots/{snap}`.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Optional user-provided name for this snapshot.
* If the name is not provided in the request, the server will assign a random
* name for this snapshot on the same project as the subscription.
* Note that for REST API requests, you must specify a name.
* Format is `projects/{project}/snapshots/{snap}`.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Optional user-provided name for this snapshot.
* If the name is not provided in the request, the server will assign a random
* name for this snapshot on the same project as the subscription.
* Note that for REST API requests, you must specify a name.
* Format is `projects/{project}/snapshots/{snap}`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional user-provided name for this snapshot.
* If the name is not provided in the request, the server will assign a random
* name for this snapshot on the same project as the subscription.
* Note that for REST API requests, you must specify a name.
* Format is `projects/{project}/snapshots/{snap}`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* Optional user-provided name for this snapshot.
* If the name is not provided in the request, the server will assign a random
* name for this snapshot on the same project as the subscription.
* Note that for REST API requests, you must specify a name.
* Format is `projects/{project}/snapshots/{snap}`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private java.lang.Object subscription_ = "";
/**
* <pre>
* The subscription whose backlog the snapshot retains.
* Specifically, the created snapshot is guaranteed to retain:
* (a) The existing backlog on the subscription. More precisely, this is
* defined as the messages in the subscription's backlog that are
* unacknowledged upon the successful completion of the
* `CreateSnapshot` request; as well as:
* (b) Any messages published to the subscription's topic following the
* successful completion of the CreateSnapshot request.
* Format is `projects/{project}/subscriptions/{sub}`.
* </pre>
*
* <code>string subscription = 2;</code>
*/
public java.lang.String getSubscription() {
java.lang.Object ref = subscription_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
subscription_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* The subscription whose backlog the snapshot retains.
* Specifically, the created snapshot is guaranteed to retain:
* (a) The existing backlog on the subscription. More precisely, this is
* defined as the messages in the subscription's backlog that are
* unacknowledged upon the successful completion of the
* `CreateSnapshot` request; as well as:
* (b) Any messages published to the subscription's topic following the
* successful completion of the CreateSnapshot request.
* Format is `projects/{project}/subscriptions/{sub}`.
* </pre>
*
* <code>string subscription = 2;</code>
*/
public com.google.protobuf.ByteString
getSubscriptionBytes() {
java.lang.Object ref = subscription_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
subscription_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* The subscription whose backlog the snapshot retains.
* Specifically, the created snapshot is guaranteed to retain:
* (a) The existing backlog on the subscription. More precisely, this is
* defined as the messages in the subscription's backlog that are
* unacknowledged upon the successful completion of the
* `CreateSnapshot` request; as well as:
* (b) Any messages published to the subscription's topic following the
* successful completion of the CreateSnapshot request.
* Format is `projects/{project}/subscriptions/{sub}`.
* </pre>
*
* <code>string subscription = 2;</code>
*/
public Builder setSubscription(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
subscription_ = value;
onChanged();
return this;
}
/**
* <pre>
* The subscription whose backlog the snapshot retains.
* Specifically, the created snapshot is guaranteed to retain:
* (a) The existing backlog on the subscription. More precisely, this is
* defined as the messages in the subscription's backlog that are
* unacknowledged upon the successful completion of the
* `CreateSnapshot` request; as well as:
* (b) Any messages published to the subscription's topic following the
* successful completion of the CreateSnapshot request.
* Format is `projects/{project}/subscriptions/{sub}`.
* </pre>
*
* <code>string subscription = 2;</code>
*/
public Builder clearSubscription() {
subscription_ = getDefaultInstance().getSubscription();
onChanged();
return this;
}
/**
* <pre>
* The subscription whose backlog the snapshot retains.
* Specifically, the created snapshot is guaranteed to retain:
* (a) The existing backlog on the subscription. More precisely, this is
* defined as the messages in the subscription's backlog that are
* unacknowledged upon the successful completion of the
* `CreateSnapshot` request; as well as:
* (b) Any messages published to the subscription's topic following the
* successful completion of the CreateSnapshot request.
* Format is `projects/{project}/subscriptions/{sub}`.
* </pre>
*
* <code>string subscription = 2;</code>
*/
public Builder setSubscriptionBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
subscription_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.pubsub.v1.CreateSnapshotRequest)
}
// @@protoc_insertion_point(class_scope:google.pubsub.v1.CreateSnapshotRequest)
private static final com.google.pubsub.v1.CreateSnapshotRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.pubsub.v1.CreateSnapshotRequest();
}
public static com.google.pubsub.v1.CreateSnapshotRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateSnapshotRequest>
PARSER = new com.google.protobuf.AbstractParser<CreateSnapshotRequest>() {
public CreateSnapshotRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CreateSnapshotRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CreateSnapshotRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateSnapshotRequest> getParserForType() {
return PARSER;
}
public com.google.pubsub.v1.CreateSnapshotRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.admin;
import java.io.Closeable;
import java.io.IOException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.client.admin.internal.BrokerStatsImpl;
import org.apache.pulsar.client.admin.internal.BrokersImpl;
import org.apache.pulsar.client.admin.internal.ClustersImpl;
import org.apache.pulsar.client.admin.internal.FunctionsImpl;
import org.apache.pulsar.client.admin.internal.JacksonConfigurator;
import org.apache.pulsar.client.admin.internal.LookupImpl;
import org.apache.pulsar.client.admin.internal.NamespacesImpl;
import org.apache.pulsar.client.admin.internal.NonPersistentTopicsImpl;
import org.apache.pulsar.client.admin.internal.PersistentTopicsImpl;
import org.apache.pulsar.client.admin.internal.TenantsImpl;
import org.apache.pulsar.client.admin.internal.PulsarAdminBuilderImpl;
import org.apache.pulsar.client.admin.internal.ResourceQuotasImpl;
import org.apache.pulsar.client.api.Authentication;
import org.apache.pulsar.client.api.AuthenticationDataProvider;
import org.apache.pulsar.client.api.AuthenticationFactory;
import org.apache.pulsar.client.api.ClientConfiguration;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.impl.auth.AuthenticationDisabled;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.common.util.SecurityUtility;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
/**
* Pulsar client admin API client.
*/
@SuppressWarnings("deprecation")
public class PulsarAdmin implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(PulsarAdmin.class);
private final Clusters clusters;
private final Brokers brokers;
private final BrokerStats brokerStats;
private final Tenants tenants;
private final Properties properties;
private final Namespaces namespaces;
private final PersistentTopics persistentTopics;
private final NonPersistentTopics nonPersistentTopics;
private final ResourceQuotas resourceQuotas;
private final ClientConfigurationData clientConfigData;
private final Client client;
private final String serviceUrl;
private final Lookup lookups;
private final Functions functions;
protected final WebTarget root;
protected final Authentication auth;
static {
/**
* The presence of slf4j-jdk14.jar, that is the jul binding for SLF4J, will force SLF4J calls to be delegated to
* jul. On the other hand, the presence of jul-to-slf4j.jar, plus the installation of SLF4JBridgeHandler, by
* invoking "SLF4JBridgeHandler.install()" will route jul records to SLF4J. Thus, if both jar are present
* simultaneously (and SLF4JBridgeHandler is installed), slf4j calls will be delegated to jul and jul records
* will be routed to SLF4J, resulting in an endless loop. We avoid this loop by detecting if slf4j-jdk14 is used
* in the client class path. If slf4j-jdk14 is found, we don't use the slf4j bridge.
*/
try {
Class.forName("org.slf4j.impl.JDK14LoggerFactory");
} catch (Exception ex) {
// Setup the bridge for java.util.logging to SLF4J
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
}
/**
* Creates a builder to construct an instance of {@link PulsarAdmin}.
*/
public static PulsarAdminBuilder builder() {
return new PulsarAdminBuilderImpl();
}
public PulsarAdmin(String serviceUrl, ClientConfigurationData clientConfigData) throws PulsarClientException {
this.clientConfigData = clientConfigData;
this.auth = clientConfigData != null ? clientConfigData.getAuthentication() : new AuthenticationDisabled();
LOG.debug("created: serviceUrl={}, authMethodName={}", serviceUrl,
auth != null ? auth.getAuthMethodName() : null);
if (auth != null) {
auth.start();
}
ClientConfig httpConfig = new ClientConfig();
httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
httpConfig.register(MultiPartFeature.class);
ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
.register(JacksonConfigurator.class).register(JacksonFeature.class);
boolean useTls = false;
if (clientConfigData != null && StringUtils.isNotBlank(clientConfigData.getServiceUrl())
&& clientConfigData.getServiceUrl().startsWith("https://")) {
useTls = true;
try {
SSLContext sslCtx = null;
X509Certificate trustCertificates[] = SecurityUtility
.loadCertificatesFromPemFile(clientConfigData.getTlsTrustCertsFilePath());
// Set private key and certificate if available
AuthenticationDataProvider authData = auth.getAuthData();
if (authData.hasDataForTls()) {
sslCtx = SecurityUtility.createSslContext(clientConfigData.isTlsAllowInsecureConnection(),
trustCertificates, authData.getTlsCertificates(), authData.getTlsPrivateKey());
} else {
sslCtx = SecurityUtility.createSslContext(clientConfigData.isTlsAllowInsecureConnection(),
trustCertificates);
}
clientBuilder.sslContext(sslCtx);
} catch (Exception e) {
try {
if (auth != null) {
auth.close();
}
} catch (IOException ioe) {
LOG.error("Failed to close the authentication service", ioe);
}
throw new PulsarClientException.InvalidConfigurationException(e.getMessage());
}
}
this.client = clientBuilder.build();
this.serviceUrl = serviceUrl;
root = client.target(serviceUrl.toString());
this.clusters = new ClustersImpl(root, auth);
this.brokers = new BrokersImpl(root, auth);
this.brokerStats = new BrokerStatsImpl(root, auth);
this.tenants = new TenantsImpl(root, auth);
this.properties = new TenantsImpl(root, auth);;
this.namespaces = new NamespacesImpl(root, auth);
this.persistentTopics = new PersistentTopicsImpl(root, auth);
this.nonPersistentTopics = new NonPersistentTopicsImpl(root, auth);
this.resourceQuotas = new ResourceQuotasImpl(root, auth);
this.lookups = new LookupImpl(root, auth, useTls);
this.functions = new FunctionsImpl(root, auth);
}
/**
* Construct a new Pulsar Admin client object.
* <p>
* This client object can be used to perform many subsquent API calls
*
* @param serviceUrl
* the Pulsar service URL (eg. "http://my-broker.example.com:8080")
* @param pulsarConfig
* the ClientConfiguration object to be used to talk with Pulsar
* @deprecated Since 2.0. Use {@link #builder()} to construct a new {@link PulsarAdmin} instance.
*/
@Deprecated
public PulsarAdmin(URL serviceUrl, ClientConfiguration pulsarConfig) throws PulsarClientException {
this(serviceUrl.toString(), pulsarConfig.getConfigurationData());
}
/**
* Construct a new Pulsar Admin client object.
* <p>
* This client object can be used to perform many subsquent API calls
*
* @param serviceUrl
* the Pulsar service URL (eg. "http://my-broker.example.com:8080")
* @param auth
* the Authentication object to be used to talk with Pulsar
* @deprecated Since 2.0. Use {@link #builder()} to construct a new {@link PulsarAdmin} instance.
*/
@Deprecated
public PulsarAdmin(URL serviceUrl, Authentication auth) throws PulsarClientException {
this(serviceUrl, new ClientConfiguration() {
private static final long serialVersionUID = 1L;
{
setAuthentication(auth);
}
});
}
/**
* Construct a new Pulsar Admin client object.
* <p>
* This client object can be used to perform many subsquent API calls
*
* @param serviceUrl
* the Pulsar URL (eg. "http://my-broker.example.com:8080")
* @param authPluginClassName
* name of the Authentication-Plugin you want to use
* @param authParamsString
* string which represents parameters for the Authentication-Plugin, e.g., "key1:val1,key2:val2"
* @deprecated Since 2.0. Use {@link #builder()} to construct a new {@link PulsarAdmin} instance.
*/
@Deprecated
public PulsarAdmin(URL serviceUrl, String authPluginClassName, String authParamsString)
throws PulsarClientException {
this(serviceUrl, AuthenticationFactory.create(authPluginClassName, authParamsString));
}
/**
* Construct a new Pulsar Admin client object.
* <p>
* This client object can be used to perform many subsquent API calls
*
* @param serviceUrl
* the Pulsar URL (eg. "http://my-broker.example.com:8080")
* @param authPluginClassName
* name of the Authentication-Plugin you want to use
* @param authParams
* map which represents parameters for the Authentication-Plugin
* @deprecated Since 2.0. Use {@link #builder()} to construct a new {@link PulsarAdmin} instance.
*/
@Deprecated
public PulsarAdmin(URL serviceUrl, String authPluginClassName, Map<String, String> authParams)
throws PulsarClientException {
this(serviceUrl, AuthenticationFactory.create(authPluginClassName, authParams));
}
/**
* @return the clusters management object
*/
public Clusters clusters() {
return clusters;
}
/**
* @return the brokers management object
*/
public Brokers brokers() {
return brokers;
}
/**
* @return the tenants management object
*/
public Tenants tenants() {
return tenants;
}
/**
*
* @deprecated since 2.0. See {@link #tenants()}
*/
@Deprecated
public Properties properties() {
return properties;
}
/**
* @return the namespaces management object
*/
public Namespaces namespaces() {
return namespaces;
}
/**
* @return the persistentTopics management object
*/
public PersistentTopics persistentTopics() {
return persistentTopics;
}
/**
* @return the persistentTopics management object
*/
public NonPersistentTopics nonPersistentTopics() {
return nonPersistentTopics;
}
/**
* @return the resource quota management object
*/
public ResourceQuotas resourceQuotas() {
return resourceQuotas;
}
/**
* @return does a looks up for the broker serving the topic
*/
public Lookup lookups() {
return lookups;
}
/**
*
* @return the functions management object
*/
public Functions functions() {
return functions;
}
/**
* @return the broker statics
*/
public BrokerStats brokerStats() {
return brokerStats;
}
/**
* @return the service HTTP URL that is being used
*/
public String getServiceUrl() {
return serviceUrl;
}
/**
* @return the client Configuration Data that is being used
*/
public ClientConfigurationData getClientConfigData() {
return clientConfigData;
}
/**
* Close the Pulsar admin client to release all the resources
*/
@Override
public void close() {
try {
if (auth != null) {
auth.close();
}
} catch (IOException e) {
LOG.error("Failed to close the authentication service", e);
}
client.close();
}
}
| |
/*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Neustar Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package com.neulevel.epp.transport;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This <code>EppSessionUtil</code> class contains some utility methods for
* handling message exchanges between an EPP Server and an EPP Client.
*
* @author Ning Zhang ning.zhang@neustar.com
* @version $Revision: 1.4 $ $Date: 2008/11/13 17:06:52 $
*/
public class EppMessageUtil
{
private static final int BUFSIZ = 8192;
private static boolean writeMessageSize = true;
private static boolean fetchMessageSize = true;
/**
* Property for handling the size of an EPP message.
*
* This property could be used to enable/disable the processing of EPP message
* length, specified for backward compatibility for EPP TCP transport mapping.
*
* Two boolean flags can be specified via the property, each of them can be
* separated by a delimit char ",".
*
* <UL>
* <LI>Flag for generating message length in outbounding messages:
* <UL><LI>+write: true</LI><LI>-write: false</LI></UL></LI>
* <LI>Flag for fetching message length in inbounding messages:
* <UL><LI>+fetch: true</LI><LI>-fetch: false</LI></UL></LI>
* </UL>
*
* For example:
*
* <P>
* -Dcom.neulevel.epp.transport.EppMessageUtil.eppMessageSize=+output,-fetch
*
* <P>
* The default values of the property is: +output,+fetch
*/
public static final String eppMessageSize = "com.neulevel.epp.transport.EppMessageUtil.eppMessageSize";
static
{
String flags = System.getProperty(eppMessageSize);
if( flags != null )
{
StringTokenizer tokens = new StringTokenizer(flags, ",");
while( tokens.hasMoreTokens() )
{
String token = tokens.nextToken();
if( token == null )
{
continue;
}
if( token.equalsIgnoreCase("+write") )
{
writeMessageSize = true;
}
else if( token.equalsIgnoreCase("-write") )
{
writeMessageSize = false;
}
else if( token.equalsIgnoreCase("+fetch") )
{
fetchMessageSize = true;
}
else if( token.equalsIgnoreCase("-fetch") )
{
fetchMessageSize = false;
}
}
}
}
/**
* Sets the flags for handling EPP message size
*/
public static void setEppMessageSizeFlags( boolean write, boolean fetch )
{
writeMessageSize = write;
fetchMessageSize = fetch;
}
/**
* Gets the flag for outputing the size of an outgoing EPP message
*/
public static boolean getEppMessageSizeWriteFlag()
{
return writeMessageSize;
}
/**
* Gets the flag for extracting the size of an incoming EPP message
*/
public static boolean getEppMessageSizeFetchFlag()
{
return fetchMessageSize;
}
/**
* Timeout value in 1/10 seconds
*/
private static int timeout = 0;
/**
* Sets the timeout values in seconds. The default value is 0, which
* means there will be no timeout.
*/
public static void setTimeout( int seconds )
{
if( seconds > 0 )
{
EppMessageUtil.timeout = seconds * 10;
}
}
/**
* Gets the timeout values in seconds. The default value is 0, which
* means there will be no timeout.
*/
public static int getTimeout()
{
return EppMessageUtil.timeout / 10;
}
/**
* Sends out an outgoing EPP message
*
* @param out the <code>OutputStream</code> object to which the EPP
* message payload is sent
*
* @param str the string to be sent out
*/
public static void putEppPayload( OutputStream out, String str ) throws IOException
{
if( writeMessageSize == true )
{
byte[] bytes = str.getBytes();
byte[] size = new byte[4];
int bytes_length = bytes.length + 4;
size[3] = (byte) ( bytes_length & 0x0000FF );
size[2] = (byte) ((bytes_length & 0x00FF00) >> 8);
size[1] = (byte) ((bytes_length & 0xFF0000) >> 16);
size[0] = (byte) ( bytes_length >>> 24);
out.write(size);
out.write(bytes);
}
else
{
out.write(str.getBytes());
}
out.flush();
}
/**
* Sends a string over a socket and reads a string back from
* the socket
*
* @param socket the socket used for sending the string
* @param str the string to be sent over the socket
*
* @return a string containing the EPP message payload, or null
* if there is any error associated with the connection to
* the server
*/
public static String send( Socket socket, String str ) throws IOException
{
socket.setSoTimeout(EppMessageUtil.timeout*1000);
OutputStream out = socket.getOutputStream();
EppMessageUtil.putEppPayload(out, str);
return EppMessageUtil.getEppPayload(socket.getInputStream());
}
/**
* Gets the EPP message payload size from an input stream
*
* @param in the <code>InputStream</code> object from which the EPP
* message payload is retrieved
*
* @return an integer indicates the size of the EPP payload
*/
private static int getEppPayloadSize( InputStream in ) throws IOException
{
int size = 0;
int n;
for( int i = 0; i < 4; i++ )
{
int loop = 0;
n = in.read();
if (n == -1)//end of stream is reached from JDK1.6 documentaion
{
System.out.println("***Connection with server lost.Throwing Exception.***");
throw new IOException("Connection with server lost.Throwing Exception.");
}
size = size << 8;
size |= n & 0xFF;
}
size -= 4;
return size;
}
/**
* Gets the EPP message payload from an input stream
*
* @param in the <code>InputStream</code> object from which the EPP
* message payload is retrieved
*
* @return a string containing the EPP message payload, or null
* if there is any error associated with the connection to
* the server
*/
public static String getEppPayload( InputStream in ) throws IOException
{
byte[] buf = new byte[BUFSIZ];
int i = 0;
int n;
boolean endFound = false;
boolean eppFound = false;
int eppSize = 0;
if( fetchMessageSize == true )
{
eppSize = EppMessageUtil.getEppPayloadSize(in);
if( eppSize <= 0 )
{
throw new IOException("Error in eppGetPayload() message size is invalid " + eppSize);
}
}
while( ! endFound )
{
int loop = 0;
n = in.read();
if (n == -1)//end of stream is reached from JDK1.6 documentaion
{
System.out.println("***Connection with server lost.Throwing Exception.***");
throw new IOException("Connection with server lost.Throwing Exception.");
}
// EPP payload rarely exceeds 8KB, so this
// doubling-up should not occur very often
if( i == buf.length )
{
byte[] newbuf = new byte[buf.length + BUFSIZ];
for( i = 0; i < buf.length; i++ )
{
newbuf[i] = buf[i];
}
buf = newbuf;
}
buf[i++] = (byte) n;
// check if we have got the "</epp" tag
if( ! eppFound
&& (i >= 5)
&& (buf[i - 5] == '<')
&& (buf[i - 4] == '/')
&& (buf[i - 3] == 'e')
&& (buf[i - 2] == 'p')
&& (buf[i - 1] == 'p') )
{
eppFound = true;
}
if( eppFound && (buf[i - 1] == '>') )
{
endFound = true;
}
// check if we have reached the size
if( fetchMessageSize == true )
{
if( i == eppSize )
{
endFound = true;
}
else
{
endFound = false;
}
}
}
// ok, we have got a buffer, either with a full EPP payload, or
// end of the input stream
return new String(buf, 0, i).trim();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.runtime.tasks;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.core.fs.CloseableRegistry;
import org.apache.flink.core.testutils.OneShotLatch;
import org.apache.flink.runtime.blob.BlobCacheService;
import org.apache.flink.runtime.blob.PermanentBlobCache;
import org.apache.flink.runtime.blob.TransientBlobCache;
import org.apache.flink.runtime.broadcast.BroadcastVariableManager;
import org.apache.flink.runtime.checkpoint.CheckpointMetaData;
import org.apache.flink.runtime.checkpoint.CheckpointMetrics;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.checkpoint.TaskStateSnapshot;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.concurrent.Executors;
import org.apache.flink.runtime.deployment.InputGateDeploymentDescriptor;
import org.apache.flink.runtime.deployment.ResultPartitionDeploymentDescriptor;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.execution.ExecutionState;
import org.apache.flink.runtime.execution.librarycache.BlobLibraryCacheManager;
import org.apache.flink.runtime.execution.librarycache.FlinkUserCodeClassLoaders;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.executiongraph.JobInformation;
import org.apache.flink.runtime.executiongraph.TaskInformation;
import org.apache.flink.runtime.filecache.FileCache;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.io.network.NettyShuffleEnvironmentBuilder;
import org.apache.flink.runtime.io.network.TaskEventDispatcher;
import org.apache.flink.runtime.io.network.partition.NoOpResultPartitionConsumableNotifier;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.InputSplitProvider;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.query.KvStateRegistry;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
import org.apache.flink.runtime.state.AbstractSnapshotStrategy;
import org.apache.flink.runtime.state.AbstractStateBackend;
import org.apache.flink.runtime.state.CheckpointStreamFactory;
import org.apache.flink.runtime.state.CheckpointStreamFactory.CheckpointStateOutputStream;
import org.apache.flink.runtime.state.DefaultOperatorStateBackend;
import org.apache.flink.runtime.state.DefaultOperatorStateBackendBuilder;
import org.apache.flink.runtime.state.OperatorStateBackend;
import org.apache.flink.runtime.state.OperatorStateCheckpointOutputStream;
import org.apache.flink.runtime.state.OperatorStateHandle;
import org.apache.flink.runtime.state.SnapshotResult;
import org.apache.flink.runtime.state.StateBackend;
import org.apache.flink.runtime.state.StateSnapshotContext;
import org.apache.flink.runtime.state.StreamStateHandle;
import org.apache.flink.runtime.state.TestTaskStateManager;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.runtime.state.testutils.BackendForTestStream;
import org.apache.flink.runtime.taskexecutor.KvStateService;
import org.apache.flink.runtime.taskexecutor.PartitionProducerStateChecker;
import org.apache.flink.runtime.taskexecutor.TestGlobalAggregateManager;
import org.apache.flink.runtime.taskmanager.CheckpointResponder;
import org.apache.flink.runtime.taskmanager.NoOpTaskOperatorEventGateway;
import org.apache.flink.runtime.taskmanager.Task;
import org.apache.flink.runtime.taskmanager.TaskManagerActions;
import org.apache.flink.runtime.util.EnvironmentInformation;
import org.apache.flink.runtime.util.TestingTaskManagerRuntimeInfo;
import org.apache.flink.streaming.api.graph.StreamConfig;
import org.apache.flink.streaming.api.operators.StreamFilter;
import org.apache.flink.streaming.api.operators.StreamOperator;
import org.apache.flink.streaming.runtime.tasks.mailbox.MailboxDefaultAction;
import org.apache.flink.util.SerializedValue;
import org.apache.flink.util.TestLogger;
import org.junit.Assert;
import org.junit.Test;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
/**
* This test checks that task checkpoints that block and do not react to thread interrupts. It also checks correct
* working of different policies how tasks deal with checkpoint failures (fail task, decline checkpoint and continue).
*/
public class TaskCheckpointingBehaviourTest extends TestLogger {
private static final OneShotLatch IN_CHECKPOINT_LATCH = new OneShotLatch();
@Test
public void testDeclineOnCheckpointErrorInSyncPart() throws Exception {
runTestDeclineOnCheckpointError(new SyncFailureInducingStateBackend());
}
@Test
public void testDeclineOnCheckpointErrorInAsyncPart() throws Exception {
runTestDeclineOnCheckpointError(new AsyncFailureInducingStateBackend());
}
@Test
public void testBlockingNonInterruptibleCheckpoint() throws Exception {
StateBackend lockingStateBackend = new BackendForTestStream(LockingOutputStream::new);
Task task =
createTask(new TestOperator(), lockingStateBackend, mock(CheckpointResponder.class));
// start the task and wait until it is in "restore"
task.startTaskThread();
IN_CHECKPOINT_LATCH.await();
// cancel the task and wait. unless cancellation properly closes
// the streams, this will never terminate
task.cancelExecution();
task.getExecutingThread().join();
assertEquals(ExecutionState.CANCELED, task.getExecutionState());
assertNull(task.getFailureCause());
}
private void runTestDeclineOnCheckpointError(AbstractStateBackend backend) throws Exception{
TestDeclinedCheckpointResponder checkpointResponder = new TestDeclinedCheckpointResponder();
Task task =
createTask(new FilterOperator(), backend, checkpointResponder);
// start the task and wait until it is in "restore"
task.startTaskThread();
checkpointResponder.declinedLatch.await();
Assert.assertEquals(ExecutionState.RUNNING, task.getExecutionState());
task.cancelExecution();
task.getExecutingThread().join();
}
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
private static Task createTask(
StreamOperator<?> op,
StateBackend backend,
CheckpointResponder checkpointResponder) throws IOException {
Configuration taskConfig = new Configuration();
StreamConfig cfg = new StreamConfig(taskConfig);
cfg.setStreamOperator(op);
cfg.setOperatorID(new OperatorID());
cfg.setStateBackend(backend);
ExecutionConfig executionConfig = new ExecutionConfig();
JobInformation jobInformation = new JobInformation(
new JobID(),
"test job name",
new SerializedValue<>(executionConfig),
new Configuration(),
Collections.emptyList(),
Collections.emptyList());
TaskInformation taskInformation = new TaskInformation(
new JobVertexID(),
"test task name",
1,
11,
TestStreamTask.class.getName(),
taskConfig);
ShuffleEnvironment<?, ?> shuffleEnvironment = new NettyShuffleEnvironmentBuilder().build();
BlobCacheService blobService =
new BlobCacheService(mock(PermanentBlobCache.class), mock(TransientBlobCache.class));
return new Task(
jobInformation,
taskInformation,
new ExecutionAttemptID(),
new AllocationID(),
0,
0,
Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
Collections.<InputGateDeploymentDescriptor>emptyList(),
0,
mock(MemoryManager.class),
mock(IOManager.class),
shuffleEnvironment,
new KvStateService(new KvStateRegistry(), null, null),
mock(BroadcastVariableManager.class),
new TaskEventDispatcher(),
new TestTaskStateManager(),
mock(TaskManagerActions.class),
mock(InputSplitProvider.class),
checkpointResponder,
new NoOpTaskOperatorEventGateway(),
new TestGlobalAggregateManager(),
blobService,
new BlobLibraryCacheManager(
blobService.getPermanentBlobService(),
FlinkUserCodeClassLoaders.ResolveOrder.CHILD_FIRST,
new String[0]),
new FileCache(new String[] { EnvironmentInformation.getTemporaryFileDirectory() },
blobService.getPermanentBlobService()),
new TestingTaskManagerRuntimeInfo(),
UnregisteredMetricGroups.createUnregisteredTaskMetricGroup(),
new NoOpResultPartitionConsumableNotifier(),
mock(PartitionProducerStateChecker.class),
Executors.directExecutor());
}
// ------------------------------------------------------------------------
// checkpoint responder that records a call to decline.
// ------------------------------------------------------------------------
private static class TestDeclinedCheckpointResponder implements CheckpointResponder {
final OneShotLatch declinedLatch = new OneShotLatch();
@Override
public void acknowledgeCheckpoint(
JobID jobID,
ExecutionAttemptID executionAttemptID,
long checkpointId,
CheckpointMetrics checkpointMetrics,
TaskStateSnapshot subtaskState) {
throw new RuntimeException("Unexpected call.");
}
@Override
public void declineCheckpoint(
JobID jobID,
ExecutionAttemptID executionAttemptID,
long checkpointId,
Throwable cause) {
declinedLatch.trigger();
}
public OneShotLatch getDeclinedLatch() {
return declinedLatch;
}
}
// ------------------------------------------------------------------------
// state backends that trigger errors in checkpointing.
// ------------------------------------------------------------------------
private static class SyncFailureInducingStateBackend extends MemoryStateBackend {
private static final long serialVersionUID = -1915780414440060539L;
@Override
public OperatorStateBackend createOperatorStateBackend(
Environment env,
String operatorIdentifier,
@Nonnull Collection<OperatorStateHandle> stateHandles,
CloseableRegistry cancelStreamRegistry) throws Exception {
return new DefaultOperatorStateBackendBuilder(
env.getUserClassLoader(),
env.getExecutionConfig(),
true,
stateHandles,
cancelStreamRegistry) {
@Override
@SuppressWarnings("unchecked")
public DefaultOperatorStateBackend build() {
return new DefaultOperatorStateBackend(
executionConfig,
cancelStreamRegistry,
new HashMap<>(),
new HashMap<>(),
new HashMap<>(),
new HashMap<>(),
mock(AbstractSnapshotStrategy.class)
) {
@Nonnull
@Override
public RunnableFuture<SnapshotResult<OperatorStateHandle>> snapshot(
long checkpointId,
long timestamp,
@Nonnull CheckpointStreamFactory streamFactory,
@Nonnull CheckpointOptions checkpointOptions) throws Exception {
throw new Exception("Sync part snapshot exception.");
}
};
}
}.build();
}
@Override
public SyncFailureInducingStateBackend configure(ReadableConfig configuration, ClassLoader classLoader) {
// retain this instance, no re-configuration!
return this;
}
}
private static class AsyncFailureInducingStateBackend extends MemoryStateBackend {
private static final long serialVersionUID = -7613628662587098470L;
@Override
public OperatorStateBackend createOperatorStateBackend(
Environment env,
String operatorIdentifier,
@Nonnull Collection<OperatorStateHandle> stateHandles,
CloseableRegistry cancelStreamRegistry) throws Exception {
return new DefaultOperatorStateBackendBuilder(
env.getUserClassLoader(),
env.getExecutionConfig(),
true,
stateHandles,
cancelStreamRegistry) {
@Override
@SuppressWarnings("unchecked")
public DefaultOperatorStateBackend build() {
return new DefaultOperatorStateBackend(
executionConfig,
cancelStreamRegistry,
new HashMap<>(),
new HashMap<>(),
new HashMap<>(),
new HashMap<>(),
mock(AbstractSnapshotStrategy.class)
) {
@Nonnull
@Override
public RunnableFuture<SnapshotResult<OperatorStateHandle>> snapshot(
long checkpointId,
long timestamp,
@Nonnull CheckpointStreamFactory streamFactory,
@Nonnull CheckpointOptions checkpointOptions) throws Exception {
return new FutureTask<>(() -> {
throw new Exception("Async part snapshot exception.");
});
}
};
}
}.build();
}
@Override
public AsyncFailureInducingStateBackend configure(ReadableConfig config, ClassLoader classLoader) {
// retain this instance, no re-configuration!
return this;
}
}
// ------------------------------------------------------------------------
// locking output stream.
// ------------------------------------------------------------------------
private static final class LockingOutputStream extends CheckpointStateOutputStream {
private final Object lock = new Object();
private volatile boolean closed;
@Nullable
@Override
public StreamStateHandle closeAndGetHandle() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void write(int b) throws IOException {
// this needs to not react to interrupts until the handle is closed
synchronized (lock) {
while (!closed) {
try {
lock.wait();
}
catch (InterruptedException ignored) {}
}
}
}
@Override
public void close() throws IOException {
synchronized (lock) {
closed = true;
lock.notifyAll();
}
}
@Override
public long getPos() {
return 0;
}
@Override
public void flush() {}
@Override
public void sync() {}
}
// ------------------------------------------------------------------------
// test source operator that calls into the locking checkpoint output stream.
// ------------------------------------------------------------------------
@SuppressWarnings("serial")
private static final class FilterOperator extends StreamFilter<Object> {
private static final long serialVersionUID = 1L;
public FilterOperator() {
super(new FilterFunction<Object>() {
@Override
public boolean filter(Object value) {
return false;
}
});
}
}
@SuppressWarnings("serial")
private static final class TestOperator extends StreamFilter<Object> {
private static final long serialVersionUID = 1L;
public TestOperator() {
super(new FilterFunction<Object>() {
@Override
public boolean filter(Object value) {
return false;
}
});
}
@Override
public void snapshotState(StateSnapshotContext context) throws Exception {
OperatorStateCheckpointOutputStream outStream = context.getRawOperatorStateOutput();
IN_CHECKPOINT_LATCH.trigger();
// this should lock
outStream.write(1);
}
}
/**
* Stream task that simply triggers a checkpoint.
*/
public static final class TestStreamTask extends OneInputStreamTask<Object, Object> {
public TestStreamTask(Environment env) throws Exception {
super(env);
}
@Override
public void init() {}
@Override
protected void processInput(MailboxDefaultAction.Controller controller) throws Exception {
triggerCheckpointOnBarrier(
new CheckpointMetaData(
11L,
System.currentTimeMillis()),
CheckpointOptions.forCheckpointWithDefaultLocation(),
new CheckpointMetrics());
while (isRunning()) {
Thread.sleep(1L);
}
controller.allActionsCompleted();
}
@Override
protected void cleanup() {}
}
}
| |
package org.folio.okapi;
import guru.nidi.ramltester.RamlDefinition;
import guru.nidi.ramltester.RamlLoaders;
import guru.nidi.ramltester.restassured3.RestAssuredClient;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.vertx.core.AsyncResult;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.SocketAddress;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.apache.logging.log4j.Logger;
import org.folio.okapi.common.OkapiLogger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@java.lang.SuppressWarnings({"squid:S1166", "squid:S1192"})
@RunWith(VertxUnitRunner.class)
public class DockerTest {
private final Logger logger = OkapiLogger.get();
private Vertx vertx;
private final int port = 9230;
private static final String LS = System.lineSeparator();
private boolean haveDocker = false;
private HttpClient client;
private JsonArray dockerImages = new JsonArray();
@Before
public void setUp(TestContext context) {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
Async async = context.async();
VertxOptions options = new VertxOptions();
options.setBlockedThreadCheckInterval(60000); // in ms
options.setWarningExceptionTime(60000); // in ms
options.setPreferNativeTransport(true);
vertx = Vertx.vertx(options);
RestAssured.port = port;
client = vertx.createHttpClient();
checkDocker(res -> {
haveDocker = res.succeeded();
if (res.succeeded()) {
dockerImages = res.result();
logger.info("Docker found");
} else {
logger.warn("No docker: " + res.cause().getMessage());
}
DeploymentOptions opt = new DeploymentOptions()
.setConfig(new JsonObject()
.put("containerHost", "localhost")
.put("port", Integer.toString(port))
.put("port_start", Integer.toString(port + 4))
.put("port_end", Integer.toString(port + 6)));
vertx.deployVerticle(MainVerticle.class.getName(),
opt, x -> async.complete());
});
}
@After
public void tearDown(TestContext context) {
logger.info("tearDown");
Async async = context.async();
HttpClient httpClient = vertx.createHttpClient();
httpClient.request(HttpMethod.DELETE, port,
"localhost", "/_/discovery/modules", context.asyncAssertSuccess(request -> {
request.end();
request.response(context.asyncAssertSuccess(response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
httpClient.close();
vertx.close(context.asyncAssertSuccess());
async.complete();
});
}));
}));
}
private void checkDocker(Handler<AsyncResult<JsonArray>> future) {
final SocketAddress socketAddress
= SocketAddress.domainSocketAddress("/var/run/docker.sock");
final String url = "http://localhost/images/json?all=1";
client.request(new RequestOptions().setURI(url).setServer(socketAddress).setMethod(HttpMethod.GET),
res1 -> {
if (res1.failed()) {
future.handle(Future.failedFuture(res1.cause()));
return;
}
res1.result().end();
res1.result().response(res2 -> {
if (res2.failed()) {
future.handle(Future.failedFuture(res2.cause()));
return;
}
HttpClientResponse res = res2.result();
Buffer body = Buffer.buffer();
res.handler(body::appendBuffer);
res.endHandler(d -> {
if (res.statusCode() == 200) {
try {
JsonArray ar = body.toJsonArray();
future.handle(Future.succeededFuture(ar));
} catch (Exception ex) {
logger.warn(ex);
future.handle(Future.failedFuture(ex));
}
} else {
String m = "checkDocker HTTP error " + res.statusCode() + "\n"
+ body.toString();
logger.error(m);
future.handle(Future.failedFuture(m));
}
});
res.exceptionHandler(d -> {
logger.warn("exceptionHandler 2 " + d, d);
future.handle(Future.failedFuture(d));
});
});
});
}
private static boolean checkTestModulePresent(JsonArray ar) {
if (ar != null) {
for (int i = 0; i < ar.size(); i++) {
JsonObject ob = ar.getJsonObject(i);
JsonArray ar1 = ob.getJsonArray("RepoTags");
if (ar1 != null) {
for (int j = 0; j < ar1.size(); j++) {
String tag = ar1.getString(j);
if (tag != null && tag.startsWith("okapi-test-module")) {
return true;
}
}
}
}
}
return false;
}
// deploys okapi-test-module
// to avoid skip, use:
// cd okapi-test-module
// docker build -t okapi-test-module .
@Test
public void deploySampleModule(TestContext context) {
org.junit.Assume.assumeTrue(checkTestModulePresent(dockerImages));
if (!checkTestModulePresent(dockerImages)) {
return;
}
RestAssuredClient c;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
final String docSampleDockerModule = "{" + LS
+ " \"id\" : \"sample-module-1.0.0\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"pathPattern\" : \"/testb\"," + LS
+ " \"permissionsRequired\" : [ ]" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"dockerImage\" : \"okapi-test-module\"," + LS
+ " \"dockerPull\" : false," + LS
+ " \"dockerCMD\" : [\"-Dfoo=bar\"]," + LS
+ " \"dockerArgs\" : {" + LS
+ " \"StopTimeout\" : 12," + LS
+ " \"HostConfig\": { \"PortBindings\": { \"8080/tcp\": [{ \"HostPort\": \"%p\" }] } }" + LS
+ " }" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured3();
c.given()
.header("Content-Type", "application/json")
.body(docSampleDockerModule).post("/_/proxy/modules")
.then()
.statusCode(201);
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
final String doc1 = "{" + LS
+ " \"srvcId\" : \"sample-module-1.0.0\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured3();
c.given().header("Content-Type", "application/json")
.body(doc1).post("/_/discovery/modules")
.then().statusCode(201);
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
}
@Test
public void deployUnknownModule(TestContext context) {
RestAssuredClient c;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
final String docSampleDockerModule = "{" + LS
+ " \"id\" : \"sample-unknown-1\"," + LS
+ " \"name\" : \"sample unknown\"," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"dockerImage\" : \"okapi-unknown\"," + LS
+ " \"dockerPull\" : false," + LS
+ " \"dockerArgs\" : {" + LS
+ " \"StopTimeout\" : 12," + LS
+ " \"HostConfig\": { \"PortBindings\": { \"8080/tcp\": [{ \"HostPort\": \"%p\" }] } }" + LS
+ " }" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured3();
c.given()
.header("Content-Type", "application/json")
.body(docSampleDockerModule).post("/_/proxy/modules")
.then()
.statusCode(201);
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
final String doc1 = "{" + LS
+ " \"srvcId\" : \"sample-unknown-1\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured3();
c.given().header("Content-Type", "application/json")
.body(doc1).post("/_/discovery/modules")
.then().statusCode(400);
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
}
@Test
public void deployBadListeningPort(TestContext context) {
org.junit.Assume.assumeTrue(haveDocker);
RestAssuredClient c;
Response r;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
// forward to 8090, which the module does not bind to..
final String docUserDockerModule = "{" + LS
+ " \"id\" : \"mod-users-5.0.0-bad-listening-port\"," + LS
+ " \"name\" : \"users\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"users\"," + LS
+ " \"version\" : \"1.0\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"pathPattern\" : \"/test\"," + LS
+ " \"permissionsRequired\" : [ ]" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"waitIterations\" : 5," + LS
+ " \"dockerImage\" : \"folioci/mod-users:5.0.0-SNAPSHOT\"," + LS
+ " \"dockerArgs\" : {" + LS
+ " \"HostConfig\": { \"PortBindings\": { \"8090/tcp\": [{ \"HostPort\": \"%p\" }] } }" + LS
+ " }" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured3();
c.given()
.header("Content-Type", "application/json")
.body(docUserDockerModule).post("/_/proxy/modules")
.then()
.statusCode(201);
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
final String doc2 = "{" + LS
+ " \"srvcId\" : \"mod-users-5.0.0-bad-listening-port\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured3();
r = c.given().header("Content-Type", "application/json")
.body(doc2).post("/_/discovery/modules")
.then().statusCode(400).extract().response();
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
context.assertTrue(r.getBody().asString().contains("Could not connect to localhost:9234"),
"body is " + r.getBody().asString());
}
@Test
public void deployModUsers(TestContext context) {
org.junit.Assume.assumeTrue(haveDocker);
RestAssuredClient c;
Response r;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
final String docUserDockerModule = "{" + LS
+ " \"id\" : \"mod-users-5.0.0\"," + LS
+ " \"name\" : \"users\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"users\"," + LS
+ " \"version\" : \"1.0\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"pathPattern\" : \"/test\"," + LS
+ " \"permissionsRequired\" : [ ]" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"waitIterations\" : 10," + LS
+ " \"dockerImage\" : \"folioci/mod-users:5.0.0-SNAPSHOT\"," + LS
+ " \"dockerArgs\" : {" + LS
+ " \"HostConfig\": {" + LS
+ " \"PortBindings\": { \"8081/tcp\": [{ \"HostIp\": \"%c\", \"HostPort\": \"%p\" }] } }" + LS
+ " }" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured3();
c.given()
.header("Content-Type", "application/json")
.body(docUserDockerModule).post("/_/proxy/modules")
.then()
.statusCode(201);
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
final String doc2 = "{" + LS
+ " \"srvcId\" : \"mod-users-5.0.0\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured3();
r = c.given().header("Content-Type", "application/json")
.body(doc2).post("/_/discovery/modules")
.then().extract().response();
int statusCode = r.getStatusCode();
context.assertTrue(c.getLastReport().isEmpty(),
"raml: " + c.getLastReport().toString());
// Deal with port forwarding not working in Jenkins pipeline FOLIO-2404
String rBody = r.getBody().asString();
if (statusCode == 400) {
context.assertTrue(rBody.contains("Could not connect to localhost:9234")
|| rBody.contains("port is already allocated"), "body is " + rBody);
} else {
context.assertEquals(201, statusCode);
}
}
}
| |
/* RestrictedORB.java --
Copyright (C) 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.CORBA;
import gnu.CORBA.CDR.BufferedCdrOutput;
import gnu.CORBA.typecodes.AliasTypeCode;
import gnu.CORBA.typecodes.ArrayTypeCode;
import gnu.CORBA.typecodes.PrimitiveTypeCode;
import gnu.CORBA.typecodes.RecordTypeCode;
import gnu.CORBA.typecodes.StringTypeCode;
import org.omg.CORBA.Any;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.Context;
import org.omg.CORBA.ContextList;
import org.omg.CORBA.Environment;
import org.omg.CORBA.ExceptionList;
import org.omg.CORBA.NO_IMPLEMENT;
import org.omg.CORBA.NVList;
import org.omg.CORBA.NamedValue;
import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.CORBA.Request;
import org.omg.CORBA.StructMember;
import org.omg.CORBA.TCKind;
import org.omg.CORBA.TypeCode;
import org.omg.CORBA.TypeCodePackage.BadKind;
import org.omg.CORBA.UnionMember;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.ValueFactory;
import org.omg.PortableInterceptor.ClientRequestInterceptorOperations;
import org.omg.PortableInterceptor.IORInterceptorOperations;
import org.omg.PortableInterceptor.IORInterceptor_3_0Operations;
import org.omg.PortableInterceptor.ServerRequestInterceptorOperations;
import java.applet.Applet;
import java.util.Hashtable;
import java.util.Properties;
/**
* This class implements so-called Singleton ORB, a highly restricted version
* that cannot communicate over network. This ORB is provided for the
* potentially malicious applets with heavy security restrictions. It, however,
* supports some basic features that might be needed even when the network
* access is not granted.
*
* This ORB can only create typecodes, {@link Any}, {@link ContextList},
* {@link NVList} and {@link org.omg.CORBA.portable.OutputStream} that writes to
* an internal buffer.
*
* All other methods throw the {@link NO_IMPLEMENT} exception.
*
* @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
*/
public class OrbRestricted extends org.omg.CORBA_2_3.ORB
{
/**
* The singleton instance of this ORB.
*/
public static final ORB Singleton = new OrbRestricted();
/**
* The cumulated listener for all IOR interceptors. Interceptors are used by
* {@link gnu.CORBA.Poa.ORB_1_4}.
*/
public IORInterceptor_3_0Operations iIor;
/**
* The cumulated listener for all server request interceptors. Interceptors
* are used by {@link gnu.CORBA.Poa.ORB_1_4}.
*/
public ServerRequestInterceptorOperations iServer;
/**
* The cumulated listener for all client request interceptros. Interceptors
* are used by {@link gnu.CORBA.Poa.ORB_1_4}.
*/
public ClientRequestInterceptorOperations iClient;
/**
* The required size of the interceptor slot array.
*/
public int icSlotSize = 0;
/**
* The value factories.
*/
protected Hashtable factories = new Hashtable();
/**
* The policy factories.
*/
protected Hashtable policyFactories = new Hashtable();
/**
* Create a new instance of the RestrictedORB. This is used in derived classes
* only.
*/
protected OrbRestricted()
{
}
/** {@inheritDoc} */
public TypeCode create_alias_tc(String id, String name, TypeCode typecode)
{
return new AliasTypeCode(typecode, id, name);
}
/** {@inheritDoc} */
public Any create_any()
{
gnuAny any = new gnuAny();
any.setOrb(this);
return any;
}
/** {@inheritDoc} */
public TypeCode create_array_tc(int length, TypeCode element_type)
{
ArrayTypeCode p =
new ArrayTypeCode(TCKind.tk_array, element_type);
p.setLength(length);
return p;
}
/** {@inheritDoc} */
public ContextList create_context_list()
{
return new gnuContextList();
}
/** {@inheritDoc} */
public TypeCode create_enum_tc(String id, String name, String[] values)
{
RecordTypeCode r = new RecordTypeCode(TCKind.tk_enum);
for (int i = 0; i < values.length; i++)
{
r.field().name = values [ i ];
}
r.setId(id);
r.setName(name);
return r;
}
/** {@inheritDoc} */
public Environment create_environment()
{
return new gnuEnvironment();
}
/** {@inheritDoc} */
public ExceptionList create_exception_list()
{
return new gnuExceptionList();
}
/** {@inheritDoc} */
public TypeCode create_exception_tc(String id, String name,
StructMember[] members
)
{
RecordTypeCode r = new RecordTypeCode(TCKind.tk_except);
r.setId(id);
r.setName(name);
for (int i = 0; i < members.length; i++)
{
r.add(members [ i ]);
}
return r;
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public TypeCode create_interface_tc(String id, String name)
{
no();
return null;
}
/** {@inheritDoc} */
public NVList create_list(int count)
{
return new gnuNVList(count);
}
/** {@inheritDoc} */
public NamedValue create_named_value(String s, Any any, int flags)
{
return new gnuNamedValue();
}
/** {@inheritDoc} */
public OutputStream create_output_stream()
{
BufferedCdrOutput stream = new BufferedCdrOutput();
stream.setOrb(this);
return stream;
}
/** {@inheritDoc} */
public TypeCode create_sequence_tc(int bound, TypeCode element_type)
{
ArrayTypeCode p =
new ArrayTypeCode(TCKind.tk_sequence, element_type);
p.setLength(bound);
return p;
}
/** {@inheritDoc} */
public TypeCode create_string_tc(int bound)
{
StringTypeCode p = new StringTypeCode(TCKind.tk_string);
p.setLength(bound);
return p;
}
/** {@inheritDoc} */
public TypeCode create_struct_tc(String id, String name,
StructMember[] members
)
{
RecordTypeCode r = new RecordTypeCode(TCKind.tk_struct);
r.setId(id);
r.setName(name);
for (int i = 0; i < members.length; i++)
{
r.add(members [ i ]);
}
return r;
}
/** {@inheritDoc} */
public TypeCode create_union_tc(String id, String name,
TypeCode discriminator_type, UnionMember[] members
)
{
RecordTypeCode r = new RecordTypeCode(TCKind.tk_union);
r.setId(id);
r.setName(name);
r.setDiscriminator_type(discriminator_type);
r.setDefaultIndex(0);
for (int i = 0; i < members.length; i++)
{
r.add(members [ i ]);
}
return r;
}
/** {@inheritDoc} */
public TypeCode create_wstring_tc(int bound)
{
StringTypeCode p = new StringTypeCode(TCKind.tk_wstring);
p.setLength(bound);
return p;
}
/** {@inheritDoc} */
public TypeCode get_primitive_tc(TCKind tcKind)
{
try
{
return TypeKindNamer.getPrimitveTC(tcKind);
}
catch (BadKind ex)
{
throw new BAD_PARAM("This is not a primitive type code: " +
tcKind.value()
);
}
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public String[] list_initial_services()
{
no();
throw new InternalError();
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public String object_to_string(org.omg.CORBA.Object forObject)
{
no();
throw new InternalError();
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws InvalidName never in this class, but it is thrown in the derived
* classes.
*
* @throws NO_IMPLEMENT, always.
*/
public org.omg.CORBA.Object resolve_initial_references(String name)
throws InvalidName
{
no();
throw new InternalError();
}
/**
* Shutdown the ORB server.
*
* For RestrictedORB, returns witout action.
*/
public void run()
{
}
/**
* Shutdown the ORB server.
*
* For RestrictedORB, returns witout action.
*/
public void shutdown(boolean wait_for_completion)
{
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public org.omg.CORBA.Object string_to_object(String IOR)
{
no();
throw new InternalError();
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
protected void set_parameters(Applet app, Properties props)
{
no();
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
protected void set_parameters(String[] args, Properties props)
{
no();
}
/**
* Throws an exception, stating that the given method is not supported by the
* Restricted ORB.
*/
private final void no()
{
// Apart the programming errors, this can only happen if the
// malicious code is trying to do that it is not allowed.
throw new NO_IMPLEMENT("Use init(args, props) for the functional version.");
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public Request get_next_response() throws org.omg.CORBA.WrongTransaction
{
no();
throw new InternalError();
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public boolean poll_next_response()
{
no();
throw new InternalError();
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public void send_multiple_requests_deferred(Request[] requests)
{
no();
}
/**
* This method is not allowed for a RestrictedORB.
*
* @throws NO_IMPLEMENT, always.
*/
public void send_multiple_requests_oneway(Request[] requests)
{
no();
}
/**
* Register the value factory under the given repository id.
*/
public ValueFactory register_value_factory(String repository_id,
ValueFactory factory
)
{
factories.put(repository_id, factory);
return factory;
}
/**
* Unregister the value factroy.
*/
public void unregister_value_factory(String id)
{
factories.remove(id);
}
/**
* Look for the value factory for the value, having the given repository id.
* The implementation checks for the registered value factories first. If none
* found, it tries to load and instantiate the class, mathing the given naming
* convention. If this faild, null is returned.
*
* @param repository_id a repository id.
*
* @return a found value factory, null if none.
*/
public ValueFactory lookup_value_factory(String repository_id)
{
ValueFactory f = (ValueFactory) factories.get(repository_id);
if (f != null)
{
return f;
}
f = (ValueFactory) ObjectCreator.createObject(repository_id,
"DefaultFactory"
);
if (f != null)
{
factories.put(repository_id, f);
}
return f;
}
/**
* Destroy the interceptors, if they are present.
*/
public void destroy()
{
if (iIor != null)
{
iIor.destroy();
iIor = null;
}
if (iServer != null)
{
iServer.destroy();
iServer = null;
}
if (iClient != null)
{
iClient.destroy();
iClient = null;
}
super.destroy();
}
/**
* Create a typecode, representing a tree-like structure.
* This structure contains a member that is a sequence of the same type,
* as the structure itself. You can imagine as if the folder definition
* contains a variable-length array of the enclosed (nested) folder
* definitions. In this way, it is possible to have a tree like
* structure that can be transferred via CORBA CDR stream.
*
* @deprecated It is easier and clearler to use a combination of
* create_recursive_tc and create_sequence_tc instead.
*
* @param bound the maximal expected number of the nested components
* on each node; 0 if not limited.
*
* @param offset the position of the field in the returned structure
* that contains the sequence of the structures of the same field.
* The members before this field are intialised using parameterless
* StructMember constructor.
*
* @return a typecode, defining a stucture, where a member at the
* <code>offset</code> position defines an array of the identical
* structures.
*
* @see #create_recursive_tc(String)
* @see #create_sequence_tc(int, TypeCode)
*/
public TypeCode create_recursive_sequence_tc(int bound, int offset)
{
RecordTypeCode r = new RecordTypeCode(TCKind.tk_struct);
for (int i = 0; i < offset; i++)
r.add(new StructMember());
TypeCode recurs = new PrimitiveTypeCode(TCKind.tk_sequence);
r.add(new StructMember("", recurs, null));
return r;
}
/**
* Get the default context of this ORB. This is an initial root of all
* contexts.
*
* The default method returns a new context with the empty name and
* no parent context.
*
* @return the default context of this ORB.
*/
public Context get_default_context()
{
return new gnuContext("", null);
}
}
| |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2022, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package gen.lib.dotgen;
import static gen.lib.cgraph.edge__c.agfstedge;
import static gen.lib.cgraph.edge__c.agfstout;
import static gen.lib.cgraph.edge__c.aghead;
import static gen.lib.cgraph.edge__c.agnxtedge;
import static gen.lib.cgraph.edge__c.agnxtout;
import static gen.lib.cgraph.edge__c.agtail;
import static gen.lib.cgraph.node__c.agfstnode;
import static gen.lib.cgraph.node__c.agnxtnode;
import static gen.lib.cgraph.obj__c.agcontains;
import static gen.lib.cgraph.obj__c.agroot;
import static gen.lib.common.utils__c.UF_setname;
import static gen.lib.common.utils__c.UF_singleton;
import static gen.lib.dotgen.class2__c.class2;
import static gen.lib.dotgen.class2__c.merge_chain;
import static gen.lib.dotgen.class2__c.mergeable;
import static gen.lib.dotgen.dotinit__c.dot_root;
import static gen.lib.dotgen.fastgr__c.delete_fast_edge;
import static gen.lib.dotgen.fastgr__c.delete_fast_node;
import static gen.lib.dotgen.fastgr__c.fast_node;
import static gen.lib.dotgen.fastgr__c.find_fast_edge;
import static gen.lib.dotgen.fastgr__c.find_flat_edge;
import static gen.lib.dotgen.fastgr__c.flat_edge;
import static gen.lib.dotgen.fastgr__c.merge_oneway;
import static gen.lib.dotgen.fastgr__c.other_edge;
import static gen.lib.dotgen.fastgr__c.safe_other_edge;
import static gen.lib.dotgen.fastgr__c.virtual_edge;
import static gen.lib.dotgen.fastgr__c.virtual_node;
import static gen.lib.dotgen.mincross__c.allocate_ranks;
import static gen.lib.dotgen.mincross__c.build_ranks;
import static gen.lib.dotgen.mincross__c.enqueue_neighbors;
import static gen.lib.dotgen.mincross__c.install_in_rank;
import static gen.lib.dotgen.position__c.ports_eq;
import static smetana.core.JUtils.EQ;
import static smetana.core.JUtils.NEQ;
import static smetana.core.Macro.AGMKOUT;
import static smetana.core.Macro.CLUSTER;
import static smetana.core.Macro.CL_CROSS;
import static smetana.core.Macro.ED_count;
import static smetana.core.Macro.ED_edge_type;
import static smetana.core.Macro.ED_to_virt;
import static smetana.core.Macro.ED_xpenalty;
import static smetana.core.Macro.GD_clust;
import static smetana.core.Macro.GD_comp;
import static smetana.core.Macro.GD_expanded;
import static smetana.core.Macro.GD_installed;
import static smetana.core.Macro.GD_leader;
import static smetana.core.Macro.GD_maxrank;
import static smetana.core.Macro.GD_minrank;
import static smetana.core.Macro.GD_n_cluster;
import static smetana.core.Macro.GD_n_nodes;
import static smetana.core.Macro.GD_nlist;
import static smetana.core.Macro.GD_rank;
import static smetana.core.Macro.GD_rankleader;
import static smetana.core.Macro.ND_UF_size;
import static smetana.core.Macro.ND_clust;
import static smetana.core.Macro.ND_in;
import static smetana.core.Macro.ND_lw;
import static smetana.core.Macro.ND_node_type;
import static smetana.core.Macro.ND_order;
import static smetana.core.Macro.ND_out;
import static smetana.core.Macro.ND_rank;
import static smetana.core.Macro.ND_ranktype;
import static smetana.core.Macro.ND_rw;
import static smetana.core.Macro.NORMAL;
import static smetana.core.Macro.UNSUPPORTED;
import static smetana.core.Macro.VIRTUAL;
import static smetana.core.debug.SmetanaDebug.ENTERING;
import static smetana.core.debug.SmetanaDebug.LEAVING;
import gen.annotation.HasND_Rank;
import gen.annotation.Original;
import gen.annotation.Reviewed;
import gen.annotation.Unused;
import h.ST_Agedge_s;
import h.ST_Agnode_s;
import h.ST_Agraph_s;
import h.ST_nodequeue;
import smetana.core.CArrayOfStar;
public class cluster__c {
//3 8bd317q0mykfu6wpr3e4cxmh2
// static node_t* map_interclust_node(node_t * n)
@Unused
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="map_interclust_node", key="8bd317q0mykfu6wpr3e4cxmh2", definition="static node_t* map_interclust_node(node_t * n)")
public static ST_Agnode_s map_interclust_node(ST_Agnode_s n) {
ENTERING("8bd317q0mykfu6wpr3e4cxmh2","map_interclust_node");
try {
ST_Agnode_s rv;
if ((ND_clust(n) == null) || ( GD_expanded(ND_clust(n))) )
rv = n;
else
rv = GD_rankleader(ND_clust(n)).get_(ND_rank(n));
return rv;
} finally {
LEAVING("8bd317q0mykfu6wpr3e4cxmh2","map_interclust_node");
}
}
/* make d slots starting at position pos (where 1 already exists) */
@Reviewed(when = "15/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="make_slots", key="5ib4nnt2ah5fdd22zs0xds29r", definition="static void make_slots(graph_t * root, int r, int pos, int d)")
public static void make_slots(ST_Agraph_s root, int r, int pos, int d) {
ENTERING("5ib4nnt2ah5fdd22zs0xds29r","make_slots");
try {
int i;
ST_Agnode_s v;
CArrayOfStar<ST_Agnode_s> vlist;
vlist = GD_rank(root).get__(r).v;
if (d <= 0) {
for (i = pos - d + 1; i < GD_rank(root).get__(r).n; i++) {
v = vlist.get_(i);
ND_order(v, i + d - 1);
vlist.set_(ND_order(v), v);
}
for (i = GD_rank(root).get__(r).n + d - 1; i < GD_rank(root).get__(r).n; i++)
vlist.set_(i, null);
} else {
/*assert(ND_rank(root)[r].n + d - 1 <= ND_rank(root)[r].an);*/
for (i = GD_rank(root).get__(r).n - 1; i > pos; i--) {
v = vlist.get_(i);
ND_order(v, i + d - 1);
vlist.set_(ND_order(v), v);
}
for (i = pos + 1; i < pos + d; i++)
vlist.set_(i, null);
}
GD_rank(root).get__(r).n = GD_rank(root).get__(r).n + d - 1;
} finally {
LEAVING("5ib4nnt2ah5fdd22zs0xds29r","make_slots");
}
}
//3 d4mwxesl56uh9dyttg9cjlq70
// static node_t* clone_vn(graph_t * g, node_t * vn)
@Unused
@HasND_Rank
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="clone_vn", key="d4mwxesl56uh9dyttg9cjlq70", definition="static node_t* clone_vn(graph_t * g, node_t * vn)")
public static ST_Agnode_s clone_vn(ST_Agraph_s g, ST_Agnode_s vn) {
ENTERING("d4mwxesl56uh9dyttg9cjlq70","clone_vn");
try {
ST_Agnode_s rv;
int r;
r = ND_rank(vn);
make_slots(g, r, ND_order(vn), 2);
rv = virtual_node(g);
ND_lw(rv, ND_lw(vn));
ND_rw(rv, ND_rw(vn));
ND_rank(rv, ND_rank(vn));
UNSUPPORTED("adc0qfdhup29vh8qu1cwl5jgj"); // GD_rank(g)[r].v[ND_order(rv)] = rv;
UNSUPPORTED("v7vqc9l7ge2bfdwnw11z7rzi"); // return rv;
UNSUPPORTED("c24nfmv9i7o5eoqaymbibp7m7"); // }
throw new UnsupportedOperationException();
} finally {
LEAVING("d4mwxesl56uh9dyttg9cjlq70","clone_vn");
}
}
//3 6o86r59v2ujlxqcw7761y6o5b
// static void map_path(node_t * from, node_t * to, edge_t * orig, edge_t * ve, int type)
@Unused
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="map_path", key="6o86r59v2ujlxqcw7761y6o5b", definition="static void map_path(node_t * from, node_t * to, edge_t * orig, edge_t * ve, int type)")
public static void map_path(ST_Agnode_s from, ST_Agnode_s to, ST_Agedge_s orig, ST_Agedge_s ve, int type) {
ENTERING("6o86r59v2ujlxqcw7761y6o5b","map_path");
try {
int r;
ST_Agnode_s u, v;
ST_Agedge_s e;
assert(ND_rank(from) < ND_rank(to));
if (EQ(agtail(ve), from) && EQ(aghead(ve), to))
return;
if (ED_count(ve) > 1) {
ED_to_virt(orig, null);
if (ND_rank(to) - ND_rank(from) == 1) {
if ((e = find_fast_edge(from, to))!=null && (ports_eq(orig, e))) {
merge_oneway(orig, e);
if ((ND_node_type(from) == 0)
&& (ND_node_type(to) == 0))
other_edge(orig);
return;
}
}
u = from;
for (r = ND_rank(from); r < ND_rank(to); r++) {
if (r < ND_rank(to) - 1)
v = clone_vn(dot_root(from), aghead(ve));
else
v = to;
e = virtual_edge(u, v, orig);
ED_edge_type(e, type);
u = v;
ED_count(ve, ED_count(ve) - 1);
ve = (ST_Agedge_s) ND_out(aghead(ve)).list.get_(0);
}
} else {
if (ND_rank(to) - ND_rank(from) == 1) {
if ((ve = find_fast_edge(from, to))!=null && (ports_eq(orig, ve))) {
/*ED_to_orig(ve) = orig; */
ED_to_virt(orig, ve);
ED_edge_type(ve, type);
ED_count(ve, ED_count(ve)+1);
if ((ND_node_type(from) == 0)
&& (ND_node_type(to) == 0))
other_edge(orig);
} else {
ED_to_virt(orig, null);
ve = virtual_edge(from, to, orig);
ED_edge_type(ve, type);
}
}
if (ND_rank(to) - ND_rank(from) > 1) {
e = ve;
if (NEQ(agtail(ve), from)) {
ED_to_virt(orig, null);
e = virtual_edge(from, aghead(ve), orig);
ED_to_virt(orig, e);
delete_fast_edge(ve);
} else
e = ve;
while (ND_rank(aghead(e)) != ND_rank(to))
e = (ST_Agedge_s) ND_out(aghead(e)).list.get_(0);
if (NEQ(aghead(e), to)) {
ve = e;
e = virtual_edge(agtail(e), to, orig);
ED_edge_type(e, type);
delete_fast_edge(ve);
}
}
}
} finally {
LEAVING("6o86r59v2ujlxqcw7761y6o5b","map_path");
}
}
//3 69xbflgja0gvrsl5xcv7o7dia
// static void make_interclust_chain(graph_t * g, node_t * from, node_t * to, edge_t * orig)
@Unused
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="make_interclust_chain", key="69xbflgja0gvrsl5xcv7o7dia", definition="static void make_interclust_chain(graph_t * g, node_t * from, node_t * to, edge_t * orig)")
public static void make_interclust_chain(ST_Agraph_s g, ST_Agnode_s from, ST_Agnode_s to, ST_Agedge_s orig) {
ENTERING("69xbflgja0gvrsl5xcv7o7dia","make_interclust_chain");
try {
int newtype;
ST_Agnode_s u, v;
u = map_interclust_node(from);
v = map_interclust_node(to);
if (EQ(u, from) && EQ(v, to))
newtype = 1;
else
newtype = 5;
map_path(u, v, orig, ED_to_virt(orig), newtype);
} finally {
LEAVING("69xbflgja0gvrsl5xcv7o7dia","make_interclust_chain");
}
}
/*
* attach and install edges between clusters.
* essentially, class2() for interclust edges.
*/
@Unused
@Reviewed(when = "15/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="interclexp", key="6g2m2y44x66lajznvnon2gubv", definition="void interclexp(graph_t * subg)")
public static void interclexp(ST_Agraph_s subg) {
ENTERING("6g2m2y44x66lajznvnon2gubv","interclexp");
try {
ST_Agraph_s g;
ST_Agnode_s n;
ST_Agedge_s e, prev, next;
g = dot_root(subg);
for (n = agfstnode(subg); n!=null; n = agnxtnode(subg, n)) {
/* N.B. n may be in a sub-cluster of subg */
prev = null;
for (e = agfstedge(g, n); e!=null; e = next) {
next = agnxtedge(g, e, n);
if (agcontains(subg, e))
continue;
/* canonicalize edge */
e = AGMKOUT(e);
/* short/flat multi edges */
if (mergeable(prev, e)) {
if (ND_rank(agtail(e)) == ND_rank(aghead(e)))
ED_to_virt(e, prev);
else
ED_to_virt(e, null);
if (ED_to_virt(prev) == null)
continue; /* internal edge */
merge_chain(subg, e, ED_to_virt(prev), false);
safe_other_edge(e);
continue;
}
/* flat edges */
if (ND_rank(agtail(e)) == ND_rank(aghead(e))) {
ST_Agedge_s fe;
if ((fe = find_flat_edge(agtail(e), aghead(e))) == null) {
flat_edge(g, e);
prev = e;
} else if (NEQ(e, fe)) {
UNSUPPORTED("ckfinb4h4twp1ry02y9peyhz"); // safe_other_edge(e);
UNSUPPORTED("dg3e0udctqa7xtfynplc7wdpj"); // if (!ED_to_virt(e)) merge_oneway(e, fe);
}
continue;
}
/* forward edges */
if (ND_rank(aghead(e)) > ND_rank(agtail(e))) {
make_interclust_chain(g, agtail(e), aghead(e), e);
prev = e;
continue;
}
/* backward edges */
else {
/*
I think that make_interclust_chain should create call other_edge(e) anyway
if (agcontains(subg,agtail(e))
&& agfindedge(g,aghead(e),agtail(e))) other_edge(e);
*/
make_interclust_chain(g, aghead(e), agtail(e), e);
prev = e;
}
}
}
} finally {
LEAVING("6g2m2y44x66lajznvnon2gubv","interclexp");
}
}
@Unused
@Reviewed(when = "15/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="merge_ranks", key="85nhs7tnmwunw0fsjj1kxao7l", definition="static void merge_ranks(graph_t * subg)")
public static void merge_ranks(ST_Agraph_s subg) {
ENTERING("85nhs7tnmwunw0fsjj1kxao7l","merge_ranks");
try {
int i, d, r, pos, ipos;
ST_Agnode_s v;
ST_Agraph_s root;
root = dot_root(subg);
if (GD_minrank(subg) > 0)
GD_rank(root).get__(GD_minrank(subg) - 1).valid = 0;
for (r = GD_minrank(subg); r <= GD_maxrank(subg); r++) {
d = GD_rank(subg).get__(r).n;
ipos = pos = ND_order(GD_rankleader(subg).get_(r));
make_slots(root, r, pos, d);
for (i = 0; i < GD_rank(subg).get__(r).n; i++) {
v = GD_rank(subg).get__(r).v.get_(i);
GD_rank(root).get__(r).v.set_(pos, v);
ND_order(v, pos++);
/* real nodes automatically have v->root = root graph */
if (ND_node_type(v) == VIRTUAL)
v.root = agroot(root);
delete_fast_node(subg, v);
fast_node(root, v);
GD_n_nodes(root, GD_n_nodes(root)+1);
}
GD_rank(subg).get__(r).v = GD_rank(root).get__(r).v.plus_(ipos);
GD_rank(root).get__(r).valid = 0;
}
if (r < GD_maxrank(root))
GD_rank(root).get__(r).valid = 0;
GD_expanded(subg, true);
} finally {
LEAVING("85nhs7tnmwunw0fsjj1kxao7l","merge_ranks");
}
}
@Reviewed(when = "15/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="remove_rankleaders", key="c9p7dm16i13qktnh95os0sv58", definition="static void remove_rankleaders(graph_t * g)")
public static void remove_rankleaders(ST_Agraph_s g) {
ENTERING("c9p7dm16i13qktnh95os0sv58","remove_rankleaders");
try {
int r;
ST_Agnode_s v;
ST_Agedge_s e;
for (r = GD_minrank(g); r <= GD_maxrank(g); r++) {
v = GD_rankleader(g).get_(r);
/* remove the entire chain */
while ((e = (ST_Agedge_s) ND_out(v).list.get_(0))!=null)
delete_fast_edge(e);
while ((e = (ST_Agedge_s) ND_in(v).list.get_(0))!=null)
delete_fast_edge(e);
delete_fast_node(dot_root(g), v);
GD_rankleader(g).set_(r, null);
}
} finally {
LEAVING("c9p7dm16i13qktnh95os0sv58","remove_rankleaders");
}
}
/* delete virtual nodes of a cluster, and install real nodes or sub-clusters */
@Reviewed(when = "15/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="expand_cluster", key="ecrplg8hsyl484f9kxc5xp0go", definition="void expand_cluster(graph_t * subg)")
public static void expand_cluster(ST_Agraph_s subg) {
ENTERING("ecrplg8hsyl484f9kxc5xp0go","expand_cluster");
try {
/* build internal structure of the cluster */
class2(subg);
GD_comp(subg).size = 1;
GD_comp(subg).list.set_(0, GD_nlist(subg));
allocate_ranks(subg);
build_ranks(subg, 0);
merge_ranks(subg);
/* build external structure of the cluster */
interclexp(subg);
remove_rankleaders(subg);
} finally {
LEAVING("ecrplg8hsyl484f9kxc5xp0go","expand_cluster");
}
}
/* this function marks every node in <g> with its top-level cluster under <g> */
@Reviewed(when = "13/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="mark_clusters", key="cxuirggihlap2iv2khmb1w5l5", definition="void mark_clusters(graph_t * g)")
public static void mark_clusters(ST_Agraph_s g) {
ENTERING("cxuirggihlap2iv2khmb1w5l5","mark_clusters");
try {
int c;
ST_Agnode_s n, nn=null, vn;
ST_Agedge_s orig, e;
ST_Agraph_s clust;
/* remove sub-clusters below this level */
for (n = agfstnode(g); n!=null; n = agnxtnode(g, n)) {
if (ND_ranktype(n) == CLUSTER)
UF_singleton(n);
ND_clust(n, null);
}
for (c = 1; c <= GD_n_cluster(g); c++) {
clust = GD_clust(g).get_(c);
for (n = agfstnode(clust); n!=null; n = nn) {
nn = agnxtnode(clust,n);
if (ND_ranktype(n) != NORMAL) {
UNSUPPORTED("5l8jenkv77ax02t47zzxyv1k0"); // agerr(AGWARN,
UNSUPPORTED("2ipl4umxgijawr7756ysp9hhd"); // "%s was already in a rankset, deleted from cluster %s\n",
UNSUPPORTED("7r0ulsiau9cygesawzzjnpt5j"); // agnameof(n), agnameof(g));
UNSUPPORTED("4zqc8357rwnd9xe7zaoqooqv3"); // agdelete(clust,n);
UNSUPPORTED("6hyelvzskqfqa07xtgjtvg2is"); // continue;
}
UF_setname(n, GD_leader(clust));
ND_clust(n, clust);
ND_ranktype(n, CLUSTER);
/* here we mark the vnodes of edges in the cluster */
for (orig = agfstout(clust, n); orig!=null;
orig = agnxtout(clust, orig)) {
if ((e = ED_to_virt(orig))!=null) {
while (e!=null && ND_node_type(vn =aghead(e)) == VIRTUAL) {
ND_clust(vn, clust);
e = (ST_Agedge_s) ND_out(aghead(e)).list.get_(0);
/* trouble if concentrators and clusters are mixed */
}
}
}
}
}
} finally {
LEAVING("cxuirggihlap2iv2khmb1w5l5","mark_clusters");
}
}
@Reviewed(when = "15/11/2020")
@HasND_Rank
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="build_skeleton", key="bwrw5u0gi2rgah1cn9h0glpse", definition="void build_skeleton(graph_t * g, graph_t * subg)")
public static void build_skeleton(ST_Agraph_s g, ST_Agraph_s subg) {
ENTERING("bwrw5u0gi2rgah1cn9h0glpse","build_skeleton");
try {
int r;
ST_Agnode_s v, prev, rl;
ST_Agedge_s e;
prev = null;
GD_rankleader(subg, CArrayOfStar.<ST_Agnode_s>ALLOC(GD_maxrank(subg) + 2, ST_Agnode_s.class));
for (r = GD_minrank(subg); r <= GD_maxrank(subg); r++) {
v = virtual_node(g);
GD_rankleader(subg).set_(r, v);
ND_rank(v, r);
ND_ranktype(v, CLUSTER);
ND_clust(v, subg);
if (prev!=null) {
e = virtual_edge(prev, v, null);
ED_xpenalty(e, ED_xpenalty(e) * CL_CROSS);
}
prev = v;
}
/* set the counts on virtual edges of the cluster skeleton */
for (v = agfstnode(subg); v!=null; v = agnxtnode(subg, v)) {
rl = GD_rankleader(subg).get_(ND_rank(v));
ND_UF_size(rl, ND_UF_size(rl)+1);
for (e = agfstout(subg, v); e!=null; e = agnxtout(subg, e)) {
for (r = ND_rank(agtail(e)); r < ND_rank(aghead(e)); r++) {
ED_count(ND_out(rl).list.get_(0), ED_count(ND_out(rl).list.get_(0))+1);
}
}
}
for (r = GD_minrank(subg); r <= GD_maxrank(subg); r++) {
rl = GD_rankleader(subg).get_(r);
if (ND_UF_size(rl) > 1)
ND_UF_size(rl, ND_UF_size(rl)-1);
}
} finally {
LEAVING("bwrw5u0gi2rgah1cn9h0glpse","build_skeleton");
}
}
@Reviewed(when = "15/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="install_cluster", key="75yt3xwcwnxipi827t1r8zcmn", definition="void install_cluster(graph_t * g, node_t * n, int pass, nodequeue * q)")
public static void install_cluster(ST_Agraph_s g, ST_Agnode_s n, int pass, ST_nodequeue q) {
ENTERING("75yt3xwcwnxipi827t1r8zcmn","install_cluster");
try {
int r;
ST_Agraph_s clust;
clust = ND_clust(n);
if (GD_installed(clust) != pass + 1) {
for (r = GD_minrank(clust); r <= GD_maxrank(clust); r++)
install_in_rank(g, GD_rankleader(clust).get_(r));
for (r = GD_minrank(clust); r <= GD_maxrank(clust); r++)
enqueue_neighbors(q, GD_rankleader(clust).get_(r), pass);
GD_installed(clust, pass + 1);
}
} finally {
LEAVING("75yt3xwcwnxipi827t1r8zcmn","install_cluster");
}
}
@Reviewed(when = "15/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="mark_lowclusters", key="4muksvb3ec03mt6cvaqpb5c7a", definition="void mark_lowclusters(Agraph_t * root)")
public static void mark_lowclusters(ST_Agraph_s root) {
ENTERING("4muksvb3ec03mt6cvaqpb5c7a","mark_lowclusters");
try {
ST_Agnode_s n, vn;
ST_Agedge_s orig, e;
/* first, zap any previous cluster labelings */
for (n = agfstnode(root); n!=null; n = agnxtnode(root, n)) {
ND_clust(n, null);
for (orig = agfstout(root, n); orig!=null; orig = agnxtout(root, orig)) {
if ((e = ED_to_virt(orig))!=null) {
while (e!=null && (ND_node_type(vn = aghead(e))) == VIRTUAL) {
ND_clust(vn, null);
e = (ST_Agedge_s) ND_out(aghead(e)).list.get_(0);
}
}
}
}
/* do the recursion */
mark_lowcluster_basic(root);
} finally {
LEAVING("4muksvb3ec03mt6cvaqpb5c7a","mark_lowclusters");
}
}
@Reviewed(when = "16/11/2020")
@Original(version="2.38.0", path="lib/dotgen/cluster.c", name="mark_lowcluster_basic", key="48j6fdymvkcgeh4wde060ctac", definition="static void mark_lowcluster_basic(Agraph_t * g)")
public static void mark_lowcluster_basic(ST_Agraph_s g) {
ENTERING("48j6fdymvkcgeh4wde060ctac","mark_lowcluster_basic");
try {
ST_Agraph_s clust;
ST_Agnode_s n, vn;
ST_Agedge_s orig, e;
int c;
for (c = 1; c <= GD_n_cluster(g); c++) {
clust = GD_clust(g).get_(c);
mark_lowcluster_basic(clust);
}
/* see what belongs to this graph that wasn't already marked */
for (n = agfstnode(g); n!=null; n = agnxtnode(g, n)) {
if (ND_clust(n) == null)
ND_clust(n, g);
for (orig = agfstout(g, n); orig!=null; orig = agnxtout(g, orig)) {
if ((e = ED_to_virt(orig))!=null) {
while (e!=null && (ND_node_type(vn = aghead(e))) == VIRTUAL) {
if (ND_clust(vn) == null)
ND_clust(vn, g);
e = (ST_Agedge_s) ND_out(aghead(e)).list.get_(0);
}
}
}
}
} finally {
LEAVING("48j6fdymvkcgeh4wde060ctac","mark_lowcluster_basic");
}
}
}
| |
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* GreedyStepwise.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.attributeSelection;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Range;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> GreedyStepwise :<br/>
* <br/>
* Performs a greedy forward or backward search through the space of attribute
* subsets. May start with no/all attributes or from an arbitrary point in the
* space. Stops when the addition/deletion of any remaining attributes results
* in a decrease in evaluation. Can also produce a ranked list of attributes by
* traversing the space from one side to the other and recording the order that
* attributes are selected.<br/>
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C
* Use conservative forward search
* </pre>
*
* <pre>
* -B
* Use a backward search instead of a
* forward one.
* </pre>
*
* <pre>
* -P <start set>
* Specify a starting set of attributes.
* Eg. 1,3,5-7.
* </pre>
*
* <pre>
* -R
* Produce a ranked list of attributes.
* </pre>
*
* <pre>
* -T <threshold>
* Specify a theshold by which attributes
* may be discarded from the ranking.
* Use in conjuction with -R
* </pre>
*
* <pre>
* -N <num to select>
* Specify number of attributes to select
* </pre>
*
* <pre>
* -num-slots <int>
* The number of execution slots, for example, the number of cores in the CPU. (default 1)
* </pre>
*
* <pre>
* -D
* Print debugging output
* </pre>
*
* <!-- options-end -->
*
* @author Mark Hall
* @version $Revision: 10172 $
*/
public class GreedyStepwise extends ASSearch implements RankedOutputSearch,
StartSetHandler, OptionHandler {
/** for serialization */
static final long serialVersionUID = -6312951970168325471L;
/** does the data have a class */
protected boolean m_hasClass;
/** holds the class index */
protected int m_classIndex;
/** number of attributes in the data */
protected int m_numAttribs;
/** true if the user has requested a ranked list of attributes */
protected boolean m_rankingRequested;
/**
* go from one side of the search space to the other in order to generate a
* ranking
*/
protected boolean m_doRank;
/** used to indicate whether or not ranking has been performed */
protected boolean m_doneRanking;
/**
* A threshold by which to discard attributes---used by the AttributeSelection
* module
*/
protected double m_threshold;
/**
* The number of attributes to select. -1 indicates that all attributes are to
* be retained. Has precedence over m_threshold
*/
protected int m_numToSelect = -1;
protected int m_calculatedNumToSelect;
/** the merit of the best subset found */
protected double m_bestMerit;
/** a ranked list of attribute indexes */
protected double[][] m_rankedAtts;
protected int m_rankedSoFar;
/** the best subset found */
protected BitSet m_best_group;
protected ASEvaluation m_ASEval;
protected Instances m_Instances;
/** holds the start set for the search as a Range */
protected Range m_startRange;
/** holds an array of starting attributes */
protected int[] m_starting;
/** Use a backwards search instead of a forwards one */
protected boolean m_backward = false;
/**
* If set then attributes will continue to be added during a forward search as
* long as the merit does not degrade
*/
protected boolean m_conservativeSelection = false;
/** Print debugging output */
protected boolean m_debug = false;
protected int m_poolSize = 1;
/** Thread pool */
protected transient ExecutorService m_pool = null;
/**
* Constructor
*/
public GreedyStepwise() {
m_threshold = -Double.MAX_VALUE;
m_doneRanking = false;
m_startRange = new Range();
m_starting = null;
resetOptions();
}
/**
* Returns a string describing this search method
*
* @return a description of the search suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "GreedyStepwise :\n\nPerforms a greedy forward or backward search "
+ "through "
+ "the space of attribute subsets. May start with no/all attributes or from "
+ "an arbitrary point in the space. Stops when the addition/deletion of any "
+ "remaining attributes results in a decrease in evaluation. "
+ "Can also produce a ranked list of "
+ "attributes by traversing the space from one side to the other and "
+ "recording the order that attributes are selected.\n";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String searchBackwardsTipText() {
return "Search backwards rather than forwards.";
}
/**
* Set whether to search backwards instead of forwards
*
* @param back true to search backwards
*/
public void setSearchBackwards(boolean back) {
m_backward = back;
if (m_backward) {
setGenerateRanking(false);
}
}
/**
* Get whether to search backwards
*
* @return true if the search will proceed backwards
*/
public boolean getSearchBackwards() {
return m_backward;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String thresholdTipText() {
return "Set threshold by which attributes can be discarded. Default value "
+ "results in no attributes being discarded. Use in conjunction with "
+ "generateRanking";
}
/**
* Set the threshold by which the AttributeSelection module can discard
* attributes.
*
* @param threshold the threshold.
*/
@Override
public void setThreshold(double threshold) {
m_threshold = threshold;
}
/**
* Returns the threshold so that the AttributeSelection module can discard
* attributes from the ranking.
*/
@Override
public double getThreshold() {
return m_threshold;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numToSelectTipText() {
return "Specify the number of attributes to retain. The default value "
+ "(-1) indicates that all attributes are to be retained. Use either "
+ "this option or a threshold to reduce the attribute set.";
}
/**
* Specify the number of attributes to select from the ranked list (if
* generating a ranking). -1 indicates that all attributes are to be retained.
*
* @param n the number of attributes to retain
*/
@Override
public void setNumToSelect(int n) {
m_numToSelect = n;
}
/**
* Gets the number of attributes to be retained.
*
* @return the number of attributes to retain
*/
@Override
public int getNumToSelect() {
return m_numToSelect;
}
/**
* Gets the calculated number of attributes to retain. This is the actual
* number of attributes to retain. This is the same as getNumToSelect if the
* user specifies a number which is not less than zero. Otherwise it should be
* the number of attributes in the (potentially transformed) data.
*/
@Override
public int getCalculatedNumToSelect() {
if (m_numToSelect >= 0) {
m_calculatedNumToSelect = m_numToSelect;
}
return m_calculatedNumToSelect;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String generateRankingTipText() {
return "Set to true if a ranked list is required.";
}
/**
* Records whether the user has requested a ranked list of attributes.
*
* @param doRank true if ranking is requested
*/
@Override
public void setGenerateRanking(boolean doRank) {
m_rankingRequested = doRank;
}
/**
* Gets whether ranking has been requested. This is used by the
* AttributeSelection module to determine if rankedAttributes() should be
* called.
*
* @return true if ranking has been requested.
*/
@Override
public boolean getGenerateRanking() {
return m_rankingRequested;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String startSetTipText() {
return "Set the start point for the search. This is specified as a comma "
+ "seperated list off attribute indexes starting at 1. It can include "
+ "ranges. Eg. 1,2,5-9,17.";
}
/**
* Sets a starting set of attributes for the search. It is the search method's
* responsibility to report this start set (if any) in its toString() method.
*
* @param startSet a string containing a list of attributes (and or ranges),
* eg. 1,2,6,10-15.
* @throws Exception if start set can't be set.
*/
@Override
public void setStartSet(String startSet) throws Exception {
m_startRange.setRanges(startSet);
}
/**
* Returns a list of attributes (and or attribute ranges) as a String
*
* @return a list of attributes (and or attribute ranges)
*/
@Override
public String getStartSet() {
return m_startRange.getRanges();
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String conservativeForwardSelectionTipText() {
return "If true (and forward search is selected) then attributes "
+ "will continue to be added to the best subset as long as merit does "
+ "not degrade.";
}
/**
* Set whether attributes should continue to be added during a forward search
* as long as merit does not decrease
*
* @param c true if atts should continue to be atted
*/
public void setConservativeForwardSelection(boolean c) {
m_conservativeSelection = c;
}
/**
* Gets whether conservative selection has been enabled
*
* @return true if conservative forward selection is enabled
*/
public boolean getConservativeForwardSelection() {
return m_conservativeSelection;
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String debuggingOutputTipText() {
return "Output debugging information to the console";
}
/**
* Set whether to output debugging info to the console
*
* @param d true if dubugging info is to be output
*/
public void setDebuggingOutput(boolean d) {
m_debug = d;
}
/**
* Get whether to output debugging info to the console
*
* @return true if dubugging info is to be output
*/
public boolean getDebuggingOutput() {
return m_debug;
}
/**
* @return a string to describe the option
*/
public String numExecutionSlotsTipText() {
return "The number of execution slots, for example, the number of cores in the CPU.";
}
/**
* Gets the number of threads.
*/
public int getNumExecutionSlots() {
return m_poolSize;
}
/**
* Sets the number of threads
*/
public void setNumExecutionSlots(int nT) {
m_poolSize = nT;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
**/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>(8);
newVector.addElement(new Option("\tUse conservative forward search", "-C",
0, "-C"));
newVector.addElement(new Option("\tUse a backward search instead of a"
+ "\n\tforward one.", "-B", 0, "-B"));
newVector.addElement(new Option("\tSpecify a starting set of attributes."
+ "\n\tEg. 1,3,5-7.", "P", 1, "-P <start set>"));
newVector.addElement(new Option("\tProduce a ranked list of attributes.",
"R", 0, "-R"));
newVector.addElement(new Option("\tSpecify a theshold by which attributes"
+ "\n\tmay be discarded from the ranking."
+ "\n\tUse in conjuction with -R", "T", 1, "-T <threshold>"));
newVector.addElement(new Option("\tSpecify number of attributes to select",
"N", 1, "-N <num to select>"));
newVector.addElement(new Option("\t" + numExecutionSlotsTipText()
+ " (default 1)\n", "-num-slots", 1, "-num-slots <int>"));
newVector.addElement(new Option("\tPrint debugging output", "D", 0, "-D"));
return newVector.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C
* Use conservative forward search
* </pre>
*
* <pre>
* -B
* Use a backward search instead of a
* forward one.
* </pre>
*
* <pre>
* -P <start set>
* Specify a starting set of attributes.
* Eg. 1,3,5-7.
* </pre>
*
* <pre>
* -R
* Produce a ranked list of attributes.
* </pre>
*
* <pre>
* -T <threshold>
* Specify a theshold by which attributes
* may be discarded from the ranking.
* Use in conjuction with -R
* </pre>
*
* <pre>
* -N <num to select>
* Specify number of attributes to select
* </pre>
*
* <pre>
* -num-slots <int>
* The number of execution slots, for example, the number of cores in the CPU. (default 1)
* </pre>
*
* <pre>
* -D
* Print debugging output
* </pre>
*
* <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions(String[] options) throws Exception {
String optionString;
resetOptions();
setSearchBackwards(Utils.getFlag('B', options));
setConservativeForwardSelection(Utils.getFlag('C', options));
optionString = Utils.getOption('P', options);
if (optionString.length() != 0) {
setStartSet(optionString);
}
setGenerateRanking(Utils.getFlag('R', options));
optionString = Utils.getOption('T', options);
if (optionString.length() != 0) {
Double temp;
temp = Double.valueOf(optionString);
setThreshold(temp.doubleValue());
}
optionString = Utils.getOption('N', options);
if (optionString.length() != 0) {
setNumToSelect(Integer.parseInt(optionString));
}
optionString = Utils.getOption("num-slots", options);
if (optionString.length() > 0) {
setNumExecutionSlots(Integer.parseInt(optionString));
}
setDebuggingOutput(Utils.getFlag('D', options));
}
/**
* Gets the current settings of ReliefFAttributeEval.
*
* @return an array of strings suitable for passing to setOptions()
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (getSearchBackwards()) {
options.add("-B");
}
if (getConservativeForwardSelection()) {
options.add("-C");
}
if (!(getStartSet().equals(""))) {
options.add("-P");
options.add("" + startSetToString());
}
if (getGenerateRanking()) {
options.add("-R");
}
options.add("-T");
options.add("" + getThreshold());
options.add("-N");
options.add("" + getNumToSelect());
options.add("-num-slots");
options.add("" + getNumExecutionSlots());
if (getDebuggingOutput()) {
options.add("-D");
}
return options.toArray(new String[0]);
}
/**
* converts the array of starting attributes to a string. This is used by
* getOptions to return the actual attributes specified as the starting set.
* This is better than using m_startRanges.getRanges() as the same start set
* can be specified in different ways from the command line---eg 1,2,3 == 1-3.
* This is to ensure that stuff that is stored in a database is comparable.
*
* @return a comma seperated list of individual attribute numbers as a String
*/
protected String startSetToString() {
StringBuffer FString = new StringBuffer();
boolean didPrint;
if (m_starting == null) {
return getStartSet();
}
for (int i = 0; i < m_starting.length; i++) {
didPrint = false;
if ((m_hasClass == false) || (m_hasClass == true && i != m_classIndex)) {
FString.append((m_starting[i] + 1));
didPrint = true;
}
if (i == (m_starting.length - 1)) {
FString.append("");
} else {
if (didPrint) {
FString.append(",");
}
}
}
return FString.toString();
}
/**
* returns a description of the search.
*
* @return a description of the search as a String.
*/
@Override
public String toString() {
StringBuffer FString = new StringBuffer();
FString.append("\tGreedy Stepwise ("
+ ((m_backward) ? "backwards)" : "forwards)") + ".\n\tStart set: ");
if (m_starting == null) {
if (m_backward) {
FString.append("all attributes\n");
} else {
FString.append("no attributes\n");
}
} else {
FString.append(startSetToString() + "\n");
}
if (!m_doneRanking) {
FString.append("\tMerit of best subset found: "
+ Utils.doubleToString(Math.abs(m_bestMerit), 8, 3) + "\n");
} else {
if (m_backward) {
FString
.append("\n\tRanking is the order that attributes were removed, "
+ "starting \n\twith all attributes. The merit scores in the left"
+ "\n\tcolumn are the goodness of the remaining attributes in the"
+ "\n\tsubset after removing the corresponding in the right column"
+ "\n\tattribute from the subset.\n");
} else {
FString
.append("\n\tRanking is the order that attributes were added, starting "
+ "\n\twith no attributes. The merit scores in the left column"
+ "\n\tare the goodness of the subset after the adding the"
+ "\n\tcorresponding attribute in the right column to the subset.\n");
}
}
if ((m_threshold != -Double.MAX_VALUE) && (m_doneRanking)) {
FString.append("\tThreshold for discarding attributes: "
+ Utils.doubleToString(m_threshold, 8, 4) + "\n");
}
return FString.toString();
}
/**
* Searches the attribute subset space by forward selection.
*
* @param ASEval the attribute evaluator to guide the search
* @param data the training instances.
* @return an array (not necessarily ordered) of selected attribute indexes
* @throws Exception if the search can't be completed
*/
@Override
public int[] search(ASEvaluation ASEval, Instances data) throws Exception {
int i;
double best_merit = -Double.MAX_VALUE;
double temp_best, temp_merit;
int temp_index = 0;
BitSet temp_group;
boolean parallel = (m_poolSize > 1);
if (parallel) {
m_pool = Executors.newFixedThreadPool(m_poolSize);
}
if (data != null) { // this is a fresh run so reset
resetOptions();
m_Instances = data;
}
m_ASEval = ASEval;
m_numAttribs = m_Instances.numAttributes();
if (m_best_group == null) {
m_best_group = new BitSet(m_numAttribs);
}
if (!(m_ASEval instanceof SubsetEvaluator)) {
throw new Exception(m_ASEval.getClass().getName() + " is not a "
+ "Subset evaluator!");
}
m_startRange.setUpper(m_numAttribs - 1);
if (!(getStartSet().equals(""))) {
m_starting = m_startRange.getSelection();
}
if (m_ASEval instanceof UnsupervisedSubsetEvaluator) {
m_hasClass = false;
m_classIndex = -1;
} else {
m_hasClass = true;
m_classIndex = m_Instances.classIndex();
}
final SubsetEvaluator ASEvaluator = (SubsetEvaluator) m_ASEval;
if (m_rankedAtts == null) {
m_rankedAtts = new double[m_numAttribs][2];
m_rankedSoFar = 0;
}
// If a starting subset has been supplied, then initialise the bitset
if (m_starting != null && m_rankedSoFar <= 0) {
for (i = 0; i < m_starting.length; i++) {
if ((m_starting[i]) != m_classIndex) {
m_best_group.set(m_starting[i]);
}
}
} else {
if (m_backward && m_rankedSoFar <= 0) {
for (i = 0; i < m_numAttribs; i++) {
if (i != m_classIndex) {
m_best_group.set(i);
}
}
}
}
// Evaluate the initial subset
best_merit = ASEvaluator.evaluateSubset(m_best_group);
// main search loop
boolean done = false;
boolean addone = false;
boolean z;
if (m_debug && parallel) {
System.err.println("Evaluating subsets in parallel...");
}
while (!done) {
List<Future<Double[]>> results = new ArrayList<Future<Double[]>>();
temp_group = (BitSet) m_best_group.clone();
temp_best = best_merit;
if (m_doRank) {
temp_best = -Double.MAX_VALUE;
}
done = true;
addone = false;
for (i = 0; i < m_numAttribs; i++) {
if (m_backward) {
z = ((i != m_classIndex) && (temp_group.get(i)));
} else {
z = ((i != m_classIndex) && (!temp_group.get(i)));
}
if (z) {
// set/unset the bit
if (m_backward) {
temp_group.clear(i);
} else {
temp_group.set(i);
}
if (parallel) {
final BitSet tempCopy = (BitSet) temp_group.clone();
final int attBeingEvaluated = i;
// make a copy if the evaluator is not thread safe
final SubsetEvaluator theEvaluator = (ASEvaluator instanceof weka.core.ThreadSafe) ? ASEvaluator
: (SubsetEvaluator) ASEvaluation.makeCopies(m_ASEval, 1)[0];
Future<Double[]> future = m_pool.submit(new Callable<Double[]>() {
@Override
public Double[] call() throws Exception {
Double[] r = new Double[2];
double e = theEvaluator.evaluateSubset(tempCopy);
r[0] = new Double(attBeingEvaluated);
r[1] = e;
return r;
}
});
results.add(future);
} else {
temp_merit = ASEvaluator.evaluateSubset(temp_group);
if (m_backward) {
z = (temp_merit >= temp_best);
} else {
if (m_conservativeSelection) {
z = (temp_merit >= temp_best);
} else {
z = (temp_merit > temp_best);
}
}
if (z) {
temp_best = temp_merit;
temp_index = i;
addone = true;
done = false;
}
}
// unset this addition/deletion
if (m_backward) {
temp_group.set(i);
} else {
temp_group.clear(i);
}
if (m_doRank) {
done = false;
}
}
}
if (parallel) {
for (int j = 0; j < results.size(); j++) {
Future<Double[]> f = results.get(j);
int index = f.get()[0].intValue();
temp_merit = f.get()[1].doubleValue();
if (m_backward) {
z = (temp_merit >= temp_best);
} else {
if (m_conservativeSelection) {
z = (temp_merit >= temp_best);
} else {
z = (temp_merit > temp_best);
}
}
if (z) {
temp_best = temp_merit;
temp_index = index;
addone = true;
done = false;
}
}
}
if (addone) {
if (m_backward) {
m_best_group.clear(temp_index);
} else {
m_best_group.set(temp_index);
}
best_merit = temp_best;
if (m_debug) {
System.err.print("Best subset found so far: ");
int[] atts = attributeList(m_best_group);
for (int a : atts) {
System.err.print("" + (a + 1) + " ");
}
System.err.println("\nMerit: " + best_merit);
}
m_rankedAtts[m_rankedSoFar][0] = temp_index;
m_rankedAtts[m_rankedSoFar][1] = best_merit;
m_rankedSoFar++;
}
}
if (parallel) {
m_pool.shutdown();
}
m_bestMerit = best_merit;
return attributeList(m_best_group);
}
/**
* Produces a ranked list of attributes. Search must have been performed prior
* to calling this function. Search is called by this function to complete the
* traversal of the the search space. A list of attributes and merits are
* returned. The attributes a ranked by the order they are added to the subset
* during a forward selection search. Individual merit values reflect the
* merit associated with adding the corresponding attribute to the subset;
* because of this, merit values may initially increase but then decrease as
* the best subset is "passed by" on the way to the far side of the search
* space.
*
* @return an array of attribute indexes and associated merit values
* @throws Exception if something goes wrong.
*/
@Override
public double[][] rankedAttributes() throws Exception {
if (m_rankedAtts == null || m_rankedSoFar == -1) {
throw new Exception("Search must be performed before attributes "
+ "can be ranked.");
}
m_doRank = true;
search(m_ASEval, null);
double[][] final_rank = new double[m_rankedSoFar][2];
for (int i = 0; i < m_rankedSoFar; i++) {
final_rank[i][0] = m_rankedAtts[i][0];
final_rank[i][1] = m_rankedAtts[i][1];
}
resetOptions();
m_doneRanking = true;
if (m_numToSelect > final_rank.length) {
throw new Exception("More attributes requested than exist in the data");
}
if (m_numToSelect <= 0) {
if (m_threshold == -Double.MAX_VALUE) {
m_calculatedNumToSelect = final_rank.length;
} else {
determineNumToSelectFromThreshold(final_rank);
}
}
return final_rank;
}
private void determineNumToSelectFromThreshold(double[][] ranking) {
int count = 0;
for (double[] element : ranking) {
if (element[1] > m_threshold) {
count++;
}
}
m_calculatedNumToSelect = count;
}
/**
* converts a BitSet into a list of attribute indexes
*
* @param group the BitSet to convert
* @return an array of attribute indexes
**/
protected int[] attributeList(BitSet group) {
int count = 0;
// count how many were selected
for (int i = 0; i < m_numAttribs; i++) {
if (group.get(i)) {
count++;
}
}
int[] list = new int[count];
count = 0;
for (int i = 0; i < m_numAttribs; i++) {
if (group.get(i)) {
list[count++] = i;
}
}
return list;
}
/**
* Resets options
*/
protected void resetOptions() {
m_doRank = false;
m_best_group = null;
m_ASEval = null;
m_Instances = null;
m_rankedSoFar = -1;
m_rankedAtts = null;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 10172 $");
}
}
| |
/*--------------------------------------------------------------------------
* Copyright 2008 utgenome.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
//--------------------------------------
// utgb-core Project
//
// UTGBEntryPointBase.java
// Since: Jun 2, 2008
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.gwt.utgb.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.*;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import org.utgenome.gwt.utgb.client.track.*;
import org.utgenome.gwt.utgb.client.ui.RoundCornerFrame;
import org.utgenome.gwt.utgb.client.util.BrowserInfo;
import org.utgenome.gwt.utgb.client.util.Properties;
import org.utgenome.gwt.utgb.client.util.StringUtil;
import org.utgenome.gwt.utgb.client.view.TrackView;
import org.utgenome.gwt.widget.client.Style;
import java.util.ArrayList;
import java.util.HashMap;
public class UTGBEntryPointBase implements EntryPoint {
// widgets
private final DockPanel basePanel = new DockPanel();
private final TrackGroup trackGroup = new TrackGroup("root");
private TrackGroup mainGroup;
private final TrackQueue trackQueue = new TrackQueue(trackGroup);
private HashMap<String, String> queryParam = new HashMap<String, String>();
public TrackGroup getTrackGroup() {
return trackGroup;
}
public TrackQueue getTrackQueue() {
return trackQueue;
}
public DockPanel getBasePanel() {
return basePanel;
}
/**
* Defines keyboard shortcuts
*
* @author leo
*
*/
public class KeyboardShortcut implements Event.NativePreviewHandler {
public void onPreviewNativeEvent(NativePreviewEvent event) {
// handle shortcut keys
int type = event.getTypeInt();
int keyCode = event.getNativeEvent().getKeyCode();
switch (type) {
case Event.ONKEYDOWN:
EventTarget eventTarget = event.getNativeEvent().getEventTarget();
if (Element.is(eventTarget)) {
Element e = eventTarget.cast();
String tagName = e.getTagName();
// disable keyboard short cuts on the input form (text area, etc.)
if (tagName.equalsIgnoreCase("input"))
break;
// Also ignore keyboard input, ALT+(key)
if (event.getNativeEvent().getAltKey())
break;
double scrollPercentage = 20.0;
if (event.getNativeEvent().getShiftKey())
scrollPercentage = 25.0;
switch (keyCode) {
case KeyCodes.KEY_RIGHT:
trackGroup.getPropertyWriter().scrollTrackWindow(scrollPercentage);
event.getNativeEvent().preventDefault();
break;
case KeyCodes.KEY_LEFT:
trackGroup.getPropertyWriter().scrollTrackWindow(-scrollPercentage);
event.getNativeEvent().preventDefault();
break;
case KeyCodes.KEY_UP:
trackGroup.getPropertyWriter().scaleUpTrackWindow();
event.getNativeEvent().preventDefault();
break;
case KeyCodes.KEY_DOWN:
trackGroup.getPropertyWriter().scaleDownTrackWindow();
event.getNativeEvent().preventDefault();
break;
}
}
break;
}
}
}
public void onModuleLoad() {
RPCServiceManager.initServices();
queryParam = BrowserInfo.getURLQueryRequestParameters();
RootPanel.get().setStyleName("utgb");
basePanel.add(trackQueue, DockPanel.CENTER);
History.addValueChangeHandler(new HistoryChangeHandler());
Event.addNativePreviewHandler(new KeyboardShortcut());
// add window size change listener
Window.addResizeHandler(new ResizeHandler() {
public void onResize(ResizeEvent e) {
adjustTrackWidth();
}
});
// invoke main method
main();
if (BrowserInfo.isIE()) {
showErrorMessage("IE does not support canvas feature in HTML5 for drawing grpahics in the browser, so we strongly recommend you to use another browser supporting HTML5, e.g., Google Chrome, Firefox, Safari, Opera, etc.");
}
}
public static int computeTrackWidth() {
RootPanel rootPanel = RootPanel.get("utgb-main");
int newBrowserWidth = rootPanel.getOffsetWidth(); // Window.getClientWidth();
return Math.max((int) (newBrowserWidth * 0.95) - TrackFrame.INFOPANEL_WIDTH, 150);
}
private void adjustTrackWidth() {
int newTrackWidth = computeTrackWidth();
for (TrackGroup g : trackGroup.getTrackGroupList()) {
g.setTrackWindowWidth(newTrackWidth);
}
}
public void displayTrackView() {
// load a view
if (queryParam.containsKey("view")) {
loadView(queryParam.get("view"));
}
else {
loadView("default-view");
}
RootPanel rootPanel = RootPanel.get("utgb-main");
if (rootPanel != null) {
rootPanel.add(basePanel);
}
else {
RootPanel.get().add(new Label("Error: <div id=\"utgb-main\"></div> tag is not found in this HTML file."));
}
}
/**
* load the view XML file from the public/view folder.
*
* @param viewName
*/
public void loadView(String viewName) {
RPCServiceManager.getRPCService().getTrackView(viewName, new AsyncCallback<TrackView>() {
public void onFailure(Throwable e) {
showErrorMessage("failed to load view: " + e.getMessage());
}
public void onSuccess(TrackView v) {
try {
mainGroup = TrackGroup.createTrackGroup(v);
// apply the URL query parameters
String hash = BrowserInfo.getHash();
if (hash != null && hash.length() > 0)
hash = hash.substring(1);
setQueryParam(mainGroup, hash);
trackGroup.addTrackGroup(mainGroup);
mainGroup.addTrackGroupPropertyChangeListener(new URLRewriter(mainGroup));
}
catch (UTGBClientException e) {
showErrorMessage("failed to load view: " + e.getMessage());
GWT.log(e.getMessage(), e);
}
}
});
}
private static class URLRewriter implements TrackGroupPropertyChangeListener {
public final TrackGroup group;
public URLRewriter(TrackGroup group) {
this.group = group;
}
public void onChange(TrackGroupPropertyChange change, TrackWindow newWindow) {
if (newWindow != null || (change != null && change.containsOneOf(UTGBProperty.coordinateParameters)))
setBrowserURL();
}
public void setBrowserURL() {
ArrayList<String> prop = new ArrayList<String>();
TrackGroupProperty propertyReader = group.getPropertyReader();
TrackWindow w = group.getTrackWindow();
prop.add("start=" + w.getStartOnGenome());
prop.add("end=" + w.getEndOnGenome());
//prop.add("width=" + w.getWindowWidth());
for (String key : propertyReader.keySet()) {
prop.add(key + "=" + propertyReader.getProperty(key));
}
String n = StringUtil.join(prop, ";");
String prev = History.getToken();
if (prev != null && prev.equals(n))
return;
else {
History.newItem(n, false);
String s = propertyReader.getProperty(UTGBProperty.TARGET) + ":" + w.getStartOnGenome() + "-" + w.getEndOnGenome();
Window.setTitle(s + " - UTGB");
}
}
}
private class HistoryChangeHandler implements ValueChangeHandler<String> {
public HistoryChangeHandler() {
}
public void onValueChange(ValueChangeEvent<String> e) {
if (mainGroup != null)
setQueryParam(mainGroup, e.getValue());
}
}
private static void setQueryParam(TrackGroup group, String queryParam) {
TrackWindow w = group.getTrackWindow();
Properties p = getProperties(queryParam);
if (p.containsKey("start")) {
int start = Integer.parseInt(p.get("start"));
int end = p.containsKey("end") ? Integer.parseInt(p.get("end")) : start + 1000;
w = w.newWindow(start, end);
}
p.remove("start");
p.remove("end");
group.getPropertyWriter().setProperty(p, w);
}
private static Properties getProperties(String query) {
Properties properties = new Properties();
if (query == null || query.length() < 1)
return properties;
String[] keyAndValue = query.split(";");
for (int i = 0; i < keyAndValue.length; i++) {
String[] kv = keyAndValue[i].split("=");
if (kv.length > 1)
properties.put(kv[0], BrowserInfo.unescape(kv[1]));
else
properties.put(kv[0], "");
}
return properties;
}
public void main() {
displayTrackView();
}
private static RoundCornerFrame errorFrame;
private static Label errorLabel = new Label();
private static PopupPanel errorPopup = new PopupPanel(true);
{
errorFrame = new RoundCornerFrame("FF6699", 0.7f, 2);
errorFrame.setWidth("400px");
errorFrame.setWidgetPanel(errorLabel);
Style.fontColor(errorLabel, "white");
errorPopup.setWidget(errorFrame);
}
public static void showErrorMessage(final String message) {
Scheduler.get().scheduleDeferred( new Command() {
public void execute() {
errorLabel.setText(message);
int x = Window.getClientWidth() / 2 - 200;
int y = 10;
errorPopup.setPopupPosition(x, y);
errorPopup.show();
}
});
}
public static void hideLoadingMessage() {
Element _loadingMessage = DOM.getElementById("loading");
if (_loadingMessage != null) {
RootPanel.setVisible(_loadingMessage, false);
}
}
public static void showLoadingMessage() {
Element _loadingMessage = DOM.getElementById("loading");
if (_loadingMessage != null) {
RootPanel.setVisible(_loadingMessage, true);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dataformat.bindy;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.camel.CamelContext;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.DataField;
import org.apache.camel.dataformat.bindy.annotation.FixedLengthRecord;
import org.apache.camel.dataformat.bindy.annotation.Link;
import org.apache.camel.dataformat.bindy.format.FormatException;
import org.apache.camel.dataformat.bindy.util.ConverterUtils;
import org.apache.camel.support.ObjectHelper;
import org.apache.camel.util.ReflectionHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The BindyCsvFactory is the class who allows to : Generate a model associated
* to a fixed length record, bind data from a record to the POJOs, export data of POJOs
* to a fixed length record and format data into String, Date, Double, ... according to
* the format/pattern defined
*/
public class BindyFixedLengthFactory extends BindyAbstractFactory implements BindyFactory {
private static final Logger LOG = LoggerFactory.getLogger(BindyFixedLengthFactory.class);
boolean isOneToMany;
private Map<Integer, DataField> dataFields = new TreeMap<>();
private Map<Integer, Field> annotatedFields = new TreeMap<>();
private int numberOptionalFields;
private int numberMandatoryFields;
private int totalFields;
private boolean hasHeader;
private boolean skipHeader;
private boolean isHeader;
private boolean hasFooter;
private boolean skipFooter;
private boolean isFooter;
private char paddingChar;
private int recordLength;
private boolean ignoreTrailingChars;
private boolean ignoreMissingChars;
private boolean countGrapheme;
private Class<?> header;
private Class<?> footer;
public BindyFixedLengthFactory(Class<?> type) throws Exception {
super(type);
header = void.class;
footer = void.class;
// initialize specific parameters of the fixed length model
initFixedLengthModel();
}
/**
* method uses to initialize the model representing the classes who will
* bind the data. This process will scan for classes according to the
* package name provided, check the annotated classes and fields
*/
public void initFixedLengthModel() throws Exception {
// Find annotated fields declared in the Model classes
initAnnotatedFields();
// initialize Fixed length parameter(s)
// from @FixedLengthrecord annotation
initFixedLengthRecordParameters();
}
@Override
public void initAnnotatedFields() {
for (Class<?> cl : models) {
List<Field> linkFields = new ArrayList<>();
if (LOG.isDebugEnabled()) {
LOG.debug("Class retrieved: {}", cl.getName());
}
for (Field field : cl.getDeclaredFields()) {
DataField dataField = field.getAnnotation(DataField.class);
if (dataField != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Position defined in the class: {}, position: {}, Field: {}", cl.getName(), dataField.pos(), dataField);
}
if (dataField.required()) {
++numberMandatoryFields;
} else {
++numberOptionalFields;
}
dataFields.put(dataField.pos(), dataField);
annotatedFields.put(dataField.pos(), field);
}
Link linkField = field.getAnnotation(Link.class);
if (linkField != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Class linked: {}, Field: {}", cl.getName(), field);
}
linkFields.add(field);
}
}
if (!linkFields.isEmpty()) {
annotatedLinkFields.put(cl.getName(), linkFields);
}
totalFields = numberMandatoryFields + numberOptionalFields;
if (LOG.isDebugEnabled()) {
LOG.debug("Number of optional fields: {}", numberOptionalFields);
LOG.debug("Number of mandatory fields: {}", numberMandatoryFields);
LOG.debug("Total: {}", totalFields);
}
}
}
// Will not be used in the case of a Fixed Length record
// as we provide the content of the record and
// we don't split it as this is the case for a CSV record
@Override
public void bind(CamelContext camelContext, List<String> data, Map<String, Object> model, int line) throws Exception {
// noop
}
public void bind(CamelContext camelContext, String recordStr, Map<String, Object> model, int line) throws Exception {
int pos = 1;
int counterMandatoryFields = 0;
DataField dataField;
String token;
int offset = 1;
int length;
String delimiter;
Field field;
final UnicodeHelper record = new UnicodeHelper(recordStr, (this.countGrapheme) ? UnicodeHelper.Method.GRAPHEME : UnicodeHelper.Method.CODEPOINTS);
// Iterate through the list of positions
// defined in the @DataField
// and grab the data from the line
Collection<DataField> c = dataFields.values();
Iterator<DataField> itr = c.iterator();
// this iterator is for a link list that was built using items in order
while (itr.hasNext()) {
dataField = itr.next();
length = dataField.length();
delimiter = dataField.delimiter();
if (length == 0 && dataField.lengthPos() != 0) {
Field lengthField = annotatedFields.get(dataField.lengthPos());
lengthField.setAccessible(true);
Object modelObj = model.get(lengthField.getDeclaringClass().getName());
Object lengthObj = lengthField.get(modelObj);
length = ((Integer)lengthObj).intValue();
}
if (length < 1 && delimiter == null && dataField.lengthPos() == 0) {
throw new IllegalArgumentException("Either length or delimiter must be specified for the field : " + dataField.toString());
}
if (offset - 1 <= -1) {
throw new IllegalArgumentException("Offset/Position of the field " + dataField.toString()
+ " cannot be negative");
}
// skip ahead if the expected position is greater than the offset
if (dataField.pos() > offset) {
LOG.debug("skipping ahead [{}] chars.", dataField.pos() - offset);
offset = dataField.pos();
}
if (length > 0) {
if (record.length() < offset) {
token = "";
} else {
int endIndex = offset + length - 1;
if (endIndex > record.length()) {
endIndex = record.length();
}
token = record.substring(offset - 1, endIndex);
}
offset += length;
} else if (!delimiter.equals("")) {
final UnicodeHelper tempToken = new UnicodeHelper(record.substring(offset - 1, record.length()), (this.countGrapheme) ? UnicodeHelper.Method.GRAPHEME : UnicodeHelper.Method.CODEPOINTS);
token = tempToken.substring(0, tempToken.indexOf(delimiter));
// include the delimiter in the offset calculation
offset += token.length() + 1;
} else {
// defined as a zero-length field
token = "";
}
if (dataField.trim()) {
token = trim(token, dataField, paddingChar);
//token = token.trim();
}
// Check mandatory field
if (dataField.required()) {
// Increment counter of mandatory fields
++counterMandatoryFields;
// Check if content of the field is empty
// This is not possible for mandatory fields
if (token.equals("")) {
throw new IllegalArgumentException("The mandatory field defined at the position " + pos
+ " is empty for the line: " + line);
}
}
// Get Field to be set
field = annotatedFields.get(dataField.pos());
field.setAccessible(true);
if (LOG.isDebugEnabled()) {
LOG.debug("Pos/Offset: {}, Data: {}, Field type: {}", offset, token, field.getType());
}
// Create format object to format the field
FormattingOptions formattingOptions = ConverterUtils.convert(dataField,
field.getType(),
field.getAnnotation(BindyConverter.class),
getLocale());
Format<?> format = formatFactory.getFormat(formattingOptions);
// field object to be set
Object modelField = model.get(field.getDeclaringClass().getName());
// format the data received
Object value = null;
if ("".equals(token)) {
token = dataField.defaultValue();
}
if (!"".equals(token)) {
try {
value = format.parse(token);
} catch (FormatException ie) {
throw new IllegalArgumentException(ie.getMessage() + ", position: " + offset + ", line: " + line, ie);
} catch (Exception e) {
throw new IllegalArgumentException("Parsing error detected for field defined at the position/offset: " + offset + ", line: " + line, e);
}
} else {
value = getDefaultValueForPrimitive(field.getType());
}
if (value != null && !dataField.method().isEmpty()) {
Class<?> clazz;
if (dataField.method().contains(".")) {
clazz = camelContext.getClassResolver().resolveMandatoryClass(dataField.method().substring(0, dataField.method().lastIndexOf(".")));
} else {
clazz = field.getType();
}
String methodName = dataField.method().substring(dataField.method().lastIndexOf(".") + 1,
dataField.method().length());
Method m = ReflectionHelper.findMethod(clazz, methodName, field.getType());
if (m != null) {
// this method must be static and return type
// must be the same as the datafield and
// must receive only the datafield value
// as the method argument
value = ObjectHelper.invokeMethod(m, null, value);
} else {
// fallback to method without parameter, that is on the value itself
m = ReflectionHelper.findMethod(clazz, methodName);
value = ObjectHelper.invokeMethod(m, value);
}
}
field.set(modelField, value);
++pos;
}
// check for unmapped non-whitespace data at the end of the line
if (offset <= record.length() && !(record.substring(offset - 1, record.length())).trim().equals("") && !isIgnoreTrailingChars()) {
throw new IllegalArgumentException("Unexpected / unmapped characters found at the end of the fixed-length record at line : " + line);
}
LOG.debug("Counter mandatory fields: {}", counterMandatoryFields);
if (pos < totalFields) {
throw new IllegalArgumentException("Some fields are missing (optional or mandatory), line: " + line);
}
if (counterMandatoryFields < numberMandatoryFields) {
throw new IllegalArgumentException("Some mandatory fields are missing, line: " + line);
}
}
private String trim(String token, DataField dataField, char paddingChar) {
char myPaddingChar = dataField.paddingChar();
if (dataField.paddingChar() == 0) {
myPaddingChar = paddingChar;
}
if ("R".equals(dataField.align())) {
return leftTrim(token, myPaddingChar);
} else if ("L".equals(dataField.align())) {
return rightTrim(token, myPaddingChar);
} else {
token = leftTrim(token, myPaddingChar);
return rightTrim(token, myPaddingChar);
}
}
private String rightTrim(String token, char myPaddingChar) {
StringBuilder sb = new StringBuilder(token);
while (sb.length() > 0 && myPaddingChar == sb.charAt(sb.length() - 1)) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
private String leftTrim(String token, char myPaddingChar) {
StringBuilder sb = new StringBuilder(token);
while (sb.length() > 0 && myPaddingChar == (sb.charAt(0))) {
sb.deleteCharAt(0);
}
return sb.toString();
}
@Override
public String unbind(CamelContext camelContext, Map<String, Object> model) throws Exception {
StringBuilder buffer = new StringBuilder();
Map<Integer, List<String>> results = new HashMap<>();
for (Class<?> clazz : models) {
if (model.containsKey(clazz.getName())) {
Object obj = model.get(clazz.getName());
if (LOG.isDebugEnabled()) {
LOG.debug("Model object: {}, class: {}", obj, obj.getClass().getName());
}
if (obj != null) {
// Generate Fixed Length table
// containing the positions of the fields
generateFixedLengthPositionMap(clazz, obj, results);
}
}
}
// Convert Map<Integer, List> into List<List>
Map<Integer, List<String>> sortValues = new TreeMap<>(results);
for (Entry<Integer, List<String>> entry : sortValues.entrySet()) {
// Get list of values
List<String> val = entry.getValue();
String value = val.get(0);
buffer.append(value);
}
return buffer.toString();
}
/**
*
* Generate a table containing the data formatted and sorted with their position/offset
* The result is placed in the Map<Integer, List> results
*/
private void generateFixedLengthPositionMap(Class<?> clazz, Object obj, Map<Integer, List<String>> results) throws Exception {
String result = "";
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
DataField datafield = field.getAnnotation(DataField.class);
if (datafield != null) {
if (obj != null) {
// Create format
FormattingOptions formattingOptions = ConverterUtils.convert(datafield,
field.getType(),
field.getAnnotation(BindyConverter.class),
getLocale());
Format<?> format = formatFactory.getFormat(formattingOptions);
// Get field value
Object value = field.get(obj);
// If the field value is empty, populate it with the default value
if (org.apache.camel.util.ObjectHelper.isNotEmpty(datafield.defaultValue()) && org.apache.camel.util.ObjectHelper.isEmpty(value)) {
value = datafield.defaultValue();
}
result = formatString(format, value);
// trim if enabled
if (datafield.trim()) {
result = result.trim();
}
int fieldLength = datafield.length();
if (fieldLength == 0 && (datafield.lengthPos() > 0)) {
List<String> resultVals = results.get(datafield.lengthPos());
fieldLength = Integer.valueOf(resultVals.get(0));
}
if (fieldLength <= 0 && datafield.delimiter().equals("") && datafield.lengthPos() == 0) {
throw new IllegalArgumentException("Either a delimiter value or length for the field: "
+ field.getName() + " is mandatory.");
}
if (!datafield.delimiter().equals("")) {
result = result + datafield.delimiter();
} else {
// Get length of the field, alignment (LEFT or RIGHT), pad
String align = datafield.align();
char padCharField = datafield.paddingChar();
char padChar;
StringBuilder temp = new StringBuilder();
// Check if we must pad
if (result.length() < fieldLength) {
// No padding defined for the field
if (padCharField == 0) {
// We use the padding defined for the Record
padChar = paddingChar;
} else {
padChar = padCharField;
}
if (align.contains("R")) {
temp.append(generatePaddingChars(padChar, fieldLength, result.length()));
temp.append(result);
} else if (align.contains("L")) {
temp.append(result);
temp.append(generatePaddingChars(padChar, fieldLength, result.length()));
} else if (align.contains("B")) {
temp.append(generatePaddingChars(padChar, fieldLength, result.length()));
temp.append(result);
} else {
throw new IllegalArgumentException("Alignment for the field: " + field.getName()
+ " must be equal to R for RIGHT or L for LEFT or B for trimming both ends");
}
result = temp.toString();
} else if (result.length() > fieldLength) {
// we are bigger than allowed
// is clipped enabled? if so clip the field
if (datafield.clip()) {
result = result.substring(0, fieldLength);
} else {
throw new IllegalArgumentException("Length for the " + field.getName()
+ " must not be larger than allowed, was: " + result.length() + ", allowed: " + fieldLength);
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Value to be formatted: {}, position: {}, and its formatted value: {}", value, datafield.pos(), result);
}
} else {
result = "";
}
Integer key;
key = datafield.pos();
if (!results.containsKey(key)) {
List<String> list = new LinkedList<>();
list.add(result);
results.put(key, list);
} else {
List<String> list = results.get(key);
list.add(result);
}
}
}
}
private String generatePaddingChars(char pad, int lengthField, int lengthString) {
StringBuilder buffer = new StringBuilder();
int size = lengthField - lengthString;
for (int i = 0; i < size; i++) {
buffer.append(Character.toString(pad));
}
return buffer.toString();
}
/**
* Get parameters defined in @FixedLengthRecord annotation
*/
private void initFixedLengthRecordParameters() {
for (Class<?> cl : models) {
// Get annotation @FixedLengthRecord from the class
FixedLengthRecord record = cl.getAnnotation(FixedLengthRecord.class);
if (record != null) {
LOG.debug("Fixed length record: {}", record);
// Get carriage return parameter
crlf = record.crlf();
LOG.debug("Carriage return defined for the CSV: {}", crlf);
eol = record.eol();
LOG.debug("EOL(end-of-line) defined for the CSV: {}", eol);
// Get header parameter
header = record.header();
LOG.debug("Header: {}", header);
hasHeader = header != void.class;
LOG.debug("Has Header: {}", hasHeader);
// Get skipHeader parameter
skipHeader = record.skipHeader();
LOG.debug("Skip Header: {}", skipHeader);
// Get footer parameter
footer = record.footer();
LOG.debug("Footer: {}", footer);
hasFooter = record.footer() != void.class;
LOG.debug("Has Footer: {}", hasFooter);
// Get skipFooter parameter
skipFooter = record.skipFooter();
LOG.debug("Skip Footer: {}", skipFooter);
// Get isHeader parameter
isHeader = hasHeader ? cl.equals(header) : false;
LOG.debug("Is Header: {}", isHeader);
// Get isFooter parameter
isFooter = hasFooter ? cl.equals(footer) : false;
LOG.debug("Is Footer: {}", isFooter);
// Get padding character
paddingChar = record.paddingChar();
LOG.debug("Padding char: {}", paddingChar);
// Get length of the record
recordLength = record.length();
LOG.debug("Length of the record: {}", recordLength);
// Get flag for ignore trailing characters
ignoreTrailingChars = record.ignoreTrailingChars();
LOG.debug("Ignore trailing chars: {}", ignoreTrailingChars);
ignoreMissingChars = record.ignoreMissingChars();
LOG.debug("Enable ignore missing chars: {}", ignoreMissingChars);
countGrapheme = record.countGrapheme();
LOG.debug("Enable grapheme counting instead of codepoints: {}", countGrapheme);
}
}
if (hasHeader && isHeader) {
throw new java.lang.IllegalArgumentException("Record can not be configured with both 'isHeader=true' and 'hasHeader=true'");
}
if (hasFooter && isFooter) {
throw new java.lang.IllegalArgumentException("Record can not be configured with both 'isFooter=true' and 'hasFooter=true'");
}
if ((isHeader || isFooter) && (skipHeader || skipFooter)) {
throw new java.lang.IllegalArgumentException(
"skipHeader and/or skipFooter can not be configured on a record where 'isHeader=true' or 'isFooter=true'");
}
}
/**
* Gets the type of the header record.
*
* @return The type of the header record if any, otherwise
* <code>void.class</code>.
*/
public Class<?> header() {
return header;
}
/**
* Flag indicating if we have a header
*/
public boolean hasHeader() {
return hasHeader;
}
/**
* Gets the type of the footer record.
*
* @return The type of the footer record if any, otherwise
* <code>void.class</code>.
*/
public Class<?> footer() {
return footer;
}
/**
* Flag indicating if we have a footer
*/
public boolean hasFooter() {
return hasFooter;
}
/**
* Flag indicating whether to skip the header parsing
*/
public boolean skipHeader() {
return skipHeader;
}
/**
* Flag indicating whether to skip the footer processing
*/
public boolean skipFooter() {
return skipFooter;
}
/**
* Flag indicating whether this factory is for a header
*/
public boolean isHeader() {
return isHeader;
}
/**
* Flag indicating whether this factory is for a footer
*/
public boolean isFooter() {
return isFooter;
}
/**
* Padding char used to fill the field
*/
public char paddingchar() {
return paddingChar;
}
/**
* Expected fixed length of the record
*/
public int recordLength() {
return recordLength;
}
/**
* Flag indicating whether trailing characters beyond the last declared field may be ignored
*/
public boolean isIgnoreTrailingChars() {
return this.ignoreTrailingChars;
}
/**
* Flag indicating whether too short lines are ignored
*/
public boolean isIgnoreMissingChars() {
return ignoreMissingChars;
}
/**
* Flag indicating whether graphemes or codepoints are counted.
*/
public boolean isCountGrapheme() {
return countGrapheme;
}
}
| |
package vrp.mip;
import gurobi.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* Created by Leo on 08/12/2016.
*/
@Data
@AllArgsConstructor
public class SolverVRP {
@NonNull private List<Truck> trucks;
@NonNull private Facility facility;
@NonNull private List<Customer> customers;
@NonNull private List<Local> locals;
private static int TIME_LIMIT_SECONDS = 200;
public Double getDistance(Local i, Local j) {
double x1 = i.getX();
double y1 = i.getY();
double x2 = j.getX();
double y2 = j.getY();
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
public void solve() {
try {
// Create Model
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env);
model.set(GRB.StringAttr.ModelName, "vrp");
//Add objectiveExpression
Objective objective = new Objective(model).addObjective();
GRBVar[][] x = objective.getX();
GRBVar[][][] t = objective.getT();
GRBVar[] u = objective.getU();
//Add constraints
new Constraints(model, t, x, u).addConstraints();
//Configure solver
model.getEnv().set(GRB.IntParam.Method, GRB.METHOD_BARRIER); // Use barrier to solve root relaxation
model.getEnv().set(GRB.IntParam.OutputFlag, 1); // Disable gurobi logs
model.getEnv().set(GRB.DoubleParam.TimeLimit, TIME_LIMIT_SECONDS); //Define time limit optimization
// model.setCallback(new VRPCallBack(x, u));
model.optimize();
model.write("VRP.lp"); //Used to print model in a file
// Print solution
// model.computeIIS(); //Used to debug solution infeasible
//model.write("VRP.ilp"); //Used to IIS in a file
printSolution(model, t, x, u);
double[][][] vars = model.get(GRB.DoubleAttr.X, t);
for (int ti = 0; ti < trucks.size(); ti++) {
System.out.println("\n\n" + ti);
int[] findsubtour = VRPCallBack.findsubtour(vars[ti]);
for (int i = 0; i < findsubtour.length; i++) {
System.out.print(findsubtour[i] + " ");
}
}
//debugSolution(model, amountDelivered, amountDelivered);
// Dispose of model and environment
model.dispose();
env.dispose();
} catch (GRBException e) {
System.out.println("Error code: " + e.getErrorCode() + ". " +
e.getMessage());
}
}
private void printSolution(GRBModel model, GRBVar[][][] t, GRBVar[][] x, GRBVar[] u) throws GRBException {
Tour tour = new Tour();
for (int i = 0; i < locals.size(); i++) {
for (int j = 0; j < locals.size(); j++) {
for (int ti = 0; ti < trucks.size(); ti++) {
if (t[ti][i][j].get(GRB.DoubleAttr.X) > 0.5) {
if (!tour.getTourByTruck().containsKey(ti)) {
tour.getTourByTruck().put(ti, new ArrayList<>());
}
tour.getTourByTruck().get(ti).add(i+"->"+j);
}
}
}
}
System.out.println("Trucks");
for (int ti = 0; ti < trucks.size(); ti++) {
System.out.print("\n" + ti);
for (int i = 0; i < locals.size(); i++) {
System.out.println();
for (int j = 0; j < locals.size(); j++) {
Integer v = (int) t[ti][i][j].get(GRB.DoubleAttr.X);
System.out.print(v + " ");
}
}
}
System.out.println("\nRoutes");
for (int i = 0; i < locals.size(); i++) {
System.out.println();
for (int j = 0; j < locals.size(); j++) {
Integer v = (int) x[i][j].get(GRB.DoubleAttr.X);
System.out.print(v + " ");
}
}
System.out.println();
for (Map.Entry<Integer, List<String>> tourByTrc: tour.getTourByTruck().entrySet()) {
System.out.print("\n"+tourByTrc.getKey() + ": ");
for (String j : tourByTrc.getValue()) {
System.out.print(j + ", ");
}
}
}
@Data
private class Objective {
private GRBModel model;
private GRBVar[][][] t; // route i->j is used by truck tw
private GRBVar[][] x; // route i->j is used
private GRBVar[] u; //(shipment for client i)
private GRBVar[] v; //(shipment for client i)
public Objective(GRBModel model) {
this.model = model;
}
public Objective addObjective() throws GRBException {
t = new GRBVar[trucks.size()][locals.size()][locals.size()];
x = new GRBVar[locals.size()][locals.size()];
for (int i = 0; i < locals.size(); ++i) {
for (int j = 0; j < locals.size(); j++) {
x[i][j] = model.addVar(0, 1, 1, GRB.BINARY, "x_"+i+"_"+j);
for (int ti = 0; ti < trucks.size(); ti++) {
t[ti][i][j] = model.addVar(0, 1, getDistance(locals.get(i), locals.get(j)), GRB.BINARY, "t_"+i+"_"+j+"_"+ti);
}
}
}
u = new GRBVar[customers.size()];
for (int i = 0; i < customers.size(); i++) {
u[i] = model.addVar(customers.get(i).getDemand(), trucks.get(0).getCapacity(), 1, GRB.CONTINUOUS, "u_"+i);
}
u = new GRBVar[customers.size()];
for (int i = 0; i < customers.size(); i++) {
u[i] = model.addVar(customers.get(i).getDemand(), trucks.get(0).getCapacity(), 1, GRB.CONTINUOUS, "u_"+i);
}
model.update();
// Forbid edge from node back to itself
for (int ti = 0; ti < trucks.size(); ti++)
for (int i = 0; i < locals.size(); i++)
t[ti][i][i].set(GRB.DoubleAttr.UB, 0.0);
for (int i = 0; i < locals.size(); i++)
x[i][i].set(GRB.DoubleAttr.UB, 0.0);
model.update();
// The objectiveExpression is to minimize the total fixed and variable costs
model.set(GRB.IntAttr.ModelSense, GRB.MINIMIZE);
return this;
}
}
@Data
@AllArgsConstructor
private class Constraints {
private GRBModel model;
private GRBVar[][][] t; // truck tw is used on route (i,j)
private GRBVar[][] x; // route (i->j) is used
private GRBVar[] u; //(shipment for client i)
private GRBVar[] V; //(shipment for client i)
public void addConstraints() throws GRBException {
// The loading capacity of each vehicle cannot be exceeded
for (int ti = 0; ti < trucks.size(); ti++) {
GRBLinExpr tot = new GRBLinExpr();
for (int i = 1; i <= customers.size(); i++) {
for (int j = 0; j < locals.size(); j++) {
tot.addTerm(customers.get(i-1).getDemand(), t[ti][i][j]);
}
}
model.addConstr(tot, GRB.LESS_EQUAL, trucks.get(ti).getCapacity(), "C1_"+ti);
}
//The route i->j can be traveled by at most one vehicle
for (int i = 0; i < locals.size(); i++) {
for (int j = 0; j < locals.size(); j++) {
GRBLinExpr totVehicleOnRoute = new GRBLinExpr();
for (int ti = 0; ti < trucks.size(); ti++) {
totVehicleOnRoute.addTerm(1, t[ti][i][j]);
}
model.addConstr(totVehicleOnRoute, GRB.EQUAL, x[i][j], "C2_" + i + "_" + j);
}
}
// The customer must be visited excactly once
for (int i=1; i <= customers.size(); i++) {
GRBLinExpr totVisitOncustomer = new GRBLinExpr();
for (int j = 0; j < locals.size(); j++) {
totVisitOncustomer.addTerm(1, x[i][j]);
}
model.addConstr(totVisitOncustomer, GRB.EQUAL, 1, "C3_"+i);
}
// The customer must be visited excactly once
for (int j= 1; j <= customers.size(); j++) {
GRBLinExpr totVisitOncustomer = new GRBLinExpr();
for (int i = 0; i < locals.size(); i++) {
totVisitOncustomer.addTerm(1, x[i][j]);
}
model.addConstr(totVisitOncustomer, GRB.EQUAL, 1, "C4_"+j);
}
//A vehicle must start at facility
GRBLinExpr totStartVehicle = new GRBLinExpr();
for (int j = 1; j <= customers.size(); j++) {
totStartVehicle.addTerm(1, x[0][j]);
}
model.addConstr(totStartVehicle, GRB.LESS_EQUAL, trucks.size(), "C5");
//A vehicle must end at facility
GRBLinExpr totEndVehicle = new GRBLinExpr();
for (int i = 1; i <= customers.size(); i++) {
totEndVehicle.addTerm(1, x[i][0]);
}
model.addConstr(totEndVehicle, GRB.LESS_EQUAL, trucks.size(), "C6");
// A vehicle that reaches a customer must leave the same customer
for (int i = 1; i < customers.size(); i++) {
for (int ti = 0; ti < trucks.size(); ti++) {
GRBLinExpr totIn = new GRBLinExpr();
for (int j = 0; j < locals.size(); j++) {
totIn.addTerm(1, t[ti][i][j]);
totIn.addTerm(-1, t[ti][j][i]);
}
model.addConstr(totIn, GRB.EQUAL, 0, "C8_"+i+"_"+ti);
}
}
for (int ti = 0; ti < trucks.size(); ti++) {
for (int i = 1; i <= customers.size(); i++) {
GRBLinExpr exp1 = new GRBLinExpr();
exp1.addTerm(customers.get(i - 1).getDemand() - trucks.get(0).getCapacity(), t[ti][0][i]);
exp1.addConstant(trucks.get(0).getCapacity());
model.addConstr(u[i - 1], GRB.LESS_EQUAL, exp1, "C9_" + ti+"_"+i);
}
}
for (int ti = 0; ti < trucks.size(); ti++) {
for (int i = 1; i <= customers.size(); i++) {
for (int j = 1; j <= customers.size(); j++) {
if (i != j) {
GRBLinExpr exp1 = new GRBLinExpr();
exp1.addTerm(1, u[i - 1]);
exp1.addTerm(-1, u[j - 1]);
exp1.addTerm(trucks.get(0).getCapacity(), t[ti][i][j]);
model.addConstr(exp1, GRB.LESS_EQUAL, trucks.get(0).getCapacity() - customers.get(j - 1).getDemand(), "C10_" +ti+"_"+ i + "_" + j);
}
}
}
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.config.Config.DiskFailurePolicy;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.Directories.DataDirectory;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.io.FSWriteError;
import static org.junit.Assert.*;
public class DirectoriesTest
{
private static File tempDataDir;
private static final String KS = "ks";
private static final String[] TABLES = new String[] { "cf1", "ks" };
private static final Set<CFMetaData> CFM = new HashSet<>(TABLES.length);
private static Map<String, List<File>> files = new HashMap<String, List<File>>();
@BeforeClass
public static void beforeClass() throws IOException
{
for (String table : TABLES)
{
UUID tableID = CFMetaData.generateLegacyCfId(KS, table);
CFM.add(CFMetaData.Builder.create(KS, table)
.withId(tableID)
.addPartitionKey("thekey", UTF8Type.instance)
.addClusteringColumn("thecolumn", UTF8Type.instance)
.build());
}
tempDataDir = File.createTempFile("cassandra", "unittest");
tempDataDir.delete(); // hack to create a temp dir
tempDataDir.mkdir();
Directories.overrideDataDirectoriesForTest(tempDataDir.getPath());
// Create two fake data dir for tests, one using CF directories, one that do not.
createTestFiles();
}
@AfterClass
public static void afterClass()
{
Directories.resetDataDirectoriesAfterTest();
FileUtils.deleteRecursive(tempDataDir);
}
private static void createTestFiles() throws IOException
{
for (CFMetaData cfm : CFM)
{
List<File> fs = new ArrayList<>();
files.put(cfm.cfName, fs);
File dir = cfDir(cfm);
dir.mkdirs();
createFakeSSTable(dir, cfm.cfName, 1, false, fs);
createFakeSSTable(dir, cfm.cfName, 2, true, fs);
File backupDir = new File(dir, Directories.BACKUPS_SUBDIR);
backupDir.mkdir();
createFakeSSTable(backupDir, cfm.cfName, 1, false, fs);
File snapshotDir = new File(dir, Directories.SNAPSHOT_SUBDIR + File.separator + "42");
snapshotDir.mkdirs();
createFakeSSTable(snapshotDir, cfm.cfName, 1, false, fs);
}
}
private static void createFakeSSTable(File dir, String cf, int gen, boolean temp, List<File> addTo) throws IOException
{
Descriptor desc = new Descriptor(dir, KS, cf, gen, temp ? Descriptor.Type.TEMP : Descriptor.Type.FINAL);
for (Component c : new Component[]{ Component.DATA, Component.PRIMARY_INDEX, Component.FILTER })
{
File f = new File(desc.filenameFor(c));
f.createNewFile();
addTo.add(f);
}
}
private static File cfDir(CFMetaData metadata)
{
String cfId = ByteBufferUtil.bytesToHex(ByteBufferUtil.bytes(metadata.cfId));
return new File(tempDataDir, metadata.ksName + File.separator + metadata.cfName + "-" + cfId);
}
@Test
public void testStandardDirs()
{
for (CFMetaData cfm : CFM)
{
Directories directories = new Directories(cfm);
assertEquals(cfDir(cfm), directories.getDirectoryForNewSSTables());
Descriptor desc = new Descriptor(cfDir(cfm), KS, cfm.cfName, 1, Descriptor.Type.FINAL);
File snapshotDir = new File(cfDir(cfm), File.separator + Directories.SNAPSHOT_SUBDIR + File.separator + "42");
assertEquals(snapshotDir, Directories.getSnapshotDirectory(desc, "42"));
File backupsDir = new File(cfDir(cfm), File.separator + Directories.BACKUPS_SUBDIR);
assertEquals(backupsDir, Directories.getBackupsDirectory(desc));
}
}
@Test
public void testSSTableLister()
{
for (CFMetaData cfm : CFM)
{
Directories directories = new Directories(cfm);
Directories.SSTableLister lister;
Set<File> listed;
// List all but no snapshot, backup
lister = directories.sstableLister();
listed = new HashSet<>(lister.listFiles());
for (File f : files.get(cfm.cfName))
{
if (f.getPath().contains(Directories.SNAPSHOT_SUBDIR) || f.getPath().contains(Directories.BACKUPS_SUBDIR))
assert !listed.contains(f) : f + " should not be listed";
else
assert listed.contains(f) : f + " is missing";
}
// List all but including backup (but no snapshot)
lister = directories.sstableLister().includeBackups(true);
listed = new HashSet<>(lister.listFiles());
for (File f : files.get(cfm.cfName))
{
if (f.getPath().contains(Directories.SNAPSHOT_SUBDIR))
assert !listed.contains(f) : f + " should not be listed";
else
assert listed.contains(f) : f + " is missing";
}
// Skip temporary and compacted
lister = directories.sstableLister().skipTemporary(true);
listed = new HashSet<>(lister.listFiles());
for (File f : files.get(cfm.cfName))
{
if (f.getPath().contains(Directories.SNAPSHOT_SUBDIR) || f.getPath().contains(Directories.BACKUPS_SUBDIR))
assert !listed.contains(f) : f + " should not be listed";
else if (f.getName().contains("tmp-"))
assert !listed.contains(f) : f + " should not be listed";
else
assert listed.contains(f) : f + " is missing";
}
}
}
@Test
public void testDiskFailurePolicy_best_effort()
{
DiskFailurePolicy origPolicy = DatabaseDescriptor.getDiskFailurePolicy();
try
{
DatabaseDescriptor.setDiskFailurePolicy(DiskFailurePolicy.best_effort);
// Fake a Directory creation failure
if (Directories.dataDirectories.length > 0)
{
String[] path = new String[] {KS, "bad"};
File dir = new File(Directories.dataDirectories[0].location, StringUtils.join(path, File.separator));
FileUtils.handleFSError(new FSWriteError(new IOException("Unable to create directory " + dir), dir));
}
for (DataDirectory dd : Directories.dataDirectories)
{
File file = new File(dd.location, new File(KS, "bad").getPath());
assertTrue(BlacklistedDirectories.isUnwritable(file));
}
}
finally
{
DatabaseDescriptor.setDiskFailurePolicy(origPolicy);
}
}
@Test
public void testMTSnapshots() throws Exception
{
for (final CFMetaData cfm : CFM)
{
final Directories directories = new Directories(cfm);
assertEquals(cfDir(cfm), directories.getDirectoryForNewSSTables());
final String n = Long.toString(System.nanoTime());
Callable<File> directoryGetter = new Callable<File>() {
public File call() throws Exception {
Descriptor desc = new Descriptor(cfDir(cfm), KS, cfm.cfName, 1, Descriptor.Type.FINAL);
return Directories.getSnapshotDirectory(desc, n);
}
};
List<Future<File>> invoked = Executors.newFixedThreadPool(2).invokeAll(Arrays.asList(directoryGetter, directoryGetter));
for(Future<File> fut:invoked) {
assertTrue(fut.get().exists());
}
}
}
@Test
public void testDiskFreeSpace()
{
DataDirectory[] dataDirectories = new DataDirectory[]
{
new DataDirectory(new File("/nearlyFullDir1"))
{
public long getAvailableSpace()
{
return 11L;
}
},
new DataDirectory(new File("/nearlyFullDir2"))
{
public long getAvailableSpace()
{
return 10L;
}
},
new DataDirectory(new File("/uniformDir1"))
{
public long getAvailableSpace()
{
return 1000L;
}
},
new DataDirectory(new File("/uniformDir2"))
{
public long getAvailableSpace()
{
return 999L;
}
},
new DataDirectory(new File("/veryFullDir"))
{
public long getAvailableSpace()
{
return 4L;
}
}
};
// directories should be sorted
// 1. by their free space ratio
// before weighted random is applied
List<Directories.DataDirectoryCandidate> candidates = getWriteableDirectories(dataDirectories, 0L);
assertSame(dataDirectories[2], candidates.get(0).dataDirectory); // available: 1000
assertSame(dataDirectories[3], candidates.get(1).dataDirectory); // available: 999
assertSame(dataDirectories[0], candidates.get(2).dataDirectory); // available: 11
assertSame(dataDirectories[1], candidates.get(3).dataDirectory); // available: 10
// check for writeSize == 5
Map<DataDirectory, DataDirectory> testMap = new IdentityHashMap<>();
for (int i=0; ; i++)
{
candidates = getWriteableDirectories(dataDirectories, 5L);
assertEquals(4, candidates.size());
DataDirectory dir = Directories.pickWriteableDirectory(candidates);
testMap.put(dir, dir);
assertFalse(testMap.size() > 4);
if (testMap.size() == 4)
{
// at least (rule of thumb) 100 iterations to see whether there are more (wrong) directories returned
if (i >= 100)
break;
}
// random weighted writeable directory algorithm fails to return all possible directories after
// many tries
if (i >= 10000000)
fail();
}
// check for writeSize == 11
testMap.clear();
for (int i=0; ; i++)
{
candidates = getWriteableDirectories(dataDirectories, 11L);
assertEquals(3, candidates.size());
for (Directories.DataDirectoryCandidate candidate : candidates)
assertTrue(candidate.dataDirectory.getAvailableSpace() >= 11L);
DataDirectory dir = Directories.pickWriteableDirectory(candidates);
testMap.put(dir, dir);
assertFalse(testMap.size() > 3);
if (testMap.size() == 3)
{
// at least (rule of thumb) 100 iterations
if (i >= 100)
break;
}
// random weighted writeable directory algorithm fails to return all possible directories after
// many tries
if (i >= 10000000)
fail();
}
}
private List<Directories.DataDirectoryCandidate> getWriteableDirectories(DataDirectory[] dataDirectories, long writeSize)
{
// copied from Directories.getWriteableLocation(long)
List<Directories.DataDirectoryCandidate> candidates = new ArrayList<>();
long totalAvailable = 0L;
for (DataDirectory dataDir : dataDirectories)
{
Directories.DataDirectoryCandidate candidate = new Directories.DataDirectoryCandidate(dataDir);
// exclude directory if its total writeSize does not fit to data directory
if (candidate.availableSpace < writeSize)
continue;
candidates.add(candidate);
totalAvailable += candidate.availableSpace;
}
Directories.sortWriteableCandidates(candidates, totalAvailable);
return candidates;
}
}
| |
import org.jsoup.*;
import org.jsoup.select.*;
import java.util.*;
import org.jsoup.nodes.*;
import static java.lang.Double.*;
import freemarker.template.*;
import java.io.*;
import org.json.*;
import org.apache.commons.io.*;
import java.net.*;
import java.text.*;
public class NBA {
public String preview(String team, boolean responsive) throws Exception {
Template template = Main.cfg.getTemplate(responsive ? "bootstrap-preview.html" : "preview.html");
String otherTeam = getNextOpponent(team);
int scoreId = getScoreIdFromBrefCode(team);
int otherScoreId = getScoreIdFromBrefCode(otherTeam);
String awayTeam, homeTeam;
String nextGameUri = getNextGameUri(scoreId);
GameInfo gameInfo = getGameInfo(nextGameUri);
int awayScoreId = gameInfo.awayId;
int homeScoreId = gameInfo.homeId;
if (scoreId == awayScoreId) {
awayTeam = team;
homeTeam = otherTeam;
} else {
homeTeam = team;
awayTeam = otherTeam;
}
Map<String, Object> data = new HashMap<String, Object>();
Map<String, Object> home = new HashMap<String, Object>();
Map<String, Object> away = new HashMap<String, Object>();
away.put("results", getLatestResults(awayScoreId));
away.put("leaders", findLeaders(awayTeam));
Map<String, TeamSeason> teamStats = getTeamStats();
away.put("rank", teamStats.get(awayTeam));
away.put("standings", getStandings(awayTeam));
home.put("results", getLatestResults(homeScoreId));
home.put("leaders", findLeaders(homeTeam));
Map<String, TeamSeason> teamStats2 = getTeamStats();
home.put("rank", teamStats2.get(homeTeam));
home.put("standings", getStandings(homeTeam));
data.put("away", away);
data.put("home", home);
data.put("headToHead", headToHead(team, otherTeam));
data.put("gameInfo", gameInfo);
StringWriter writer = new StringWriter();
template.process(data, writer);
return writer.getBuffer().toString();
}
public GameInfo getGameInfo(String uri) throws Exception {
// location, stadium, tv_listings.[short_name]
String url = "http://api.thescore.com" + uri;
String str = IOUtils.toString(new URL(url), "UTF-8");
JSONObject game = new JSONObject(str);
GameInfo gameInfo = new GameInfo();
gameInfo.location = game.getString("location");
gameInfo.stadium = game.getString("stadium");
JSONArray tvListings = game.getJSONArray("tv_listings");
String tv = "";
for (int i=0; i<tvListings.length(); i++) {
tv += tvListings.getJSONObject(i).getString("short_name");
if (i != tvListings.length()-1) {
tv += ", ";
}
}
gameInfo.tv = tv;
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d, h:mm a");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
gameInfo.time = simpleDateFormat.format(sdf.parse(game.getString("game_date"))) + " EST";
gameInfo.awayLogo = game.getJSONObject("away_team").getJSONObject("logos").getString("small");
gameInfo.awayName = game.getJSONObject("away_team").getString("full_name");
gameInfo.awayId = game.getJSONObject("away_team").getInt("id");
gameInfo.homeLogo = game.getJSONObject("home_team").getJSONObject("logos").getString("small");
gameInfo.homeName = game.getJSONObject("home_team").getString("full_name");
gameInfo.homeId = game.getJSONObject("home_team").getInt("id");
if (!game.isNull("odd")) {
gameInfo.line = game.getJSONObject("odd").getString("line");
gameInfo.overUnder = game.getJSONObject("odd").getString("over_under");
}
return gameInfo;
}
public String getNextGameUri(int teamId) throws Exception {
String url = "http://api.thescore.com/nba/teams/" + teamId + "/events/upcoming?rpp=2";
String str = IOUtils.toString(new URL(url), "UTF-8");
JSONArray upcoming = new JSONArray(str);
if (upcoming.length() > 0) {
for (int i=0; i<upcoming.length(); i++) {
JSONObject game = upcoming.getJSONObject(i);
if (game.getString("event_status").equals("pre_game")) {
return game.getString("api_uri");
}
}
}
return null;
}
public int getScoreIdFromBrefCode(String team) throws Exception {
return Integer.parseInt(ResourceBundle.getBundle("bref_to_thescore").getString(team));
}
public String getBrefCodeFromScoreId(int id) throws Exception {
return ResourceBundle.getBundle("thescore_to_bref").getString(id + "");
}
public String getNextOpponent(String team) throws Exception {
int teamId = getScoreIdFromBrefCode(team);
String url = "http://api.thescore.com/nba/teams/" + teamId + "/events/upcoming?rpp=2";
String str = IOUtils.toString(new URL(url), "UTF-8");
JSONArray upcoming = new JSONArray(str);
if (upcoming.length() > 0) {
for (int i=0; i<upcoming.length(); i++) {
JSONObject game = upcoming.getJSONObject(i);
if (game.getString("event_status").equals("pre_game")) {
int away = game.getJSONObject("away_team").getInt("id");
int home = game.getJSONObject("home_team").getInt("id");
int answer = away == teamId ? home : away;
return getBrefCodeFromScoreId(answer);
}
}
}
return null;
}
public List<TeamResult> getLatestResults(int teamId) throws Exception {
String url = "https://api.thescore.com/nba/teams/" + teamId + "/events/previous?rpp=5";
String str = IOUtils.toString(new URL(url), "UTF-8");
JSONArray games = new JSONArray(str);
List<TeamResult> teamResults = new ArrayList<TeamResult>();
for (int i=0; i < games.length(); i++) {
TeamResult tr = new TeamResult();
JSONObject game = games.getJSONObject(i);
JSONObject away = game.getJSONObject("away_team");
JSONObject home = game.getJSONObject("home_team");
tr.homeId = home.getInt("id");
tr.home = home.getString("abbreviation");
tr.homeScore = "" + game.getJSONObject("box_score").getJSONObject("score").getJSONObject("home").getInt("score");
tr.awayId = away.getInt("id");
tr.away = away.getString("abbreviation");
tr.awayScore = "" + game.getJSONObject("box_score").getJSONObject("score").getJSONObject("away").getInt("score");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
tr.gameDate = new SimpleDateFormat("MMM d").format(sdf.parse(game.getString("game_date")));
tr.boxScoreUrl = "http://www.thescore.com" + game.getString("api_uri") + "/box_score";
teamResults.add(tr);
}
return teamResults;
}
/*
public List<TeamResult> getLatestResults(String team) throws Exception {
String url = "http://www.basketball-reference.com/teams/" + team + "/2015/gamelog/";
Document doc = Jsoup.connect(url).get();
Element table = doc.getElementById("tgl_basic");
Elements results = table.getElementsByAttributeValueStarting("id", "tgl_basic.");
int startIndex = -1, endIndex = -1;
int numGames = 5;
if (results.size() >= numGames) {
startIndex = results.size() - numGames;
endIndex = results.size()-1;
} else if (results.size() > 0) {
startIndex = 0;
endIndex = results.size()-1;
}
List<TeamResult> teamResults = new ArrayList<TeamResult>();
if (startIndex != -1) {
for (int i=startIndex; i<=endIndex; i++) {
TeamResult tr = new TeamResult();
Element result = results.get(i);
String location = result.child(3).text();
if (location.equals("@")) {
tr.home = result.child(4).text();
tr.homeScore = result.child(7).text();
tr.away = team;
tr.awayScore = result.child(6).text();
} else {
tr.away = result.child(4).text();
tr.awayScore = result.child(7).text();
tr.home = team;
tr.homeScore = result.child(6).text();
}
tr.gameDate = result.child(2).text();
tr.boxScoreUrl = "http://basketball-reference.com" + result.child(2).child(0).attr("href");
teamResults.add(tr);
}
}
Collections.reverse(teamResults);
return teamResults;
}
*/
public PlayerSeason topPlayerSeason(List<PlayerSeason> list, String field) {
Collections.sort(list, new PlayerSeasonComparator(field));
return list.get(0);
}
public Map<String, PlayerSeason> findLeaders(String team) throws Exception {
Map<String, PlayerSeason> leaders = new HashMap<String, PlayerSeason>();
List<PlayerSeason> stats = getSeasonStats(team);
leaders.put("ppg", topPlayerSeason(stats, "ppg"));
leaders.put("rpg", topPlayerSeason(stats, "rpg"));
leaders.put("apg", topPlayerSeason(stats, "apg"));
leaders.put("spg", topPlayerSeason(stats, "spg"));
leaders.put("bpg", topPlayerSeason(stats, "bpg"));
return leaders;
}
public List<PlayerSeason> getSeasonStats(String team) throws Exception {
String url = "http://www.basketball-reference.com/teams/" + team + "/2016.html";
Document doc = Jsoup.connect(url).get();
Element table = doc.getElementById("per_game");
Elements results = table.child(2).getElementsByTag("tr");
List<PlayerSeason> playerSeasons = new ArrayList<PlayerSeason>();
for (Element r : results) {
//1, 20 21, 22 27
PlayerSeason ps = new PlayerSeason();
ps.name = r.child(1).text();
ps.ppg = parseDouble(r.child(26).text());
ps.rpg = parseDouble(r.child(20).text());
ps.apg = parseDouble(r.child(21).text());
ps.spg = parseDouble(r.child(22).text());
ps.bpg = parseDouble(r.child(23).text());
playerSeasons.add(ps);
}
return playerSeasons;
}
public void applyRankings(List<TeamSeason> teamSeasons) {
Collections.sort(teamSeasons, new TeamSeasonComparator("ortg"));
for (int i=0; i<teamSeasons.size(); i++) {
teamSeasons.get(i).ortgRank = i+1;
}
Collections.sort(teamSeasons, new TeamSeasonComparator("drtg"));
for (int i=0; i<teamSeasons.size(); i++) {
teamSeasons.get(i).drtgRank = Math.abs(teamSeasons.size() - (i + 1)) + 1;
}
Collections.sort(teamSeasons, new TeamSeasonComparator("pace"));
for (int i=0; i<teamSeasons.size(); i++) {
teamSeasons.get(i).paceRank = i+1;
}
Collections.sort(teamSeasons, new TeamSeasonComparator("drb"));
for (int i=0; i<teamSeasons.size(); i++) {
teamSeasons.get(i).drbRank = i+1;
}
Collections.sort(teamSeasons, new TeamSeasonComparator("ts"));
for (int i=0; i<teamSeasons.size(); i++) {
teamSeasons.get(i).tsRank = i+1;
}
}
public Map<String, TeamSeason> getTeamStats() throws Exception {
String url = "http://www.basketball-reference.com/leagues/NBA_2016.html";
Document doc = Jsoup.connect(url).get();
Element table = doc.getElementById("misc");
Elements results = table.child(2).getElementsByTag("tr");
results.remove(results.size()-1); // get rid of average
List<TeamSeason> teamSeasons = new ArrayList<TeamSeason>();
for (Element r : results) {
//1, 20 21, 22 27
TeamSeason teamSeason = new TeamSeason();
teamSeason.name = r.child(1).child(0).attr("href").split("/")[2];
teamSeason.ortg = parseDouble(r.child(8).text());
teamSeason.drtg = parseDouble(r.child(9).text());
teamSeason.pace = parseDouble(r.child(10).text());
teamSeason.drb = parseDouble(r.child(20).text());
teamSeason.ts = parseDouble(r.child(13).text());
teamSeasons.add(teamSeason);
}
applyRankings(teamSeasons);
Map<String, TeamSeason> teamSeasonMap = new HashMap<String, TeamSeason>();
for (TeamSeason ts : teamSeasons) {
teamSeasonMap.put(ts.name, ts);
}
return teamSeasonMap;
}
public Standings getStandings(String teamCode) throws Exception {
int id = getScoreIdFromBrefCode(teamCode);
String url = "http://api.thescore.com/nba/teams/" + id + "/";
String str = IOUtils.toString(new URL(url), "UTF-8");
JSONObject team = new JSONObject(str);
Standings standings = new Standings();
standings.division = team.getString("division");
standings.conference = team.getString("conference");
standings.conferenceStanding = team.getJSONObject("standing").getInt("conference_ranking");
standings.divisionStanding = team.getJSONObject("standing").getInt("division_ranking");
standings.recentRecord = team.getJSONObject("standing").getString("last_ten_games_record");
standings.record = team.getJSONObject("standing").getString("short_record");
return standings;
}
public List<TeamResult> headToHead(String awayTeam, String homeTeam) throws Exception {
int team1 = getScoreIdFromBrefCode(homeTeam);
int team2 = getScoreIdFromBrefCode(awayTeam);
String url = "https://api.thescore.com/nba/teams/" + team1 + "/events/previous?rpp=200";
List<TeamResult> teamResults = new ArrayList<TeamResult>();
String str = IOUtils.toString(new URL(url), "UTF-8");
JSONArray games = new JSONArray(str);
List<JSONObject> selectedGames = new ArrayList<JSONObject>();
for (int i=0; i < games.length(); i++) {
TeamResult tr = new TeamResult();
JSONObject game = games.getJSONObject(i);
int awayId = game.getJSONObject("away_team").getInt("id");
int homeId = game.getJSONObject("home_team").getInt("id");
if ((team1 == homeId && team2 == awayId) || (team2 == homeId && team1 == awayId)) {
selectedGames.add(game);
if (selectedGames.size() == 5) {
break;
}
}
}
for (JSONObject game : selectedGames) {
JSONObject away = game.getJSONObject("away_team");
JSONObject home = game.getJSONObject("home_team");
TeamResult tr = new TeamResult();
tr.homeId = home.getInt("id");
tr.home = home.getString("abbreviation");
tr.homeScore = "" + game.getJSONObject("box_score").getJSONObject("score").getJSONObject("home").getInt("score");
tr.awayId = away.getInt("id");
tr.away = away.getString("abbreviation");
tr.awayScore = "" + game.getJSONObject("box_score").getJSONObject("score").getJSONObject("away").getInt("score");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
tr.gameDate = new SimpleDateFormat("MMM d").format(sdf.parse(game.getString("game_date")));
tr.boxScoreUrl = "http://www.thescore.com" + game.getString("api_uri") + "/box_score";
teamResults.add(tr);
}
return teamResults;
}
/*
System.out.println(home + " " + away);
String url = "http://www.basketball-reference.com/play-index/tgl_finder.cgi?request=1&match=game&lg_id=NBA&year_min=1947&year_max=2015&team_id=" + away + "&opp_id=" + home + "&is_playoffs=&round_id=&best_of=&team_seed_cmp=eq&team_seed=&opp_seed_cmp=eq&opp_seed=&is_range=N&game_num_type=team&game_num_min=&game_num_max=&game_month=&game_location=&game_result=&is_overtime=&c1stat=&c1comp=gt&c1val=&c2stat=&c2comp=gt&c2val=&c3stat=&c3comp=gt&c3val=&c4stat=&c4comp=gt&c4val=&order_by=date_game";
Document doc = Jsoup.connect(url).get();
Element table = doc.getElementById("stats");
Elements results = table.child(2).getElementsByTag("tr");
int startIndex = -1, endIndex = -1;
int numGames = 5;
if (results.size() > 0) {
startIndex = 0;
}
if (results.size() >= numGames) {
endIndex = numGames;
} else if (results.size() != 0 && results.size() < numGames) {
endIndex = results.size() - 1;
}
if (startIndex == -1)
return null;
// 0, 3, 19, 32
List<TeamResult> teamResults = new ArrayList<TeamResult>();
for (int i=startIndex; i<=endIndex; i++) {
Element result = results.get(i);
String location = result.child(3).text().trim();
String score1 = result.child(19).text();
String score2 = result.child(32).text();
TeamResult tr = new TeamResult();
if (location.equals("@")) {
tr.away = away;
tr.home = home;
tr.homeScore = score1;
tr.awayScore = score2;
} else {
tr.away = home;
tr.home = away;
tr.homeScore = score2;
tr.awayScore = score1;
}
tr.boxScoreUrl = "http://basketball-reference.com" + result.child(1).child(0).attr("href");
tr.gameDate = result.child(1).text();
teamResults.add(tr);
*/
}
| |
package org.marketcetera.messagehistory;
import static java.math.BigDecimal.ZERO;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import org.marketcetera.core.instruments.InstrumentFromMessage;
import org.marketcetera.core.instruments.InstrumentToMessage;
import org.marketcetera.quickfix.FIXMessageFactory;
import org.marketcetera.trade.*;
import org.marketcetera.util.log.SLF4JLoggerProxy;
import org.marketcetera.util.misc.ClassVersion;
import quickfix.FieldNotFound;
import quickfix.Message;
import quickfix.field.AvgPx;
import quickfix.field.CumQty;
import quickfix.field.MsgType;
import ca.odell.glazedlists.AbstractEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.event.ListEvent;
import ca.odell.glazedlists.event.ListEventListener;
/* $License$ */
/**
* A virtual list of {@link ReportHolder} that tracks the average price of
* symbols in a source list. This list will have one entry for each unique
* symbol in the source list.
*
* @author anshul@marketcetera.com
* @author <a href="mailto:will@marketcetera.com">Will Horn</a>
* @version $Id: AveragePriceReportList.java 16888 2014-04-22 18:32:36Z colin $
* @since 1.0.0
*/
@ClassVersion("$Id: AveragePriceReportList.java 16888 2014-04-22 18:32:36Z colin $")
public class AveragePriceReportList extends AbstractEventList<ReportHolder> implements ListEventListener<ReportHolder> {
private final HashMap<SymbolSide, Integer> mAveragePriceIndexes = new HashMap<SymbolSide, Integer>();
private final ArrayList<ReportHolder> mAveragePricesList = new ArrayList<ReportHolder>();
private final FIXMessageFactory mMessageFactory;
public AveragePriceReportList(FIXMessageFactory messageFactory, EventList<ReportHolder> source) {
super(source.getPublisher());
this.mMessageFactory = messageFactory;
source.addListEventListener(this);
readWriteLock = source.getReadWriteLock();
}
public void listChanged(ListEvent<ReportHolder> listChanges) {
// all of these changes to this list happen "atomically"
updates.beginEvent(true);
// handle reordering events
if(!listChanges.isReordering()) {
// for all changes, one index at a time
while(listChanges.next()) {
// get the current change info
int changeType = listChanges.getType();
EventList<ReportHolder> sourceList = listChanges.getSourceList();
// handle delete events
if(changeType == ListEvent.UPDATE) {
throw new UnsupportedOperationException();
} else if (changeType == ListEvent.DELETE) {
// assume a delete all since this is the only thing supported.
clear();
updates.commitEvent();
return;
} else if(changeType == ListEvent.INSERT) {
ReportHolder deltaReportHolder = sourceList.get(listChanges.getIndex());
Message deltaMessage = deltaReportHolder.getMessage();
ReportBase deltaReport = deltaReportHolder.getReport();
quickfix.field.Side orderSide = new quickfix.field.Side();
try {
deltaMessage.getField(orderSide);
} catch (FieldNotFound e) {
orderSide.setValue(quickfix.field.Side.UNDISCLOSED);
}
String side = String.valueOf(orderSide.getValue());
Instrument instrument = InstrumentFromMessage.SELECTOR.forValue(deltaMessage).extract(deltaMessage);
SymbolSide symbolSide = new SymbolSide(instrument, side);
if(deltaReport instanceof ExecutionReport) {
SLF4JLoggerProxy.debug(AveragePriceReportList.class,
"Considering {}", //$NON-NLS-1$
deltaReport);
ExecutionReport execReport = (ExecutionReport)deltaReport;
ExecutionType execType = execReport.getExecutionType();
if(execType == null) {
SLF4JLoggerProxy.debug(AveragePriceReportList.class,
"Skipping {} because the execType was null", //$NON-NLS-1$
execReport);
continue;
}
if(execType == null || !execType.isFill()){
SLF4JLoggerProxy.debug(AveragePriceReportList.class,
"Skipping {} because its execution type {} is not a fill", //$NON-NLS-1$
execReport,
execReport.getExecutionType());
continue;
}
if(!execReport.getOriginator().forOrders() || !execReport.getHierarchy().forOrders()) {
SLF4JLoggerProxy.debug(AveragePriceReportList.class,
"Skipping {} because it's not appropriate for FIX Message Views", //$NON-NLS-1$
execReport);
continue;
}
BigDecimal lastQuantity = execReport.getLastQuantity();
BigDecimal lastPrice = execReport.getLastPrice();
if(lastQuantity == null || !(lastQuantity.compareTo(BigDecimal.ZERO) > 0)) {
SLF4JLoggerProxy.debug(AveragePriceReportList.class,
"Skipping {} because the last quantity was null/zero", //$NON-NLS-1$
execReport);
continue;
}
if(lastPrice == null) {
SLF4JLoggerProxy.debug(AveragePriceReportList.class,
"Skipping {} because the last price was null", //$NON-NLS-1$
execReport);
continue;
}
Integer averagePriceIndex = mAveragePriceIndexes.get(symbolSide);
// decide if we've seen this symbol/side combination in the list of ERs before. if we have, averagePriceIndex will be non-null
if(averagePriceIndex != null) {
// we have already processed at least one ER with this symbol/side combination. that means the math must take into account the existing
// ERs as well as the current ER
ReportHolder averagePriceReportHolder = mAveragePricesList.get(averagePriceIndex);
Message averagePriceMessage = averagePriceReportHolder.getMessage();
ExecutionReport averagePriceReport = (ExecutionReport) averagePriceReportHolder.getReport();
BigDecimal existingCumQty = averagePriceReport.getCumulativeQuantity();
BigDecimal existingAvgPx = averagePriceReport.getAveragePrice();
BigDecimal newLastQty = lastQuantity;
BigDecimal newTotal = existingCumQty.add(newLastQty);
if(!newTotal.equals(ZERO)) {
BigDecimal numerator = existingCumQty.multiply(existingAvgPx).add(newLastQty.multiply(lastPrice));
BigDecimal newAvgPx = numerator.divide(newTotal,
4,
RoundingMode.HALF_UP);
averagePriceMessage.setDecimal(AvgPx.FIELD,
newAvgPx);
averagePriceMessage.setDecimal(CumQty.FIELD,
newTotal);
updates.elementUpdated(averagePriceIndex,
averagePriceReportHolder,
averagePriceReportHolder);
}
} else {
// we have not seen an ER with this instrument/side combination, make a new average price entry
Message averagePriceMessage = mMessageFactory.createMessage(MsgType.EXECUTION_REPORT);
averagePriceMessage.setField(orderSide);
InstrumentToMessage.SELECTOR.forInstrument(instrument).set(instrument,
mMessageFactory.getBeginString(),
averagePriceMessage);
averagePriceMessage.setField(new CumQty(lastQuantity));
averagePriceMessage.setField(new AvgPx(lastPrice.setScale(4,
RoundingMode.HALF_UP)));
try {
ReportHolder newReport = new ReportHolder(Factory.getInstance().createExecutionReport(averagePriceMessage,
execReport.getBrokerID(),
Originator.Broker,
execReport.getActorID(),
execReport.getViewerID()),
deltaReportHolder.getUnderlying());
mAveragePricesList.add(newReport);
averagePriceIndex = mAveragePricesList.size()-1;
mAveragePriceIndexes.put(symbolSide,
averagePriceIndex);
updates.elementInserted(averagePriceIndex,
newReport);
} catch (MessageCreationException e) {
Messages.UNEXPECTED_ERROR.error(this,e);
}
}
} else {
SLF4JLoggerProxy.debug(AveragePriceReportList.class,
"Skipping {} because it's not an ExecutionReport", //$NON-NLS-1$
deltaReport);
}
}
}
}
// commit the changes and notify listeners
updates.commitEvent();
}
@Override
public ReportHolder get(int index) {
return mAveragePricesList.get(index);
}
@Override
public int size() {
return mAveragePricesList.size();
}
@Override
public void clear() {
// don't do a clear on an empty set
if(isEmpty()) return;
// create the change event
updates.beginEvent();
for(int i = 0, size = size(); i < size; i++) {
updates.elementDeleted(0, get(i));
}
// do the actual clear
mAveragePricesList.clear();
mAveragePriceIndexes.clear();
// fire the event
updates.commitEvent();
}
@Override
public void dispose() {
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.omid.transaction;
import static org.mockito.Mockito.spy;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Coprocessor;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.omid.TestUtils;
import org.apache.omid.committable.CommitTable;
import org.apache.omid.committable.hbase.HBaseCommitTableConfig;
import org.apache.omid.metrics.NullMetricsProvider;
import org.apache.omid.timestamp.storage.HBaseTimestampStorageConfig;
import org.apache.omid.tso.TSOServer;
import org.apache.omid.tso.TSOServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class TestSnapshotFilterLL {
private static final Logger LOG = LoggerFactory.getLogger(TestSnapshotFilterLL.class);
private static final String TEST_FAMILY = "test-fam";
private static final int MAX_VERSIONS = 3;
private AbstractTransactionManager tm;
private Injector injector;
private Admin admin;
private Configuration hbaseConf;
private HBaseTestingUtility hbaseTestUtil;
private MiniHBaseCluster hbaseCluster;
private TSOServer tso;
private CommitTable commitTable;
private PostCommitActions syncPostCommitter;
private Connection connection;
@BeforeClass
public void setupTestSnapshotFilter() throws Exception {
TSOServerConfig tsoConfig = new TSOServerConfig();
tsoConfig.setPort(5678);
tsoConfig.setConflictMapSize(1);
tsoConfig.setWaitStrategy("LOW_CPU");
tsoConfig.setLowLatency(true);
injector = Guice.createInjector(new TSOForSnapshotFilterTestModule(tsoConfig));
hbaseConf = injector.getInstance(Configuration.class);
hbaseConf.setBoolean("omid.server.side.filter", true);
hbaseConf.setInt("hbase.hconnection.threads.core", 5);
hbaseConf.setInt("hbase.hconnection.threads.max", 10);
// Tunn down handler threads in regionserver
hbaseConf.setInt("hbase.regionserver.handler.count", 10);
// Set to random port
hbaseConf.setInt("hbase.master.port", 0);
hbaseConf.setInt("hbase.master.info.port", 0);
hbaseConf.setInt("hbase.regionserver.port", 0);
hbaseConf.setInt("hbase.regionserver.info.port", 0);
HBaseCommitTableConfig hBaseCommitTableConfig = injector.getInstance(HBaseCommitTableConfig.class);
HBaseTimestampStorageConfig hBaseTimestampStorageConfig = injector.getInstance(HBaseTimestampStorageConfig.class);
setupHBase();
connection = ConnectionFactory.createConnection(hbaseConf);
admin = connection.getAdmin();
createRequiredHBaseTables(hBaseTimestampStorageConfig, hBaseCommitTableConfig);
setupTSO();
commitTable = injector.getInstance(CommitTable.class);
}
private void setupHBase() throws Exception {
LOG.info("--------------------------------------------------------------------------------------------------");
LOG.info("Setting up HBase");
LOG.info("--------------------------------------------------------------------------------------------------");
hbaseTestUtil = new HBaseTestingUtility(hbaseConf);
LOG.info("--------------------------------------------------------------------------------------------------");
LOG.info("Creating HBase MiniCluster");
LOG.info("--------------------------------------------------------------------------------------------------");
hbaseCluster = hbaseTestUtil.startMiniCluster(1);
}
private void createRequiredHBaseTables(HBaseTimestampStorageConfig timestampStorageConfig,
HBaseCommitTableConfig hBaseCommitTableConfig) throws IOException {
createTableIfNotExists(timestampStorageConfig.getTableName(), timestampStorageConfig.getFamilyName().getBytes());
createTableIfNotExists(hBaseCommitTableConfig.getTableName(), hBaseCommitTableConfig.getCommitTableFamily(), hBaseCommitTableConfig.getLowWatermarkFamily());
}
private void createTableIfNotExists(String tableName, byte[]... families) throws IOException {
if (!admin.tableExists(TableName.valueOf(tableName))) {
LOG.info("Creating {} table...", tableName);
HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
for (byte[] family : families) {
HColumnDescriptor datafam = new HColumnDescriptor(family);
datafam.setMaxVersions(MAX_VERSIONS);
desc.addFamily(datafam);
}
int priority = Coprocessor.PRIORITY_HIGHEST;
desc.addCoprocessor(OmidSnapshotFilter.class.getName(),null,++priority,null);
desc.addCoprocessor("org.apache.hadoop.hbase.coprocessor.AggregateImplementation",null,++priority,null);
admin.createTable(desc);
try {
hbaseTestUtil.waitTableAvailable(TableName.valueOf(tableName),5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void setupTSO() throws IOException, InterruptedException {
tso = injector.getInstance(TSOServer.class);
tso.startAndWait();
TestUtils.waitForSocketListening("localhost", 5678, 100);
Thread.currentThread().setName("UnitTest(s) thread");
}
@AfterClass
public void cleanupTestSnapshotFilter() throws Exception {
teardownTSO();
hbaseCluster.shutdown();
}
private void teardownTSO() throws IOException, InterruptedException {
tso.stopAndWait();
TestUtils.waitForSocketNotListening("localhost", 5678, 1000);
}
@BeforeMethod
public void setupTestSnapshotFilterIndividualTest() throws Exception {
tm = spy((AbstractTransactionManager) newTransactionManager());
}
private TransactionManager newTransactionManager() throws Exception {
HBaseOmidClientConfiguration hbaseOmidClientConf = new HBaseOmidClientConfiguration();
hbaseOmidClientConf.setConnectionString("localhost:5678");
hbaseOmidClientConf.setHBaseConfiguration(hbaseConf);
CommitTable.Client commitTableClient = commitTable.getClient();
syncPostCommitter =
spy(new HBaseSyncPostCommitter(new NullMetricsProvider(),commitTableClient));
return HBaseTransactionManager.builder(hbaseOmidClientConf)
.postCommitter(syncPostCommitter)
.commitTableClient(commitTableClient)
.build();
}
@Test(timeOut = 60_000)
public void testInvalidate() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testGetFirstResult";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put row1 = new Put(rowName1);
row1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, row1);
Transaction tx2 = tm.begin();
Get get = new Get(rowName1);
Result result = tt.get(tx2, get);
assertTrue(result.isEmpty(), "Result should not be empty!");
boolean gotInvalidated = false;
try {
tm.commit(tx1);
} catch (RollbackException e) {
gotInvalidated = true;
}
assertTrue(gotInvalidated);
assertTrue(tm.isLowLatency());
}
@Test(timeOut = 60_000)
public void testInvalidateByScan() throws Throwable {
byte[] rowName1 = Bytes.toBytes("row1");
byte[] famName1 = Bytes.toBytes(TEST_FAMILY);
byte[] colName1 = Bytes.toBytes("col1");
byte[] dataValue1 = Bytes.toBytes("testWrite-1");
String TEST_TABLE = "testGetFirstResult";
createTableIfNotExists(TEST_TABLE, Bytes.toBytes(TEST_FAMILY));
TTable tt = new TTable(connection, TEST_TABLE);
Transaction tx1 = tm.begin();
Put row1 = new Put(rowName1);
row1.addColumn(famName1, colName1, dataValue1);
tt.put(tx1, row1);
Transaction tx2 = tm.begin();
ResultScanner iterableRS = tt.getScanner(tx2, new Scan().setStartRow(rowName1).setStopRow(rowName1));
assertTrue(iterableRS.next() == null);
tm.commit(tx2);
boolean gotInvalidated = false;
try {
tm.commit(tx1);
} catch (RollbackException e) {
gotInvalidated = true;
}
assertTrue(gotInvalidated);
assertTrue(tm.isLowLatency());
}
}
| |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package g7.bluesky.launcher3;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityManager;
import android.widget.FrameLayout;
public class AppsCustomizeTabHost extends FrameLayout implements LauncherTransitionable, Insettable {
static final String LOG_TAG = "AppsCustomizeTabHost";
private static final String APPS_TAB_TAG = "APPS";
private static final String WIDGETS_TAB_TAG = "WIDGETS";
private AppsCustomizePagedView mPagedView;
private View mContent;
private boolean mInTransition = false;
private final Rect mInsets = new Rect();
public AppsCustomizeTabHost(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Convenience methods to select specific tabs. We want to set the content type immediately
* in these cases, but we note that we still call setCurrentTabByTag() so that the tab view
* reflects the new content (but doesn't do the animation and logic associated with changing
* tabs manually).
*/
void setContentTypeImmediate(AppsCustomizePagedView.ContentType type) {
mPagedView.setContentType(type);
}
public void setCurrentTabFromContent(AppsCustomizePagedView.ContentType type) {
setContentTypeImmediate(type);
}
@Override
public void setInsets(Rect insets) {
mInsets.set(insets);
LayoutParams flp = (LayoutParams) mContent.getLayoutParams();
flp.topMargin = insets.top;
flp.bottomMargin = insets.bottom;
flp.leftMargin = insets.left;
flp.rightMargin = insets.right;
mContent.setLayoutParams(flp);
}
/**
* Setup the tab host and create all necessary tabs.
*/
@Override
protected void onFinishInflate() {
mPagedView = (AppsCustomizePagedView) findViewById(R.id.apps_customize_pane_content);
mContent = findViewById(R.id.content);
}
public void setBackground(Drawable d) {
if (mContent != null) {
mContent.setBackground(d);
}
}
public String getContentTag() {
return getTabTagForContentType(mPagedView.getContentType());
}
/**
* Returns the content type for the specified tab tag.
*/
public AppsCustomizePagedView.ContentType getContentTypeForTabTag(String tag) {
if (tag.equals(APPS_TAB_TAG)) {
return AppsCustomizePagedView.ContentType.Applications;
} else if (tag.equals(WIDGETS_TAB_TAG)) {
return AppsCustomizePagedView.ContentType.Widgets;
}
return AppsCustomizePagedView.ContentType.Applications;
}
/**
* Returns the tab tag for a given content type.
*/
public String getTabTagForContentType(AppsCustomizePagedView.ContentType type) {
if (type == AppsCustomizePagedView.ContentType.Applications) {
return APPS_TAB_TAG;
} else if (type == AppsCustomizePagedView.ContentType.Widgets) {
return WIDGETS_TAB_TAG;
}
return APPS_TAB_TAG;
}
/**
* Disable focus on anything under this view in the hierarchy if we are not visible.
*/
@Override
public int getDescendantFocusability() {
if (getVisibility() != View.VISIBLE) {
return ViewGroup.FOCUS_BLOCK_DESCENDANTS;
}
return super.getDescendantFocusability();
}
void reset() {
// Reset immediately
mPagedView.reset();
}
void trimMemory() {
mPagedView.trimMemory();
}
public void onWindowVisible() {
if (getVisibility() == VISIBLE) {
mContent.setVisibility(VISIBLE);
// We unload the widget previews when the UI is hidden, so need to reload pages
// Load the current page synchronously, and the neighboring pages asynchronously
mPagedView.loadAssociatedPages(mPagedView.getCurrentPage(), true);
mPagedView.loadAssociatedPages(mPagedView.getCurrentPage());
}
}
@Override
public ViewGroup getContent() {
return mPagedView;
}
public boolean isInTransition() {
return mInTransition;
}
/* LauncherTransitionable overrides */
@Override
public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
mPagedView.onLauncherTransitionPrepare(l, animated, toWorkspace);
mInTransition = true;
if (toWorkspace) {
// Going from All Apps -> Workspace
setVisibilityOfSiblingsWithLowerZOrder(VISIBLE);
} else {
// Going from Workspace -> All Apps
mContent.setVisibility(VISIBLE);
// Make sure the current page is loaded (we start loading the side pages after the
// transition to prevent slowing down the animation)
// TODO: revisit this
mPagedView.loadAssociatedPages(mPagedView.getCurrentPage());
}
}
@Override
public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
mPagedView.onLauncherTransitionStart(l, animated, toWorkspace);
}
@Override
public void onLauncherTransitionStep(Launcher l, float t) {
mPagedView.onLauncherTransitionStep(l, t);
}
@Override
public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
mPagedView.onLauncherTransitionEnd(l, animated, toWorkspace);
mInTransition = false;
if (!toWorkspace) {
// Make sure adjacent pages are loaded (we wait until after the transition to
// prevent slowing down the animation)
mPagedView.loadAssociatedPages(mPagedView.getCurrentPage());
// Opening apps, need to announce what page we are on.
AccessibilityManager am = (AccessibilityManager)
getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
if (am.isEnabled()) {
// Notify the user when the page changes
announceForAccessibility(mPagedView.getCurrentPageDescription());
}
// Going from Workspace -> All Apps
// NOTE: We should do this at the end since we check visibility state in some of the
// cling initialization/dismiss code above.
setVisibilityOfSiblingsWithLowerZOrder(INVISIBLE);
}
}
private void setVisibilityOfSiblingsWithLowerZOrder(int visibility) {
ViewGroup parent = (ViewGroup) getParent();
if (parent == null) return;
View overviewPanel = ((Launcher) getContext()).getOverviewPanel();
final int count = parent.getChildCount();
if (!isChildrenDrawingOrderEnabled()) {
for (int i = 0; i < count; i++) {
final View child = parent.getChildAt(i);
if (child == this) {
break;
} else {
if (child.getVisibility() == GONE || child == overviewPanel) {
continue;
}
child.setVisibility(visibility);
}
}
} else {
throw new RuntimeException("Failed; can't get z-order of views");
}
}
}
| |
/* Copyright (c) 2001-2011, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb;
import org.hsqldb.ParserDQL.CompileContext;
import org.hsqldb.RangeVariable.RangeVariableConditions;
import org.hsqldb.error.Error;
import org.hsqldb.error.ErrorCode;
import org.hsqldb.index.Index;
import org.hsqldb.lib.ArrayUtil;
import org.hsqldb.lib.HsqlArrayList;
import org.hsqldb.lib.IntKeyIntValueHashMap;
import org.hsqldb.lib.Iterator;
import org.hsqldb.lib.MultiValueHashMap;
import org.hsqldb.lib.OrderedHashSet;
import org.hsqldb.lib.OrderedIntHashSet;
/**
* Determines how JOIN and WHERE expressions are used in query
* processing and which indexes are used for table access.
*
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 2.0.1
* @since 1.9.0
*/
public class RangeVariableResolver {
Session session;
RangeVariable[] rangeVariables;
Expression conditions;
OrderedHashSet rangeVarSet = new OrderedHashSet();
CompileContext compileContext;
SortAndSlice sortAndSlice = SortAndSlice.noSort;
//
HsqlArrayList[] tempJoinExpressions;
HsqlArrayList[] joinExpressions;
HsqlArrayList[] whereExpressions;
HsqlArrayList queryExpressions = new HsqlArrayList();
//
Expression[] inExpressions;
boolean[] inInJoin;
int inExpressionCount = 0;
boolean expandInExpression = true;
//
boolean hasOuterJoin = false;
int firstLeftJoinIndex;
int firstRightJoinIndex;
//
OrderedIntHashSet colIndexSetEqual = new OrderedIntHashSet();
IntKeyIntValueHashMap colIndexSetOther = new IntKeyIntValueHashMap();
OrderedHashSet tempSet = new OrderedHashSet();
MultiValueHashMap tempMap = new MultiValueHashMap();
RangeVariableResolver(QuerySpecification select) {
this.rangeVariables = select.rangeVariables;
this.conditions = select.queryCondition;
this.compileContext = select.compileContext;
this.sortAndSlice = select.sortAndSlice;
// this.expandInExpression = select.checkQueryCondition == null;
initialise();
}
RangeVariableResolver(RangeVariable[] rangeVariables,
Expression conditions,
CompileContext compileContext) {
this.rangeVariables = rangeVariables;
this.conditions = conditions;
this.compileContext = compileContext;
initialise();
}
private void initialise() {
firstLeftJoinIndex = rangeVariables.length;
firstRightJoinIndex = rangeVariables.length;
for (int i = 0; i < rangeVariables.length; i++) {
RangeVariable range = rangeVariables[i];
if (range.isLeftJoin) {
if (firstLeftJoinIndex == rangeVariables.length) {
firstLeftJoinIndex = i;
}
hasOuterJoin = true;
}
if (range.isRightJoin) {
if (firstRightJoinIndex == rangeVariables.length) {
firstRightJoinIndex = i;
}
hasOuterJoin = true;
}
}
inExpressions = new Expression[rangeVariables.length];
inInJoin = new boolean[rangeVariables.length];
tempJoinExpressions = new HsqlArrayList[rangeVariables.length];
for (int i = 0; i < rangeVariables.length; i++) {
tempJoinExpressions[i] = new HsqlArrayList();
}
joinExpressions = new HsqlArrayList[rangeVariables.length];
for (int i = 0; i < rangeVariables.length; i++) {
joinExpressions[i] = new HsqlArrayList();
}
whereExpressions = new HsqlArrayList[rangeVariables.length];
for (int i = 0; i < rangeVariables.length; i++) {
whereExpressions[i] = new HsqlArrayList();
}
}
void processConditions(Session session) {
this.session = session;
decomposeAndConditions(session, conditions, queryExpressions);
for (int i = 0; i < rangeVariables.length; i++) {
if (rangeVariables[i].joinCondition == null) {
continue;
}
decomposeAndConditions(session, rangeVariables[i].joinCondition,
tempJoinExpressions[i]);
}
conditions = null;
if (!sortAndSlice.usingIndex
|| sortAndSlice.primaryTableIndex == null) {
for (int i = 0; i < rangeVariables.length; i++) {
rangeVarSet.add(rangeVariables[i]);
}
reorder();
rangeVarSet.clear();
}
for (int i = 0; i < rangeVariables.length; i++) {
rangeVarSet.add(rangeVariables[i]);
}
assignToLists();
expandConditions();
assignToRangeVariables();
}
void reorder() {
if (rangeVariables.length == 1 || firstLeftJoinIndex == 1
|| firstRightJoinIndex != rangeVariables.length) {
return;
}
for (int i = 0; i < rangeVariables.length; i++) {
if (!rangeVariables[i].rangeTable.isSchemaBaseTable()) {
return;
}
}
HsqlArrayList joins = new HsqlArrayList();
HsqlArrayList starts = new HsqlArrayList();
HsqlArrayList others = new HsqlArrayList();
for (int i = 0; i < firstLeftJoinIndex; i++) {
HsqlArrayList tempJoins = tempJoinExpressions[i];
for (int j = 0; j < tempJoins.size(); j++) {
Expression e = (Expression) tempJoins.get(j);
if (e.isColumnEqual) {
joins.add(e);
} else if (e.isSingleColumnCondition) {
starts.add(e);
} else {
others.add(e);
}
}
}
for (int i = 0; i < queryExpressions.size(); i++) {
Expression e = (Expression) queryExpressions.get(i);
RangeVariable[] ranges = e.getJoinRangeVariables(rangeVariables);
int count =
ArrayUtil.countCommonElements((Object[]) rangeVariables,
firstLeftJoinIndex,
(Object[]) ranges);
if (count != ranges.length) {
continue;
}
if (e.isColumnEqual) {
joins.add(e);
} else if (e.isSingleColumnCondition) {
starts.add(e);
} else {
others.add(e);
}
}
if (starts.size() == 0) {
return;
}
// choose start expressions
Expression start = null;
int position = 0;
RangeVariable range = null;
double cost =
rangeVariables[0].rangeTable.getRowStore(session).elementCount();
if (cost < Index.minimumSelectivity) {
cost = Index.minimumSelectivity;
}
if (rangeVariables[0].rangeTable.getTableType()
== TableBase.CACHED_TABLE) {
cost *= Index.cachedFactor;
}
for (int i = 0; i < starts.size(); i++) {
Expression e = (Expression) starts.get(i);
range = e.getJoinRangeVariables(rangeVariables)[0];
double currentCost = e.costFactor(session, range, OpTypes.EQUAL);
if (range == rangeVariables[0]) {
start = null;
break;
}
if (currentCost < cost) {
start = e;
}
}
if (start == null) {
return;
}
//
position = ArrayUtil.find(rangeVariables, range);
if (position <= 0) {
return;
}
RangeVariable[] newRanges = new RangeVariable[rangeVariables.length];
ArrayUtil.copyArray(rangeVariables, newRanges, rangeVariables.length);
newRanges[position] = newRanges[0];
newRanges[0] = range;
position = 1;
for (; position < firstLeftJoinIndex; position++) {
boolean found = false;
for (int i = 0; i < joins.size(); i++) {
Expression e = (Expression) joins.get(i);
if (e == null) {
continue;
}
int newPosition = getJoinedRangePosition(e, position,
newRanges);
if (newPosition >= position) {
range = newRanges[position];
newRanges[position] = newRanges[newPosition];
newRanges[newPosition] = range;
joins.set(i, null);
found = true;
break;
}
}
if (!found) {
break;
}
}
if (position != firstLeftJoinIndex) {
return;
}
ArrayUtil.copyArray(newRanges, rangeVariables, rangeVariables.length);
joins.clear();
for (int i = 0; i < firstLeftJoinIndex; i++) {
HsqlArrayList tempJoins = tempJoinExpressions[i];
joins.addAll(tempJoins);
tempJoins.clear();
}
tempJoinExpressions[firstLeftJoinIndex - 1].addAll(joins);
}
int getJoinedRangePosition(Expression e, int position,
RangeVariable[] currentRanges) {
int found = -1;
RangeVariable[] ranges = e.getJoinRangeVariables(currentRanges);
for (int i = 0; i < ranges.length; i++) {
for (int j = 0; j < currentRanges.length; j++) {
if (ranges[i] == currentRanges[j]) {
if (j >= position) {
if (found > 0) {
return -1;
} else {
found = j;
}
}
}
}
}
return found;
}
/**
* Divides AND and OR conditions and assigns
*/
static Expression decomposeAndConditions(Session session, Expression e,
HsqlArrayList conditions) {
if (e == null) {
return Expression.EXPR_TRUE;
}
Expression arg1 = e.getLeftNode();
Expression arg2 = e.getRightNode();
int type = e.getType();
if (type == OpTypes.AND) {
arg1 = decomposeAndConditions(session, arg1, conditions);
arg2 = decomposeAndConditions(session, arg2, conditions);
if (arg1 == Expression.EXPR_TRUE) {
return arg2;
}
if (arg2 == Expression.EXPR_TRUE) {
return arg1;
}
e.setLeftNode(arg1);
e.setRightNode(arg2);
return e;
} else if (type == OpTypes.EQUAL) {
if (arg1.getType() == OpTypes.ROW
&& arg2.getType() == OpTypes.ROW) {
for (int i = 0; i < arg1.nodes.length; i++) {
Expression part = new ExpressionLogical(arg1.nodes[i],
arg2.nodes[i]);
part.resolveTypes(session, null);
conditions.add(part);
}
return Expression.EXPR_TRUE;
}
}
if (e != Expression.EXPR_TRUE) {
conditions.add(e);
}
return Expression.EXPR_TRUE;
}
/**
* Divides AND and OR conditions and assigns
*/
static Expression decomposeOrConditions(Expression e,
HsqlArrayList conditions) {
if (e == null) {
return Expression.EXPR_FALSE;
}
Expression arg1 = e.getLeftNode();
Expression arg2 = e.getRightNode();
int type = e.getType();
if (type == OpTypes.OR) {
arg1 = decomposeOrConditions(arg1, conditions);
arg2 = decomposeOrConditions(arg2, conditions);
if (arg1 == Expression.EXPR_FALSE) {
return arg2;
}
if (arg2 == Expression.EXPR_FALSE) {
return arg1;
}
e = new ExpressionLogical(OpTypes.OR, arg1, arg2);
return e;
}
if (e != Expression.EXPR_FALSE) {
conditions.add(e);
}
return Expression.EXPR_FALSE;
}
/**
* Assigns the conditions to separate lists
*/
void assignToLists() {
int lastBoundary = 0;
int lastOuterIndex = -1;
int lastRightIndex = -1;
for (int i = 0; i < rangeVariables.length; i++) {
if (rangeVariables[i].isLeftJoin) {
lastOuterIndex = i;
}
if (rangeVariables[i].isRightJoin) {
lastOuterIndex = i;
lastRightIndex = i;
}
if (rangeVariables[i].isBoundary) {
lastBoundary = i;
}
if (lastOuterIndex == i) {
joinExpressions[i].addAll(tempJoinExpressions[i]);
} else {
int start = lastOuterIndex + 1;
if (lastBoundary > start) {
start = lastBoundary;
}
for (int j = 0; j < tempJoinExpressions[i].size(); j++) {
assignToJoinLists(
(Expression) tempJoinExpressions[i].get(j),
joinExpressions, start);
}
}
}
for (int i = 0; i < queryExpressions.size(); i++) {
assignToJoinLists((Expression) queryExpressions.get(i),
whereExpressions, lastRightIndex);
}
}
/**
* Assigns a single condition to the relevant list of conditions
*
* Parameter first indicates the first range variable to which condition
* can be assigned
*/
void assignToJoinLists(Expression e, HsqlArrayList[] expressionLists,
int first) {
tempSet.clear();
e.collectRangeVariables(rangeVariables, tempSet);
int index = rangeVarSet.getLargestIndex(tempSet);
// condition is independent of tables if no range variable is found
if (index == -1) {
index = 0;
}
// condition is assigned to first non-outer range variable
if (index < first) {
index = first;
}
if (e instanceof ExpressionLogical) {
if (((ExpressionLogical) e).isTerminal) {
index = expressionLists.length - 1;
}
}
expressionLists[index].add(e);
}
void expandConditions() {
if (hasOuterJoin) {
return;
}
expandConditions(joinExpressions, true);
expandConditions(whereExpressions, false);
}
void expandConditions(HsqlArrayList[] array, boolean isJoin) {
for (int i = 0; i < rangeVariables.length; i++) {
HsqlArrayList list = array[i];
tempMap.clear();
tempSet.clear();
boolean hasChain = false;
for (int j = 0; j < list.size(); j++) {
Expression e = (Expression) list.get(j);
if (!e.isColumnEqual) {
continue;
}
if (e.getLeftNode().getRangeVariable()
== e.getRightNode().getRangeVariable()) {
continue;
}
if (e.getLeftNode().getRangeVariable() == rangeVariables[i]) {
tempMap.put(e.getLeftNode().getColumn(), e.getRightNode());
if (!tempSet.add(e.getLeftNode().getColumn())) {
hasChain = true;
}
} else if (e.getRightNode().getRangeVariable()
== rangeVariables[i]) {
tempMap.put(e.getRightNode().getColumn(), e.getLeftNode());
if (!tempSet.add(e.getRightNode().getColumn())) {
hasChain = true;
}
}
}
if (hasChain) {
Iterator keyIt = tempMap.keySet().iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
Iterator it = tempMap.get(key);
tempSet.clear();
while (it.hasNext()) {
tempSet.add(it.next());
}
while (tempSet.size() > 1) {
Expression e1 =
(Expression) tempSet.remove(tempSet.size() - 1);
for (int j = 0; j < tempSet.size(); j++) {
Expression e2 = (Expression) tempSet.get(j);
closeJoinChain(array, e1, e2);
}
}
}
}
}
}
void closeJoinChain(HsqlArrayList[] array, Expression e1, Expression e2) {
int idx1 = rangeVarSet.getIndex(e1.getRangeVariable());
int idx2 = rangeVarSet.getIndex(e2.getRangeVariable());
int index = idx1 > idx2 ? idx1
: idx2;
if (idx1 == -1 || idx2 == -1) {
return;
}
Expression e = new ExpressionLogical(e1, e2);
for (int i = 0; i < array[index].size(); i++) {
if (e.equals(array[index].get(i))) {
return;
}
}
array[index].add(e);
}
/**
* Assigns conditions to range variables and converts suitable IN conditions
* to table lookup.
*/
void assignToRangeVariables() {
for (int i = 0; i < rangeVariables.length; i++) {
boolean hasIndex = false;
RangeVariableConditions conditions;
if (i < firstLeftJoinIndex
&& firstRightJoinIndex == rangeVariables.length) {
conditions = rangeVariables[i].joinConditions[0];
joinExpressions[i].addAll(whereExpressions[i]);
assignToRangeVariable(rangeVariables[i], conditions, i,
joinExpressions[i]);
assignToRangeVariable(conditions, joinExpressions[i]);
} else {
conditions = rangeVariables[i].joinConditions[0];
assignToRangeVariable(rangeVariables[i], conditions, i,
joinExpressions[i]);
conditions = rangeVariables[i].joinConditions[0];
if (conditions.hasIndex()) {
hasIndex = true;
}
assignToRangeVariable(conditions, joinExpressions[i]);
conditions = rangeVariables[i].whereConditions[0];
// assign to all right range variables to the right
for (int j = i + 1; j < rangeVariables.length; j++) {
if (rangeVariables[j].isRightJoin) {
assignToRangeVariable(
rangeVariables[j].whereConditions[0],
whereExpressions[i]);
}
}
// index only on one condition -- right and full can have index
if (!hasIndex) {
assignToRangeVariable(rangeVariables[i], conditions, i,
whereExpressions[i]);
}
assignToRangeVariable(conditions, whereExpressions[i]);
}
}
if (expandInExpression && inExpressionCount != 0) {
setInConditionsAsTables();
}
}
void assignToRangeVariable(RangeVariableConditions conditions,
HsqlArrayList exprList) {
for (int j = 0, size = exprList.size(); j < size; j++) {
Expression e = (Expression) exprList.get(j);
conditions.addCondition(e);
}
}
Expression getIndexableColumn(HsqlArrayList exprList, int start) {
for (int j = start, size = exprList.size(); j < size; j++) {
Expression e = (Expression) exprList.get(j);
if (e.getType() != OpTypes.EQUAL) {
continue;
}
if (e.exprSubType == OpTypes.ALL_QUANTIFIED) {
continue;
}
if (e.exprSubType == OpTypes.ANY_QUANTIFIED) {
// can process in the future
continue;
}
tempSet.clear();
e.collectRangeVariables(rangeVariables, tempSet);
if (tempSet.size() != 1) {
continue;
}
RangeVariable range = (RangeVariable) tempSet.get(0);
e = e.getIndexableExpression(range);
if (e == null) {
continue;
}
e = e.getLeftNode();
if (e.getType() != OpTypes.COLUMN) {
continue;
}
int colIndex = e.getColumnIndex();
if (range.rangeTable.indexTypeForColumn(session, colIndex)
!= Index.INDEX_NONE) {
return e;
}
}
return null;
}
/**
* Assigns a set of conditions to a range variable.
*/
void assignToRangeVariable(RangeVariable rangeVar,
RangeVariableConditions conditions,
int rangeVarIndex, HsqlArrayList exprList) {
if (exprList.isEmpty()) {
return;
}
setIndexConditions(conditions, exprList, rangeVarIndex, true);
}
private void setIndexConditions(RangeVariableConditions conditions,
HsqlArrayList exprList, int rangeVarIndex,
boolean includeOr) {
boolean hasIndex;
colIndexSetEqual.clear();
colIndexSetOther.clear();
for (int j = 0, size = exprList.size(); j < size; j++) {
Expression e = (Expression) exprList.get(j);
if (e == null) {
continue;
}
// repeat check required for OR
if (!e.isIndexable(conditions.rangeVar)) {
continue;
}
int type = e.getType();
switch (type) {
case OpTypes.OR : {
continue;
}
case OpTypes.COLUMN : {
continue;
}
case OpTypes.EQUAL : {
if (e.exprSubType == OpTypes.ANY_QUANTIFIED
|| e.exprSubType == OpTypes.ALL_QUANTIFIED) {
continue;
}
if (e.getLeftNode().getRangeVariable()
!= conditions.rangeVar) {
continue;
}
int colIndex = e.getLeftNode().getColumnIndex();
colIndexSetEqual.add(colIndex);
break;
}
case OpTypes.IS_NULL : {
if (e.getLeftNode().getRangeVariable()
!= conditions.rangeVar) {
continue;
}
if (conditions.rangeVar.isLeftJoin) {
continue;
}
int colIndex = e.getLeftNode().getColumnIndex();
colIndexSetEqual.add(colIndex);
break;
}
case OpTypes.NOT : {
if (e.getLeftNode().getLeftNode().getRangeVariable()
!= conditions.rangeVar) {
continue;
}
if (conditions.rangeVar.isLeftJoin) {
continue;
}
int colIndex =
e.getLeftNode().getLeftNode().getColumnIndex();
int count = colIndexSetOther.get(colIndex, 0);
colIndexSetOther.put(colIndex, count + 1);
break;
}
case OpTypes.SMALLER :
case OpTypes.SMALLER_EQUAL :
case OpTypes.GREATER :
case OpTypes.GREATER_EQUAL : {
if (e.getLeftNode().getRangeVariable()
!= conditions.rangeVar) {
continue;
}
int colIndex = e.getLeftNode().getColumnIndex();
int count = colIndexSetOther.get(colIndex, 0);
colIndexSetOther.put(colIndex, count + 1);
break;
}
default : {
Error.runtimeError(ErrorCode.U_S0500,
"RangeVariableResolver");
}
}
}
setEqualityConditions(conditions, exprList, rangeVarIndex);
hasIndex = conditions.hasIndex();
if (!hasIndex) {
setNonEqualityConditions(conditions, exprList, rangeVarIndex);
}
if (rangeVarIndex == 0 && sortAndSlice.usingIndex) {
hasIndex = true;
} else {
hasIndex = conditions.hasIndex();
}
// no index found
boolean isOR = false;
if (!hasIndex && includeOr) {
for (int j = 0, size = exprList.size(); j < size; j++) {
Expression e = (Expression) exprList.get(j);
if (e == null) {
continue;
}
if (e.getType() == OpTypes.OR) {
//
hasIndex = ((ExpressionLogical) e).isIndexable(
conditions.rangeVar);
if (hasIndex) {
hasIndex = setOrConditions(conditions,
(ExpressionLogical) e,
rangeVarIndex);
}
if (hasIndex) {
exprList.set(j, null);
isOR = true;
break;
}
} else if (e.getType() == OpTypes.EQUAL
&& e.exprSubType == OpTypes.ANY_QUANTIFIED) {
if (rangeVarIndex >= firstLeftJoinIndex
|| firstRightJoinIndex != rangeVariables.length) {
continue;
}
if (e.getRightNode().isCorrelated()) {
continue;
}
OrderedIntHashSet set = new OrderedIntHashSet();
((ExpressionLogical) e).addLeftColumnsForAllAny(
conditions.rangeVar, set);
Index index =
conditions.rangeVar.rangeTable.getIndexForColumns(
session, set, false);
// code to disable IN optimisation
// index = null;
if (index != null
&& inExpressions[rangeVarIndex] == null) {
inExpressions[rangeVarIndex] = e;
inInJoin[rangeVarIndex] = conditions.isJoin;
inExpressionCount++;
exprList.set(j, null);
break;
}
}
}
}
for (int i = 0, size = exprList.size(); i < size; i++) {
Expression e = (Expression) exprList.get(i);
if (e == null) {
continue;
}
if (isOR) {
for (int j = 0; j < conditions.rangeVar.joinConditions.length;
j++) {
if (conditions.isJoin) {
conditions.rangeVar.joinConditions[j]
.nonIndexCondition =
ExpressionLogical
.andExpressions(e, conditions.rangeVar
.joinConditions[j].nonIndexCondition);
} else {
conditions.rangeVar.whereConditions[j]
.nonIndexCondition =
ExpressionLogical
.andExpressions(e, conditions.rangeVar
.whereConditions[j].nonIndexCondition);
}
}
} else {
conditions.addCondition(e);
}
}
}
private boolean setOrConditions(RangeVariableConditions conditions,
ExpressionLogical orExpression,
int rangeVarIndex) {
HsqlArrayList orExprList = new HsqlArrayList();
decomposeOrConditions(orExpression, orExprList);
RangeVariableConditions[] conditionsArray =
new RangeVariableConditions[orExprList.size()];
for (int i = 0; i < orExprList.size(); i++) {
HsqlArrayList exprList = new HsqlArrayList();
Expression e = (Expression) orExprList.get(i);
decomposeAndConditions(session, e, exprList);
RangeVariableConditions c =
new RangeVariableConditions(conditions);
setIndexConditions(c, exprList, rangeVarIndex, false);
conditionsArray[i] = c;
if (!c.hasIndex()) {
// deep OR
return false;
}
}
Expression exclude = null;
for (int i = 0; i < conditionsArray.length; i++) {
RangeVariableConditions c = conditionsArray[i];
conditionsArray[i].excludeConditions = exclude;
if (i == conditionsArray.length - 1) {
break;
}
Expression e = null;
if (c.indexCond != null) {
for (int k = 0; k < c.indexedColumnCount; k++) {
e = ExpressionLogical.andExpressions(e, c.indexCond[k]);
}
}
e = ExpressionLogical.andExpressions(e, c.indexEndCondition);
e = ExpressionLogical.andExpressions(e, c.nonIndexCondition);
exclude = ExpressionLogical.orExpressions(e, exclude);
}
if (exclude != null) {
// return false;
}
if (conditions.isJoin) {
conditions.rangeVar.joinConditions = conditionsArray;
conditionsArray = new RangeVariableConditions[orExprList.size()];
ArrayUtil.fillArray(conditionsArray,
conditions.rangeVar.whereConditions[0]);
conditions.rangeVar.whereConditions = conditionsArray;
} else {
conditions.rangeVar.whereConditions = conditionsArray;
conditionsArray = new RangeVariableConditions[orExprList.size()];
ArrayUtil.fillArray(conditionsArray,
conditions.rangeVar.joinConditions[0]);
conditions.rangeVar.joinConditions = conditionsArray;
}
return true;
}
private void setEqualityConditions(RangeVariableConditions conditions,
HsqlArrayList exprList,
int rangeVarIndex) {
Index idx = null;
if (rangeVarIndex == 0 && sortAndSlice.usingIndex) {
idx = sortAndSlice.primaryTableIndex;
if (idx != null) {
conditions.rangeIndex = idx;
}
}
if (idx == null) {
idx = conditions.rangeVar.rangeTable.getIndexForColumns(session,
colIndexSetEqual, false);
}
if (idx == null) {
return;
}
int[] cols = idx.getColumns();
int colCount = cols.length;
Expression[] firstRowExpressions = new Expression[cols.length];
for (int j = 0; j < exprList.size(); j++) {
Expression e = (Expression) exprList.get(j);
if (e == null) {
continue;
}
int type = e.getType();
if (type == OpTypes.EQUAL || type == OpTypes.IS_NULL) {
if (e.getLeftNode().getRangeVariable()
!= conditions.rangeVar) {
continue;
}
if (!e.isIndexable(conditions.rangeVar)) {
continue;
}
int offset = ArrayUtil.find(cols,
e.getLeftNode().getColumnIndex());
if (offset != -1 && firstRowExpressions[offset] == null) {
firstRowExpressions[offset] = e;
exprList.set(j, null);
continue;
}
}
}
boolean hasNull = false;
for (int i = 0; i < firstRowExpressions.length; i++) {
Expression e = firstRowExpressions[i];
if (e == null) {
if (colCount == cols.length) {
colCount = i;
}
hasNull = true;
continue;
}
if (hasNull) {
conditions.addCondition(e);
firstRowExpressions[i] = null;
}
}
if (colCount > 0) {
conditions.addIndexCondition(firstRowExpressions, idx, colCount);
}
}
private void setNonEqualityConditions(RangeVariableConditions conditions,
HsqlArrayList exprList,
int rangeVarIndex) {
if (colIndexSetOther.isEmpty()) {
return;
}
int currentCount = 0;
int currentIndex = 0;
Iterator it = colIndexSetOther.keySet().iterator();
while (it.hasNext()) {
int colIndex = it.nextInt();
int colCount = colIndexSetOther.get(colIndex);
if (colCount > currentCount) {
currentIndex = colIndex;
}
}
Index idx = null;
if (rangeVarIndex == 0 && sortAndSlice.usingIndex) {
idx = sortAndSlice.primaryTableIndex;
}
if (idx == null) {
idx = conditions.rangeVar.rangeTable.getIndexForColumn(session,
currentIndex);
}
if (idx == null) {
it = colIndexSetOther.keySet().iterator();
while (it.hasNext()) {
int colIndex = it.nextInt();
if (colIndex != currentIndex) {
idx = conditions.rangeVar.rangeTable.getIndexForColumn(
session, colIndex);
if (idx != null) {
break;
}
}
}
}
if (idx == null) {
return;
}
int[] cols = idx.getColumns();
for (int j = 0; j < exprList.size(); j++) {
Expression e = (Expression) exprList.get(j);
if (e == null) {
continue;
}
boolean isIndexed = false;
switch (e.getType()) {
case OpTypes.NOT : {
if (e.getLeftNode().getType() == OpTypes.IS_NULL
&& cols[0]
== e.getLeftNode().getLeftNode()
.getColumnIndex()) {
isIndexed = true;
}
break;
}
case OpTypes.SMALLER :
case OpTypes.SMALLER_EQUAL :
case OpTypes.GREATER :
case OpTypes.GREATER_EQUAL : {
if (cols[0] == e.getLeftNode().getColumnIndex()) {
if (e.getRightNode() != null
&& !e.getRightNode().isCorrelated()) {
isIndexed = true;
}
}
break;
}
}
if (isIndexed) {
Expression[] firstRowExpressions =
new Expression[idx.getColumnCount()];
firstRowExpressions[0] = e;
conditions.addIndexCondition(firstRowExpressions, idx, 1);
exprList.set(j, null);
break;
}
}
}
/**
* Converts an IN conditions into a JOIN
*/
void setInConditionsAsTables() {
for (int i = rangeVariables.length - 1; i >= 0; i--) {
RangeVariable rangeVar = rangeVariables[i];
ExpressionLogical in = (ExpressionLogical) inExpressions[i];
if (in != null) {
OrderedIntHashSet set = new OrderedIntHashSet();
in.addLeftColumnsForAllAny(rangeVar, set);
Index index = rangeVar.rangeTable.getIndexForColumns(session,
set, false);
int indexedColCount = 0;
for (int j = 0; j < index.getColumnCount(); j++) {
if (set.contains(index.getColumns()[j])) {
indexedColCount++;
} else {
break;
}
}
RangeVariable newRangeVar =
new RangeVariable(in.getRightNode().getTable(), null,
null, null, compileContext);
newRangeVar.isGenerated = true;
RangeVariable[] newList =
new RangeVariable[rangeVariables.length + 1];
ArrayUtil.copyAdjustArray(rangeVariables, newList,
newRangeVar, i, 1);
rangeVariables = newList;
// make two columns as arg
Expression[] exprList = new Expression[index.getColumnCount()];
for (int j = 0; j < indexedColCount; j++) {
int leftIndex = index.getColumns()[j];
int rightIndex = set.getIndex(leftIndex);
Expression e = new ExpressionLogical(rangeVar, leftIndex,
newRangeVar,
rightIndex);
exprList[j] = e;
}
boolean isOuter = rangeVariables[i].isLeftJoin
|| rangeVariables[i].isRightJoin;
RangeVariableConditions conditions =
!inInJoin[i] && isOuter ? rangeVar.whereConditions[0]
: rangeVar.joinConditions[0];
conditions.addIndexCondition(exprList, index, indexedColCount);
for (int j = 0; j < set.size(); j++) {
int leftIndex = set.get(j);
int rightIndex = j;
Expression e = new ExpressionLogical(rangeVar, leftIndex,
newRangeVar,
rightIndex);
conditions.addCondition(e);
}
}
}
}
}
| |
package se.kodapan.osm.domain.root.indexed;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.kodapan.osm.domain.root.Root;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
/**
* Implementation using Lucene 3.5.0.
* <p/>
* Created by kalle on 10/19/13.
*/
public class IndexedRootImpl extends IndexedRoot<Query> {
private static Logger log = LoggerFactory.getLogger(IndexedRootImpl.class);
private QueryFactories<Query> queryFactories = new QueryFactoriesImpl();
@Override
public QueryFactories<Query> getQueryFactories() {
return queryFactories;
}
private File fileSystemDirectory;
private Directory directory;
private IndexWriter indexWriter;
private SearcherManager searcherManager;
private OsmObjectVisitor<Void> addVisitor = new AddVisitor();
public IndexedRootImpl(Root decorated, File fileSystemDirectory) {
super(decorated);
this.fileSystemDirectory = fileSystemDirectory;
}
public IndexedRootImpl(Root decorated) {
super(decorated);
}
private Analyzer analyzer = new KeywordAnalyzer();
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
if (open) {
throw new RuntimeException("Need to close current Directory first.");
}
this.directory = directory;
}
@Override
public void reconstruct(int numberOfThreads) throws IOException {
final ConcurrentLinkedQueue<OsmObject> queue = new ConcurrentLinkedQueue<OsmObject>();
Enumerator<Node> nodes = enumerateNodes();
Node node;
while ((node = nodes.next()) != null) {
queue.add(node);
}
Enumerator<Way> ways = enumerateWays();
Way way;
while ((way = ways.next()) != null) {
queue.add(way);
}
Enumerator<Relation> relations = enumerateRelations();
Relation relation;
while ((relation = relations.next()) != null) {
queue.add(relation);
}
indexWriter.deleteAll();
Thread[] threads = new Thread[numberOfThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
OsmObject object;
while ((object = queue.poll()) != null) {
object.accept(indexVisitor);
}
}
});
threads[i].setName("Reconstruct IndexableRoot thread #" + i);
threads[i].setDaemon(true);
threads[i].start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
commit();
}
private boolean open = false;
@Override
public void open() throws IOException {
if (fileSystemDirectory == null) {
directory = new RAMDirectory();
} else {
directory = new SimpleFSDirectory(fileSystemDirectory);
}
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35, analyzer);
config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
SearcherWarmer warmer = null;
ExecutorService es = null; // todo
indexWriter = new IndexWriter(directory, config);
searcherManager = new SearcherManager(indexWriter, true, warmer, es);
open = true;
}
@Override
public void close() throws IOException {
searcherManager.close();
indexWriter.close();
directory.close();
open = false;
}
private IndexVisitor indexVisitor = new IndexVisitor();
private class IndexVisitor implements OsmObjectVisitor<Void>, Serializable {
private static final long serialVersionUID = 1l;
private void addObjectFields(OsmObject object, Document document) {
if (object.getTags() != null) {
for (Map.Entry<String, String> tag : object.getTags().entrySet()) {
document.add(new Field("tag.key", tag.getKey(), Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
document.add(new Field("tag.value", tag.getValue(), Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
document.add(new Field("tag.key_and_value", tag.getKey() + "=" + tag.getValue(), Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
}
}
}
public NumericField numericCoordinateFieldFactory(String name, double value) {
NumericField field = new NumericField(name, 4, Field.Store.NO, true);
field.setDoubleValue(value);
return field;
}
@Override
public Void visit(Node node) {
Document document = new Document();
document.add(new Field("class", "node", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
document.add(new Field("node.identity", String.valueOf(node.getId()), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
if (node.isLoaded()) {
document.add(numericCoordinateFieldFactory("node.latitude", node.getLatitude()));
document.add(numericCoordinateFieldFactory("node.longitude", node.getLongitude()));
} else if (log.isInfoEnabled()) {
log.info("Indexing node " + node.getId() + " which has not been loaded. Coordinates will not be searchable.");
}
addObjectFields(node, document);
try {
indexWriter.updateDocument(new Term("node.identity", String.valueOf(node.getId())), document);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
@Override
public Void visit(Way way) {
Document document = new Document();
document.add(new Field("class", "way", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
document.add(new Field("way.identity", String.valueOf(way.getId()), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
if (way.getNodes() != null) {
double southLatitude = 90d;
double westLongitude = 180d;
double northLatitude = -90d;
double eastLongitude = -180d;
boolean hasLoadedNodes = false;
for (Node node : way.getNodes()) {
if (!node.isLoaded()) {
if (log.isDebugEnabled()) {
log.debug("Skipping non loaded node " + node.getId() + " in way " + way.getId());
}
continue;
}
if (node.getLatitude() < southLatitude) {
southLatitude = node.getLatitude();
}
if (node.getLatitude() > northLatitude) {
northLatitude = node.getLatitude();
}
if (node.getLongitude() < westLongitude) {
westLongitude = node.getLongitude();
}
if (node.getLongitude() > eastLongitude) {
eastLongitude = node.getLongitude();
}
hasLoadedNodes = true;
}
if (hasLoadedNodes) {
document.add(numericCoordinateFieldFactory("way.envelope.south_latitude", southLatitude));
document.add(numericCoordinateFieldFactory("way.envelope.west_longitude", westLongitude));
document.add(numericCoordinateFieldFactory("way.envelope.north_latitude", northLatitude));
document.add(numericCoordinateFieldFactory("way.envelope.east_longitude", eastLongitude));
} else if (log.isInfoEnabled()) {
log.info("Indexing way " + way.getId() + " which contains nodes that are not loaded. Coordinates will not be searchable.");
}
}
addObjectFields(way, document);
try {
indexWriter.updateDocument(new Term("way.identity", String.valueOf(way.getId())), document);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
@Override
public Void visit(Relation relation) {
Document document = new Document();
document.add(new Field("class", "relation", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
document.add(new Field("relation.identity", String.valueOf(relation.getId()), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
// todo envelope
addObjectFields(relation, document);
try {
indexWriter.updateDocument(new Term("relation.identity", String.valueOf(relation.getId())), document);
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
}
@Override
public Set<OsmObject> remove(OsmObject object) {
Set<OsmObject> affectedRelations = object.accept(removeVisitor);
return affectedRelations;
}
private RemoveVisitor removeVisitor = new RemoveVisitor();
private class RemoveVisitor implements OsmObjectVisitor<Set<OsmObject>>, Serializable {
private static final long serialVersionUID = 1l;
@Override
public Set<OsmObject> visit(Node node) {
Set<OsmObject> affectedObjects = getDecorated().remove(node);
try {
indexWriter.deleteDocuments(new Term("node.identity", String.valueOf(node.getId())));
} catch (IOException e) {
throw new RuntimeException(e);
}
for (OsmObject object : affectedObjects) {
object.accept(indexVisitor);
}
return affectedObjects;
}
@Override
public Set<OsmObject> visit(Way way) {
Set<OsmObject> affectedObjects = getDecorated().remove(way);
try {
indexWriter.deleteDocuments(new Term("way.identity", String.valueOf(way.getId())));
} catch (IOException e) {
throw new RuntimeException(e);
}
for (OsmObject object : affectedObjects) {
object.accept(indexVisitor);
}
return affectedObjects;
}
@Override
public Set<OsmObject> visit(Relation relation) {
Set<OsmObject> affectedObjects = getDecorated().remove(relation);
try {
indexWriter.deleteDocuments(new Term("relation.identity", String.valueOf(relation.getId())));
} catch (IOException e) {
throw new RuntimeException(e);
}
for (OsmObject object : affectedObjects) {
object.accept(indexVisitor);
}
return affectedObjects;
}
}
private class AddVisitor implements OsmObjectVisitor<Void>, Serializable {
private static final long serialVersionUID = 1l;
@Override
public Void visit(Node node) {
getDecorated().add(node);
node.accept(indexVisitor);
return null;
}
@Override
public Void visit(Way way) {
getDecorated().add(way);
way.accept(indexVisitor);
return null;
}
@Override
public Void visit(Relation relation) {
getDecorated().add(relation);
relation.accept(indexVisitor);
return null;
}
}
@Override
public void add(OsmObject osmObject) {
osmObject.accept(addVisitor);
}
@Override
public void commit() throws IOException {
indexWriter.commit();
searcherManager.maybeReopen();
}
@Override
public Map<OsmObject, Float> search(Query query) throws IOException {
IndexSearcher indexSearcher = searcherManager.acquire();
try {
final Map<OsmObject, Float> searchResults = new HashMap<OsmObject, Float>();
Collector collector = new Collector() {
private Scorer scorer;
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
}
@Override
public void collect(int doc) throws IOException {
Document document = indexReader.document(doc);
String objectClass = document.get("class");
OsmObject object;
if ("node".equals(objectClass)) {
object = getNode(Long.valueOf(document.get("node.identity")));
} else if ("way".equals(objectClass)) {
object = getWay(Long.valueOf(document.get("way.identity")));
} else if ("relation".equals(objectClass)) {
object = getRelation(Long.valueOf(document.get("relation.identity")));
} else {
throw new RuntimeException("Unknown class " + objectClass);
}
searchResults.put(object, scorer.score());
}
private IndexReader indexReader;
private int docBase;
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
this.indexReader = reader;
this.docBase = docBase;
}
@Override
public boolean acceptsDocsOutOfOrder() {
return true;
}
};
indexSearcher.search(query, collector);
return searchResults;
} finally {
searcherManager.release(indexSearcher);
}
}
}
| |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.ApiMessage;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Generated;
import javax.annotation.Nullable;
@Generated("by GAPIC")
@BetaApi
/** Contains a list of TargetSslProxy resources. */
public final class TargetSslProxyList implements ApiMessage {
private final String id;
private final List<TargetSslProxy> items;
private final String kind;
private final String nextPageToken;
private final String selfLink;
private final Warning warning;
private TargetSslProxyList() {
this.id = null;
this.items = null;
this.kind = null;
this.nextPageToken = null;
this.selfLink = null;
this.warning = null;
}
private TargetSslProxyList(
String id,
List<TargetSslProxy> items,
String kind,
String nextPageToken,
String selfLink,
Warning warning) {
this.id = id;
this.items = items;
this.kind = kind;
this.nextPageToken = nextPageToken;
this.selfLink = selfLink;
this.warning = warning;
}
@Override
public Object getFieldValue(String fieldName) {
if ("id".equals(fieldName)) {
return id;
}
if ("items".equals(fieldName)) {
return items;
}
if ("kind".equals(fieldName)) {
return kind;
}
if ("nextPageToken".equals(fieldName)) {
return nextPageToken;
}
if ("selfLink".equals(fieldName)) {
return selfLink;
}
if ("warning".equals(fieldName)) {
return warning;
}
return null;
}
@Nullable
@Override
public ApiMessage getApiMessageRequestBody() {
return null;
}
@Nullable
@Override
/**
* The fields that should be serialized (even if they have empty values). If the containing
* message object has a non-null fieldmask, then all the fields in the field mask (and only those
* fields in the field mask) will be serialized. If the containing object does not have a
* fieldmask, then only non-empty fields will be serialized.
*/
public List<String> getFieldMask() {
return null;
}
/** [Output Only] Unique identifier for the resource; defined by the server. */
public String getId() {
return id;
}
/** A list of TargetSslProxy resources. */
public List<TargetSslProxy> getItemsList() {
return items;
}
/** Type of resource. */
public String getKind() {
return kind;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public String getNextPageToken() {
return nextPageToken;
}
/** [Output Only] Server-defined URL for this resource. */
public String getSelfLink() {
return selfLink;
}
/** [Output Only] Informational warning message. */
public Warning getWarning() {
return warning;
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(TargetSslProxyList prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
public static TargetSslProxyList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final TargetSslProxyList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new TargetSslProxyList();
}
public static class Builder {
private String id;
private List<TargetSslProxy> items;
private String kind;
private String nextPageToken;
private String selfLink;
private Warning warning;
Builder() {}
public Builder mergeFrom(TargetSslProxyList other) {
if (other == TargetSslProxyList.getDefaultInstance()) return this;
if (other.getId() != null) {
this.id = other.id;
}
if (other.getItemsList() != null) {
this.items = other.items;
}
if (other.getKind() != null) {
this.kind = other.kind;
}
if (other.getNextPageToken() != null) {
this.nextPageToken = other.nextPageToken;
}
if (other.getSelfLink() != null) {
this.selfLink = other.selfLink;
}
if (other.getWarning() != null) {
this.warning = other.warning;
}
return this;
}
Builder(TargetSslProxyList source) {
this.id = source.id;
this.items = source.items;
this.kind = source.kind;
this.nextPageToken = source.nextPageToken;
this.selfLink = source.selfLink;
this.warning = source.warning;
}
/** [Output Only] Unique identifier for the resource; defined by the server. */
public String getId() {
return id;
}
/** [Output Only] Unique identifier for the resource; defined by the server. */
public Builder setId(String id) {
this.id = id;
return this;
}
/** A list of TargetSslProxy resources. */
public List<TargetSslProxy> getItemsList() {
return items;
}
/** A list of TargetSslProxy resources. */
public Builder addAllItems(List<TargetSslProxy> items) {
if (this.items == null) {
this.items = new LinkedList<>();
}
this.items.addAll(items);
return this;
}
/** A list of TargetSslProxy resources. */
public Builder addItems(TargetSslProxy items) {
if (this.items == null) {
this.items = new LinkedList<>();
}
this.items.add(items);
return this;
}
/** Type of resource. */
public String getKind() {
return kind;
}
/** Type of resource. */
public Builder setKind(String kind) {
this.kind = kind;
return this;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public String getNextPageToken() {
return nextPageToken;
}
/**
* [Output Only] This token allows you to get the next page of results for list requests. If the
* number of results is larger than maxResults, use the nextPageToken as a value for the query
* parameter pageToken in the next list request. Subsequent list requests will have their own
* nextPageToken to continue paging through the results.
*/
public Builder setNextPageToken(String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
/** [Output Only] Server-defined URL for this resource. */
public String getSelfLink() {
return selfLink;
}
/** [Output Only] Server-defined URL for this resource. */
public Builder setSelfLink(String selfLink) {
this.selfLink = selfLink;
return this;
}
/** [Output Only] Informational warning message. */
public Warning getWarning() {
return warning;
}
/** [Output Only] Informational warning message. */
public Builder setWarning(Warning warning) {
this.warning = warning;
return this;
}
public TargetSslProxyList build() {
return new TargetSslProxyList(id, items, kind, nextPageToken, selfLink, warning);
}
public Builder clone() {
Builder newBuilder = new Builder();
newBuilder.setId(this.id);
newBuilder.addAllItems(this.items);
newBuilder.setKind(this.kind);
newBuilder.setNextPageToken(this.nextPageToken);
newBuilder.setSelfLink(this.selfLink);
newBuilder.setWarning(this.warning);
return newBuilder;
}
}
@Override
public String toString() {
return "TargetSslProxyList{"
+ "id="
+ id
+ ", "
+ "items="
+ items
+ ", "
+ "kind="
+ kind
+ ", "
+ "nextPageToken="
+ nextPageToken
+ ", "
+ "selfLink="
+ selfLink
+ ", "
+ "warning="
+ warning
+ "}";
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof TargetSslProxyList) {
TargetSslProxyList that = (TargetSslProxyList) o;
return Objects.equals(this.id, that.getId())
&& Objects.equals(this.items, that.getItemsList())
&& Objects.equals(this.kind, that.getKind())
&& Objects.equals(this.nextPageToken, that.getNextPageToken())
&& Objects.equals(this.selfLink, that.getSelfLink())
&& Objects.equals(this.warning, that.getWarning());
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(id, items, kind, nextPageToken, selfLink, warning);
}
}
| |
package net.glider.src.strucures;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.glider.src.blocks.BlockContainerMod;
import net.glider.src.blocks.BlockMod;
import net.glider.src.tiles.TileEntityInfo;
import net.glider.src.tiles.TileEntityRemoveInfo;
import net.glider.src.utils.ForgeDirectionUtils;
import net.glider.src.utils.ItemUtil;
import net.glider.src.utils.MatrixHelper;
import net.glider.src.utils.OreDictItemStack;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
public class BuildHandler {
public static StructureStub str1 = new StructureStub(true);
public static StructureHall str2 = new StructureHall(false);
public static StructureCornerHall str3 = new StructureCornerHall(false);
public static StructureCrossroad str4 = new StructureCrossroad(false);
public static StructureHallWAirlock str5 = new StructureHallWAirlock(false);
public static StructureWindow str6 = new StructureWindow(false);
public static StructureCupola str7 = new StructureCupola(false);
public static StructureDockingPort str8 = new StructureDockingPort(false);
public static StructureSolarPanel str9 = new StructureSolarPanel(false);
public static StructureThall str10 = new StructureThall(false);
public static StructureBigHall str11 = new StructureBigHall(false);
public static StructureGreenHouse str12 = new StructureGreenHouse();
public static StructurePierce str13 = new StructurePierce();
private static boolean haveContainerItem(List<ItemStack> found, OreDictItemStack is)
{
for (int i = 0; i < found.size(); i++)
{
OreDictItemStack curr = new OreDictItemStack(found.get(i));
if (is != null && curr != null)
{
if (is.isStackEqual(curr, false))
{
return true;
}
}
}
return false;
}
public static boolean CheckItems(World world, String FuncName, NBTTagList items, EntityPlayer player, int rot)
{
if (player.capabilities.isCreativeMode)
{
return true;
}
Structure CurStr = Structure.FindStructure(FuncName);
if (CurStr instanceof StructureRotatable)
{
((StructureRotatable) CurStr).setRotation(rot);
}
List<OreDictItemStack> required = CurStr.getRequiredItems();
for (int i = 0; i < required.size(); i++)
{
OreDictItemStack curr = required.get(i);
for (int j = 0; j < required.size(); j += 0)
{
boolean removed = false;
if (j != i)
{
OreDictItemStack last = required.get(j);
if (last != null && curr != null)
{
if (curr.isStackEqual(last, true))
{
curr.example.stackSize += last.example.stackSize;
required.remove(j);
removed = true;
}
}
}
if (!removed)
{
j++;
}
}
}
List<ItemStack> found = new ArrayList();
if (items.tagCount() > 0)
{
for (int i = 0; i < items.tagCount(); i++)
{
int[] pos = items.func_150306_c(i);
if (world != null)
{
TileEntity te = world.getTileEntity(pos[0], pos[1], pos[2]);
if (te instanceof IInventory)
{
IInventory inv = (IInventory) te;
if (inv.getSizeInventory() > 0)
{
for (int j = 0; j < inv.getSizeInventory(); j++)
{
if (inv.getStackInSlot(j) != null)
{
found.add(inv.getStackInSlot(j).copy());
}
}
}
}
}
}
}
if (player.inventory.getSizeInventory() > 0)
{
for (int j = 0; j < player.inventory.getSizeInventory(); j++)
{
if (player.inventory.getStackInSlot(j) != null)
{
found.add(player.inventory.getStackInSlot(j).copy());
}
}
}
for (int i = 0; i < found.size(); i++)
{
ItemStack curr = found.get(i);
for (int j = 0; j < found.size(); j += 0)
{
boolean removed = false;
if (j != i)
{
ItemStack last = found.get(j);
if (last != null && curr != null)
{
if (ItemUtil.AreItemStackEqual(curr, last, true))
{
curr.stackSize += last.stackSize;
found.remove(j);
removed = true;
}
}
}
if (!removed)
{
j++;
}
}
}
// boolean skipped = false;
for (int i = 0; i < required.size(); i++)
{
if (!haveContainerItem(found, required.get(i)))
{
return false;
}
}
for (int k = 0; k < required.size(); k++)
{
OreDictItemStack wantedItem = required.get(k);
boolean Found = false;
for (int i = 0; i < items.tagCount(); i++)
{
int[] pos = items.func_150306_c(i);
if (world != null)
{
TileEntity te = world.getTileEntity(pos[0], pos[1], pos[2]);
if (te instanceof IInventory)
{
IInventory inv = (IInventory) te;
if (inv.getSizeInventory() > 0)
{
for (int j = 0; j < inv.getSizeInventory(); j++)
{
OreDictItemStack curr = new OreDictItemStack(inv.getStackInSlot(j));
if (wantedItem != null && curr != null)
{
if (wantedItem.isStackEqual(curr, true))
{
if (curr.example.stackSize >= wantedItem.example.stackSize)
{
Found = true;
inv.decrStackSize(j, wantedItem.example.stackSize);
if (inv.getStackInSlot(j) != null && inv.getStackInSlot(j).stackSize == 0)
{
inv.setInventorySlotContents(j, null);
}
break;
} else if (curr.example.stackSize > 0)
{
wantedItem.example.stackSize -= curr.example.stackSize;
inv.setInventorySlotContents(j, null);
}
}
}
}
if (Found)
{
break;
}
}
}
}
}
if (player.inventory.getSizeInventory() > 0)
{
for (int j = 0; j < player.inventory.getSizeInventory(); j++)
{
OreDictItemStack curr = new OreDictItemStack(player.inventory.getStackInSlot(j));
if (wantedItem != null && curr != null)
{
if (wantedItem.isStackEqual(curr, true))
{
if (curr.example.stackSize >= wantedItem.example.stackSize)
{
Found = true;
player.inventory.decrStackSize(j, wantedItem.example.stackSize);
if (player.inventory.getStackInSlot(j) != null && player.inventory.getStackInSlot(j).stackSize == 0)
{
player.inventory.setInventorySlotContents(j, null);
}
break;
} else if (curr.example.stackSize > 0)
{
wantedItem.example.stackSize -= curr.example.stackSize;
player.inventory.setInventorySlotContents(j, null);
}
}
}
}
}
if (!Found)
{
return false;
}
}
return true;
}
public static boolean HandleBuild(World world, ForgeDirection dir, String FuncName, int x, int y, int z, int rot, EntityPlayerMP player)
{
switch (FuncName) {
case "stub":
if (str1.Check(world, dir, x, y, z, -1))
{
str1.Build(world, dir, x, y, z);
return true;
}
case "hall":
if (str2.Check(world, dir, x, y, z, -1))
{
int[] IPoint = MatrixHelper.findMatrixPoint(world, dir, x, y, z);
Map Matrix;
if (IPoint != null)
{
Matrix = new HashMap<Integer, int[]>();
Matrix.clear();
Matrix = MatrixHelper.findTotalMatrix(world, IPoint);
// if (Matrix == null) return false;
if (Matrix != null) if (!isAvailable(dir, Matrix, IPoint[0], IPoint[1], IPoint[2])) return false;
} else Matrix = null;
// no if's for each dir!
int[] Spos = new int[] { x, y, z };
Spos = ForgeDirectionUtils.IncreaseByDir(dir, Spos, 9);
int[] Ppos;
if (IPoint != null)
{
Ppos = IPoint.clone();
Ppos = ForgeDirectionUtils.IncreaseByDir(dir, Ppos, 18);
} else
{
Ppos = new int[] { 0, 0, 0 };
}
TileEntityInfo te = null;
if (IPoint != null)
{
te = (TileEntityInfo) world.getTileEntity(IPoint[0], IPoint[1], IPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str2.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.ChildObjects.add(Nstr);
}
}
str2.Build(world, dir, x, y, z);
boolean Conect = false;
if (Matrix != null)
{
if (MatrixHelper.FindPointInMatrix(Matrix, Ppos) != null)
{
te = (TileEntityInfo) world.getTileEntity(Ppos[0], Ppos[1], Ppos[2]);
if (te != null)
{
if ((te.Object.getUnlocalizedName().equals("hall") || te.Object.getUnlocalizedName().equals("hallairlock"))
&& te.Object.placementDir.getOpposite() == dir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("corner") && str3.onTurn(te.Object.placementDir, te.Object.placementRotation).getOpposite() == dir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("crossroad") || te.Object.getUnlocalizedName().equals("bighall"))
{
ForgeDirection[] dirs = str4.getDirs(te.Object.placementDir);
for (int i = 0; i < 3; i++)
{
ForgeDirection STdir = dirs[i];
if (STdir.getOpposite() == dir)
{
Conect = true;
break;
}
}
} else if (te.Object.getUnlocalizedName().equals("thall"))
{
str10.setRotation(te.Object.placementRotation);
ForgeDirection[] dirs = str10.getDirs(te.Object.placementDir);
for (int i = 0; i < 2; i++)
{
ForgeDirection STdir = dirs[i];
if (STdir.getOpposite() == dir) Conect = true;
}
}
if (Conect)
{
int[] Ipos = ForgeDirectionUtils.IncreaseByDir(dir, IPoint.clone(), 9);
TileEntityInfo Ite = (TileEntityInfo) world.getTileEntity(Ipos[0], Ipos[1], Ipos[2]);
if (Ite != null)
{
Ite.Object.connections.add(te.Object);
}
}
}
}
}
if (!Conect)
{
str1.Build(world, dir, Spos[0], Spos[1], Spos[2]);
str2.ClearWay(world, dir, x, y, z);
} else
{
// no if's for each dir!
Spos = ForgeDirectionUtils.IncreaseByDir(dir.getOpposite(), Spos, 2);
str3.ClearWay(world, dir, Spos[0], Spos[1], Spos[2]);
str2.ClearWay(world, dir, x, y, z);
}
return true;
}
case "corner":
str3.setRotation(rot);
if (str3.Check(world, dir, x, y, z, -1))
{
int[] IPoint = MatrixHelper.findMatrixPoint(world, dir, x, y, z);
Map Matrix;
if (IPoint != null)
{
Matrix = new HashMap<Integer, int[]>();
Matrix.clear();
Matrix = MatrixHelper.findTotalMatrix(world, IPoint);
// if (Matrix == null) return false;
if (Matrix != null) if (!isAvailable(dir, Matrix, IPoint[0], IPoint[1], IPoint[2])) return false;
} else Matrix = null;
TileEntityInfo te = null;
if (IPoint != null)
{
te = (TileEntityInfo) world.getTileEntity(IPoint[0], IPoint[1], IPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str3.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.ChildObjects.add(Nstr);
}
}
str3.Build(world, dir, x, y, z);
ForgeDirection Ndir = str3.onTurn(dir, rot);
// no if's for each dir!
int[] Spos = new int[] { x, y, z };
Spos = ForgeDirectionUtils.IncreaseByDir(dir, Spos, 4);
Spos = ForgeDirectionUtils.IncreaseByDir(Ndir, Spos, 5);
int[] Ppos;
if (IPoint != null)
{
Ppos = IPoint.clone();
Ppos = ForgeDirectionUtils.IncreaseByDir(dir, Ppos, 9);
Ppos = ForgeDirectionUtils.IncreaseByDir(Ndir, Ppos, 9);
} else
{
Ppos = new int[] { 0, 0, 0 };
}
boolean Conect = false;
if (Matrix != null)
{
if (MatrixHelper.FindPointInMatrix(Matrix, Ppos) != null)
{
te = (TileEntityInfo) world.getTileEntity(Ppos[0], Ppos[1], Ppos[2]);
if (te != null)
{
if ((te.Object.getUnlocalizedName().equals("hall") || te.Object.getUnlocalizedName().equals("hallairlock"))
&& te.Object.placementDir.getOpposite() == Ndir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("corner") && str3.onTurn(te.Object.placementDir, te.Object.placementRotation).getOpposite() == Ndir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("crossroad") || te.Object.getUnlocalizedName().equals("bighall"))
{
ForgeDirection[] dirs = str4.getDirs(te.Object.placementDir);
for (int i = 0; i < 3; i++)
{
ForgeDirection STdir = dirs[i];
if (STdir.getOpposite() == Ndir) Conect = true;
}
} else if (te.Object.getUnlocalizedName().equals("thall"))
{
str10.setRotation(te.Object.placementRotation);
ForgeDirection[] dirs = str10.getDirs(te.Object.placementDir);
for (int i = 0; i < 2; i++)
{
ForgeDirection STdir = dirs[i];
if (STdir.getOpposite() == Ndir) Conect = true;
}
}
if (Conect)
{
int[] Ipos = ForgeDirectionUtils.IncreaseByDir(dir, IPoint.clone(), 9);
TileEntityInfo Ite = (TileEntityInfo) world.getTileEntity(Ipos[0], Ipos[1], Ipos[2]);
if (Ite != null)
{
Ite.Object.connections.add(te.Object);
}
}
}
}
if (!Conect)
{
str1.Build(world, Ndir, Spos[0], Spos[1], Spos[2]);
str2.ClearWay(world, dir, x, y, z);
} else
{
// no if's for each dir!
Spos = ForgeDirectionUtils.IncreaseByDir(Ndir.getOpposite(), Spos, 2);
str3.ClearWay(world, Ndir, Spos[0], Spos[1], Spos[2]);
str2.ClearWay(world, dir, x, y, z);
// str3.ClearWay(world, Ndir,
// Spos[0], Spos[1],
// Spos[2]);
}
} else
{
str1.Build(world, Ndir, Spos[0], Spos[1], Spos[2]);
str2.ClearWay(world, dir, x, y, z);
}
return true;
}
case "crossroad":
if (str4.Check(world, dir, x, y, z, -1))
{
int[] IPoint = MatrixHelper.findMatrixPoint(world, dir, x, y, z);
Map Matrix;
if (IPoint != null)
{
Matrix = new HashMap<Integer, int[]>();
Matrix.clear();
Matrix = MatrixHelper.findTotalMatrix(world, IPoint);
if (dir != ForgeDirection.UNKNOWN)
{
if (Matrix != null) if (!isAvailable(dir, Matrix, IPoint[0], IPoint[1], IPoint[2])) return false;
}
} else Matrix = null;
TileEntityInfo te = null;
if (IPoint != null && dir != ForgeDirection.UNKNOWN)
{
te = (TileEntityInfo) world.getTileEntity(IPoint[0], IPoint[1], IPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str4.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.ChildObjects.add(Nstr);
}
}
str4.Build(world, dir, x, y, z);
if (dir != ForgeDirection.UNKNOWN)
{
ForgeDirection[] dirs = str4.getDirs(dir);
for (int i = 0; i < 3; i++)
{
ForgeDirection Ndir = dirs[i];
int[] pos = str4.ChangePosForDir(dir, Ndir, x, y, z);
// no if's for each dir!
int[] Spos;
if (IPoint != null)
{
Spos = IPoint.clone();
Spos = ForgeDirectionUtils.IncreaseByDir(dir, Spos, 9);
Spos = ForgeDirectionUtils.IncreaseByDir(Ndir, Spos, 9);
} else
{
Spos = new int[] { 0, 0, 0 };
}
boolean Conect = false;
if (Matrix != null)
{
if (MatrixHelper.FindPointInMatrix(Matrix, Spos) != null)
{
te = (TileEntityInfo) world.getTileEntity(Spos[0], Spos[1], Spos[2]);
if (te != null)
{
if ((te.Object.getUnlocalizedName().equals("hall") || te.Object.getUnlocalizedName().equals("hallairlock"))
&& te.Object.placementDir.getOpposite() == Ndir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("corner")
&& str3.onTurn(te.Object.placementDir, te.Object.placementRotation).getOpposite() == Ndir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("crossroad") || te.Object.getUnlocalizedName().equals("bighall"))
{
ForgeDirection[] dirs1 = str4.getDirs(te.Object.placementDir);
for (int i2 = 0; i2 < 3; i2++)
{
ForgeDirection STdir = dirs1[i2];
if (STdir.getOpposite() == Ndir) Conect = true;
}
} else if (te.Object.getUnlocalizedName().equals("thall"))
{
str10.setRotation(te.Object.placementRotation);
ForgeDirection[] dirs1 = str10.getDirs(te.Object.placementDir);
for (int i2 = 0; i2 < 2; i2++)
{
ForgeDirection STdir = dirs1[i2];
if (STdir.getOpposite() == Ndir) Conect = true;
}
}
if (Conect)
{
int[] Ipos = ForgeDirectionUtils.IncreaseByDir(dir, IPoint.clone(), 9);
TileEntityInfo Ite = (TileEntityInfo) world.getTileEntity(Ipos[0], Ipos[1], Ipos[2]);
if (Ite != null)
{
Ite.Object.connections.add(te.Object);
}
}
}
}
}
if (!Conect)
{
str1.Build(world, Ndir, pos[0], pos[1], pos[2]);
} else
{
// no if's for each dir!
pos = ForgeDirectionUtils.IncreaseByDir(Ndir.getOpposite(), pos, 2);
str3.ClearWay(world, Ndir, pos[0], pos[1], pos[2]);
}
}
str2.ClearWay(world, dir, x, y, z);
}
return true;
}
case "hallairlock":
if (str5.Check(world, dir, x, y, z, -1))
{
int[] IPoint = MatrixHelper.findMatrixPoint(world, dir, x, y, z);
Map Matrix;
if (IPoint != null)
{
Matrix = new HashMap<Integer, int[]>();
Matrix.clear();
Matrix = MatrixHelper.findTotalMatrix(world, IPoint);
// if (Matrix == null) return false;
if (Matrix != null) if (!isAvailable(dir, Matrix, IPoint[0], IPoint[1], IPoint[2])) return false;
} else Matrix = null;
TileEntityInfo te = null;
if (IPoint != null)
{
te = (TileEntityInfo) world.getTileEntity(IPoint[0], IPoint[1], IPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str5.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.ChildObjects.add(Nstr);
}
}
str5.setOwner(player.getGameProfile().getName());
str5.Build(world, dir, x, y, z);
// no if's for each dir!
int[] Spos = new int[] { x, y, z };
Spos = ForgeDirectionUtils.IncreaseByDir(dir, Spos, 9);
int[] Ppos;
if (IPoint != null)
{
Ppos = IPoint.clone();
Ppos = ForgeDirectionUtils.IncreaseByDir(dir, Ppos, 18);
} else
{
Ppos = new int[] { 0, 0, 0 };
}
boolean Conect = false;
if (Matrix != null)
{
if (MatrixHelper.FindPointInMatrix(Matrix, Ppos) != null)
{
te = (TileEntityInfo) world.getTileEntity(Ppos[0], Ppos[1], Ppos[2]);
if (te != null)
{
if ((te.Object.getUnlocalizedName().equals("hall") || te.Object.getUnlocalizedName().equals("hallairlock"))
&& te.Object.placementDir.getOpposite() == dir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("corner") && str3.onTurn(te.Object.placementDir, te.Object.placementRotation).getOpposite() == dir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("crossroad") || te.Object.getUnlocalizedName().equals("bighall"))
{
ForgeDirection[] dirs = str4.getDirs(te.Object.placementDir);
for (int i = 0; i < 3; i++)
{
ForgeDirection STdir = dirs[i];
if (STdir.getOpposite() == dir)
{
Conect = true;
break;
}
}
} else if (te.Object.getUnlocalizedName().equals("thall"))
{
str10.setRotation(te.Object.placementRotation);
ForgeDirection[] dirs = str10.getDirs(te.Object.placementDir);
for (int i = 0; i < 2; i++)
{
ForgeDirection STdir = dirs[i];
if (STdir.getOpposite() == dir) Conect = true;
}
}
if (Conect)
{
int[] Ipos = ForgeDirectionUtils.IncreaseByDir(dir, IPoint.clone(), 9);
TileEntityInfo Ite = (TileEntityInfo) world.getTileEntity(Ipos[0], Ipos[1], Ipos[2]);
if (Ite != null)
{
Ite.Object.connections.add(te.Object);
}
}
}
}
}
if (!Conect)
{
str1.Build(world, dir, Spos[0], Spos[1], Spos[2], 0);
str2.ClearWay(world, dir, x, y, z);
} else
{
// no if's for each dir!
Spos = ForgeDirectionUtils.IncreaseByDir(dir.getOpposite(), Spos, 2);
str3.ClearWay(world, dir, Spos[0], Spos[1], Spos[2]);
str2.ClearWay(world, dir, x, y, z);
}
return true;
}
case "window"://TODO: make window use glass that was in players inventory
if (str6.Check(world, dir, x, y, z, -1))
{
int[] MatrixPoint = MatrixHelper.findPointForAddOBJ(world, dir, x, y, z);
if (MatrixPoint != null && MatrixPoint.length > 0)
{
TileEntityInfo te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str6.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.configureTileEntity("ADD", Nstr);
}
}
str6.setRotation(rot);
if (rot == 1) str2.ClearWay(world, dir, x, y, z);
str6.Build(world, dir, x, y, z);
return true;
}
case "cupola"://TODO: make window use glass that was in players inventory
if (str7.Check(world, dir, x, y, z, -1))
{
int[] MatrixPoint = MatrixHelper.findPointForAddOBJ(world, dir, x, y, z);
if (MatrixPoint != null && MatrixPoint.length > 0)
{
TileEntityInfo te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str7.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.configureTileEntity("ADD", Nstr);
}
}
str7.Build(world, dir, x, y, z);
str7.ClearWay(world, dir, x, y, z);
return true;
}
case "dockport":
if (str8.Check(world, dir, x, y, z, -1))
{
int[] MatrixPoint = MatrixHelper.findPointForAddOBJ(world, dir, x, y, z);
if (MatrixPoint != null && MatrixPoint.length > 0)
{
TileEntityInfo te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str8.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.configureTileEntity("ADD", Nstr);
}
}
str8.Build(world, dir, x, y, z);
str8.ClearWay(world, dir, x, y, z);
return true;
}
case "solarpanel":
if (str9.Check(world, dir, x, y, z, -1))
{
int[] MatrixPoint = MatrixHelper.findPointForAddOBJ(world, dir, x, y, z);
if (MatrixPoint != null && MatrixPoint.length > 0)
{
TileEntityInfo te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str9.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.configureTileEntity("ADD", Nstr);
}
}
str9.setRotation(rot);
str9.Build(world, dir, x, y, z);
return true;
}
case "thall":
if (str10.Check(world, dir, x, y, z, -1))
{
int[] IPoint = MatrixHelper.findMatrixPoint(world, dir, x, y, z);
Map Matrix;
if (IPoint != null)
{
Matrix = new HashMap<Integer, int[]>();
Matrix.clear();
Matrix = MatrixHelper.findTotalMatrix(world, IPoint);
// if (Matrix == null) return false;
if (Matrix != null) if (!isAvailable(dir, Matrix, IPoint[0], IPoint[1], IPoint[2])) return false;
} else Matrix = null;
TileEntityInfo te = null;
if (IPoint != null)
{
te = (TileEntityInfo) world.getTileEntity(IPoint[0], IPoint[1], IPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str10.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.ChildObjects.add(Nstr);
}
}
str10.setRotation(rot);
str10.Build(world, dir, x, y, z);
ForgeDirection[] dirs = str10.getDirs(dir);
for (int i = 0; i < 2; i++)
{
ForgeDirection Ndir = dirs[i];
int[] pos = str4.ChangePosForDir(dir, Ndir, x, y, z);
// str1.Build(world, Ndir,
// pos[0],pos[1],pos[2]);
int[] Spos;
if (IPoint != null)
{
Spos = IPoint.clone();
Spos = ForgeDirectionUtils.IncreaseByDir(dir, Spos, 9);
Spos = ForgeDirectionUtils.IncreaseByDir(Ndir, Spos, 9);
} else
{
Spos = new int[] { 0, 0, 0 };
}
boolean Conect = false;
if (Matrix != null)
{
if (MatrixHelper.FindPointInMatrix(Matrix, Spos) != null)
{
te = (TileEntityInfo) world.getTileEntity(Spos[0], Spos[1], Spos[2]);
if (te != null)
{
if ((te.Object.getUnlocalizedName().equals("hall") || te.Object.getUnlocalizedName().equals("hallairlock"))
&& te.Object.placementDir.getOpposite() == Ndir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("corner")
&& str3.onTurn(te.Object.placementDir, te.Object.placementRotation).getOpposite() == Ndir)
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("crossroad") || te.Object.getUnlocalizedName().equals("bighall"))
{
ForgeDirection[] dirs1 = str4.getDirs(te.Object.placementDir);
for (int i2 = 0; i2 < 3; i2++)
{
ForgeDirection STdir = dirs1[i2];
if (STdir.getOpposite() == Ndir) Conect = true;
}
} else if (te.Object.getUnlocalizedName().equals("thall"))
{
str10.setRotation(te.Object.placementRotation);
ForgeDirection[] dirs1 = str10.getDirs(te.Object.placementDir);
for (int j = 0; j < 2; j++)
{
ForgeDirection STdir = dirs1[j];
if (STdir.getOpposite() == Ndir) Conect = true;
}
}
if (Conect)
{
int[] Ipos = ForgeDirectionUtils.IncreaseByDir(dir, IPoint.clone(), 9);
TileEntityInfo Ite = (TileEntityInfo) world.getTileEntity(Ipos[0], Ipos[1], Ipos[2]);
if (Ite != null)
{
Ite.Object.connections.add(te.Object);
}
}
}
}
}
// System.out.println("W "+pos[0]+" "+pos[1]+" "+pos[2]+" "+Ndir+" "+i);
if (!Conect)
{
str1.Build(world, Ndir, pos[0], pos[1], pos[2]);
} else
{
pos = ForgeDirectionUtils.IncreaseByDir(Ndir.getOpposite(), pos, 2);
str3.ClearWay(world, Ndir, pos[0], pos[1], pos[2]);
}
}
str2.ClearWay(world, dir, x, y, z);
return true;
}
case "bighall"://TODO: Corners in this strucure is not sealable
if (str11.Check(world, dir, x, y, z, -1))
{
int[] IPoint = MatrixHelper.findMatrixPoint(world, dir, x, y, z);
Map Matrix;
if (IPoint != null)
{
Matrix = new HashMap<Integer, int[]>();
Matrix.clear();
Matrix = MatrixHelper.findTotalMatrix(world, IPoint);
if (Matrix != null)
{
if (!isAvailable(dir, Matrix, IPoint[0], IPoint[1], IPoint[2])) return false;
int[] FTPos = ForgeDirectionUtils.IncreaseByDir(dir, IPoint.clone(), 9);
if (!isAvailable(dir, Matrix, FTPos[0], FTPos[1], FTPos[2])) return false;
ForgeDirection Tdir;
if (rot == 0)
{
Tdir = ForgeDirectionUtils.turnAgainstClockwise(dir);
} else
{
Tdir = ForgeDirectionUtils.turnClockwise(dir);
}
int[] Tpos = ForgeDirectionUtils.IncreaseByDir(Tdir, IPoint.clone(), 9);
if (!isAvailable(dir, Matrix, Tpos[0], Tpos[1], Tpos[2])) return false;
ForgeDirectionUtils.IncreaseByDir(dir, Tpos, 9);
if (!isAvailable(dir, Matrix, FTPos[0], FTPos[1], FTPos[2])) return false;
}
} else Matrix = null;
TileEntityInfo te = null;
if (IPoint != null)
{
te = (TileEntityInfo) world.getTileEntity(IPoint[0], IPoint[1], IPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str11.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.ChildObjects.add(Nstr);
}
}
str11.setRotation(rot);
str11.Build(world, dir, x, y, z);
ForgeDirection[] dirs = str11.getDirs(dir);
List<int[]> posT = str11.getPos(dir, dirs, x, y, z);
Iterator<int[]> posI = posT.iterator();
int i = 0;
while (posI.hasNext())
{
int[] pos = posI.next();
boolean Conect = false;
if (Matrix != null)
{
int Px;
int Pz;
if (dirs[i] == ForgeDirection.NORTH)
{
Pz = pos[2] - 4;
Px = pos[0];
} else if (dirs[i] == ForgeDirection.SOUTH)
{
Pz = pos[2] + 4;
Px = pos[0];
} else if (dirs[i] == ForgeDirection.WEST)
{
Pz = pos[2];
Px = pos[0] - 4;
} else if (dirs[i] == ForgeDirection.EAST)
{
Pz = pos[2];
Px = pos[0] + 4;
} else
{
Px = pos[0];
Pz = pos[2];
}
if (MatrixHelper.FindPointInMatrix(Matrix, new int[] { Px, pos[1] - 3, Pz }) != null)
{
te = (TileEntityInfo) world.getTileEntity(Px, pos[1] - 3, Pz);
if (te != null)
{
if ((te.Object.getUnlocalizedName().equals("hall") || te.Object.getUnlocalizedName().equals("hallairlock"))
&& te.Object.placementDir.getOpposite() == dirs[i])
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("corner")
&& str3.onTurn(te.Object.placementDir, te.Object.placementRotation).getOpposite() == dirs[i])
{
Conect = true;
} else if (te.Object.getUnlocalizedName().equals("crossroad") || te.Object.getUnlocalizedName().equals("bighall"))
{
ForgeDirection[] Cdirs = str4.getDirs(te.Object.placementDir);
for (int i2 = 0; i2 < Cdirs.length; i2++)
{
ForgeDirection STdir = Cdirs[i2];
if (STdir.getOpposite() == dirs[i])
{
Conect = true;
break;
}
}
} else if (te.Object.getUnlocalizedName().equals("thall"))
{
str10.setRotation(te.Object.placementRotation);
ForgeDirection[] dirs1 = str10.getDirs(te.Object.placementDir);
for (int j = 0; j < dirs1.length; j++)
{
ForgeDirection STdir = dirs1[j];
if (STdir.getOpposite() == dirs[i]) Conect = true;
}
}
if (Conect)
{
int[] Ipos = ForgeDirectionUtils.IncreaseByDir(dir, IPoint.clone(), 9);
TileEntityInfo Ite = (TileEntityInfo) world.getTileEntity(Ipos[0], Ipos[1], Ipos[2]);
if (Ite != null)
{
Ite.Object.connections.add(te.Object);
}
}
}
}
}
if (!Conect)
{
str1.Build(world, dirs[i], pos[0], pos[1], pos[2]);
i++;
} else
{
int Sx = pos[0];
int Sz = pos[2];
if (dirs[i] == ForgeDirection.WEST)
{
Sx = pos[0] + 2;
} else if (dirs[i] == ForgeDirection.EAST)
{
Sx = pos[0] - 2;
} else if (dirs[i] == ForgeDirection.SOUTH)
{
Sz = pos[2] - 2;
} else if (dirs[i] == ForgeDirection.NORTH)
{
Sz = pos[2] + 2;
}
str2.ClearWay(world, dirs[i], pos[0], y, pos[2]);
str3.ClearWay(world, dirs[i], Sx, y, Sz);
i++;
}
}
str2.ClearWay(world, dir, x, y, z);
return true;
}
case "greenhouse":
if (str12.Check(world, dir, x, y, z, -1))
{
int[] MatrixPoint = MatrixHelper.findPointForAddOBJ(world, dir, x, y, z);
if (MatrixPoint != null && MatrixPoint.length > 0)
{
TileEntityInfo te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
if (te != null)
{
Map Matrix = new HashMap<Integer, int[]>();
Matrix.clear();
Matrix = MatrixHelper.findTotalMatrix(world, MatrixPoint);
Structure curr = te.Object;
boolean[] wrong = new boolean[] { false, false };
if (Matrix != null)
{
int[] Nmatr = MatrixHelper.FindPointInMatrix(Matrix, new int[] { MatrixPoint[0] - 9, MatrixPoint[1], MatrixPoint[2] });
if (Nmatr != null && Nmatr.length > 0)
{
TileEntityInfo te2 = (TileEntityInfo) world.getTileEntity(Nmatr[0], Nmatr[1], Nmatr[2]);
if (te2 != null)
{
if (te2.AddObjects != null && te2.AddObjects.size() > 0)
{
for (int j = 0; j < te2.AddObjects.size(); j++)
{
if (te2.AddObjects.get(j).getUnlocalizedName() == Structure.SOLARPANELID
|| te2.AddObjects.get(j).getUnlocalizedName() == Structure.GREENHOUSE)
{
return false;
}
}
}
if (!(te2.Object.placementPos[0] == curr.placementPos[0] && te2.Object.placementPos[1] == curr.placementPos[1]
&& te2.Object.placementPos[2] == curr.placementPos[2]))
{
wrong[0] = true;
}
}
} else
{
wrong[0] = true;
}
Nmatr = MatrixHelper.FindPointInMatrix(Matrix, new int[] { MatrixPoint[0], MatrixPoint[1], MatrixPoint[2] - 9 });
if (Nmatr != null && Nmatr.length > 0)
{
TileEntityInfo te2 = (TileEntityInfo) world.getTileEntity(Nmatr[0], Nmatr[1], Nmatr[2]);
if (te2 != null)
{
if (te2.AddObjects != null && te2.AddObjects.size() > 0)
{
for (int j = 0; j < te2.AddObjects.size(); j++)
{
if (te2.AddObjects.get(j).getUnlocalizedName() == Structure.SOLARPANELID
|| te2.AddObjects.get(j).getUnlocalizedName() == Structure.GREENHOUSE)
{
return false;
}
}
}
if (!(te2.Object.placementPos[0] == curr.placementPos[0] && te2.Object.placementPos[1] == curr.placementPos[1]
&& te2.Object.placementPos[2] == curr.placementPos[2]))
{
wrong[1] = true;
}
}
} else
{
wrong[1] = true;
}
if (wrong[0] && wrong[1])
{
x = x + 9;
z = z + 9;
MatrixPoint[0] = MatrixPoint[0] + 9;
MatrixPoint[2] = MatrixPoint[2] + 9;
te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
} else if (wrong[0])
{
x = x + 9;
MatrixPoint[0] = MatrixPoint[0] + 9;
te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
} else if (wrong[1])
{
z = z + 9;
MatrixPoint[2] = MatrixPoint[2] + 9;
te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
}
Nmatr = MatrixHelper.FindPointInMatrix(Matrix, new int[] { MatrixPoint[0] - 9, MatrixPoint[1], MatrixPoint[2] - 9 });
if (Nmatr != null && Nmatr.length > 0)
{
TileEntityInfo te2 = (TileEntityInfo) world.getTileEntity(Nmatr[0], Nmatr[1], Nmatr[2]);
if (te2 != null)
{
if (te2.AddObjects != null && te2.AddObjects.size() > 0)
{
for (int j = 0; j < te2.AddObjects.size(); j++)
{
if (te2.AddObjects.get(j).getUnlocalizedName() == Structure.SOLARPANELID
|| te2.AddObjects.get(j).getUnlocalizedName() == Structure.GREENHOUSE)
{
return false;
}
}
}
}
}
}
}
if (te != null)
{
Structure Nstr = Structure.FindStructure(str12.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.configureTileEntity("ADD", Nstr);
}
}
str12.Build(world, dir, x, y, z);
return true;
}
case "pierce":
if (str13.Check(world, dir, x, y, z, -1))
{
int[] MatrixPoint = MatrixHelper.findPointForAddOBJ(world, dir, x, y, z);
if (MatrixPoint != null && MatrixPoint.length > 0)
{
TileEntityInfo te = (TileEntityInfo) world.getTileEntity(MatrixPoint[0], MatrixPoint[1], MatrixPoint[2]);
if (te != null)
{
Structure Nstr = Structure.FindStructure(str13.getUnlocalizedName());
Nstr.Configure(new int[] { x, y, z }, rot, dir);
te.configureTileEntity("ADD", Nstr);
}
}
if (rot == 1) str2.ClearWay(world, dir, x, y, z);
str13.Build(world, dir, x, y, z);
str2.ClearWay(world, dir, x, y, z);
return true;
}
}
return false;
}
public static void buildInfoPoint(World world, ForgeDirection dir, String FuncName, int x, int y, int z, int rot, int PLx, int PLy, int PLz)
{
Block info = BlockContainerMod.BlockInfo;
TileEntityInfo te;
switch (FuncName) {
case "hall":
world.setBlock(x, y, z, info, 0, 2);
te = (TileEntityInfo) world.getTileEntity(x, y, z);
te.configureTileEntity(dir, rot, str2.copy(), new int[] { PLx, PLy, PLz });
break;
case "corner":
world.setBlock(x, y, z, info, 0, 2);
te = (TileEntityInfo) world.getTileEntity(x, y, z);
te.configureTileEntity(dir, rot, str3.copy(), new int[] { PLx, PLy, PLz });
break;
case "crossroad":
world.setBlock(x, y, z, info, 0, 2);
te = (TileEntityInfo) world.getTileEntity(x, y, z);
te.configureTileEntity(dir, rot, str4.copy(), new int[] { PLx, PLy, PLz });
break;
case "hallairlock":
world.setBlock(x, y, z, info, 0, 2);
te = (TileEntityInfo) world.getTileEntity(x, y, z);
te.configureTileEntity(dir, rot, str5.copy(), new int[] { PLx, PLy, PLz });
break;
case "thall":
world.setBlock(x, y, z, info, 0, 2);
te = (TileEntityInfo) world.getTileEntity(x, y, z);
te.configureTileEntity(dir, rot, str10.copy(), new int[] { PLx, PLy, PLz });
break;
case "bighall":
world.setBlock(x, y, z, info, 0, 2);
te = (TileEntityInfo) world.getTileEntity(x, y, z);
te.configureTileEntity(dir, rot, str11.copy(), new int[] { PLx, PLy, PLz });
break;
}
}
public static void buildRemoveInfoPoint(World world, ForgeDirection dir, String FuncName, int x, int y, int z, int rot, int Ix, int Iy, int Iz)
{
Block info = BlockContainerMod.BlockRemoveInfo;
TileEntityRemoveInfo te;
switch (FuncName) {
case "hall":
world.setBlock(x, y, z, info, str2.getMetaFromDir(dir), 2);
te = (TileEntityRemoveInfo) world.getTileEntity(x, y, z);
te.configureTileEntity((TileEntityInfo) world.getTileEntity(Ix, Iy, Iz));
break;
case "corner":
world.setBlock(x, y, z, info, str3.getMetaFromDirARot(dir, rot), 2);
te = (TileEntityRemoveInfo) world.getTileEntity(x, y, z);
te.configureTileEntity((TileEntityInfo) world.getTileEntity(Ix, Iy, Iz));
break;
case "crossroad":
world.setBlock(x, y, z, info, str2.getMetaFromDir(dir), 2);
te = (TileEntityRemoveInfo) world.getTileEntity(x, y, z);
te.configureTileEntity((TileEntityInfo) world.getTileEntity(Ix, Iy, Iz));
break;
case "hallairlock":
world.setBlock(x, y, z, info, str2.getMetaFromDir(dir), 2);
te = (TileEntityRemoveInfo) world.getTileEntity(x, y, z);
te.configureTileEntity((TileEntityInfo) world.getTileEntity(Ix, Iy, Iz));
break;
case "thall":
world.setBlock(x, y, z, info, str10.getMetaFromDirARot(dir, rot), 2);
te = (TileEntityRemoveInfo) world.getTileEntity(x, y, z);
te.configureTileEntity((TileEntityInfo) world.getTileEntity(Ix, Iy, Iz));
break;
}
}
public static void buildBuildPoint(World world, int x, int y, int z, int type)
{
Block info = BlockMod.BuildpPoint;
world.setBlock(x, y, z, info, type, 2);
}
public static boolean isAvailable(ForgeDirection dir, Map<Integer, int[]> M, int x, int y, int z)
{
int Px;
int Pz;
if (dir == ForgeDirection.WEST)
{
Px = x - 9;
Pz = z;
} else if (dir == ForgeDirection.EAST)
{
Px = x + 9;
Pz = z;
} else if (dir == ForgeDirection.SOUTH)
{
Px = x;
Pz = z + 9;
} else if (dir == ForgeDirection.NORTH)
{
Px = x;
Pz = z - 9;
} else
{
Px = x;
Pz = z;
}
if (MatrixHelper.FindPointInMatrix(M, new int[] { Px, y, Pz }) == null)
{
return true;
}
return false;
}
public static String getLocolizedName(String uln, int rot, boolean isShort)
{
switch (uln) {
case "stub":
return str1.getName();
case "hall":
return str2.getName();
case "corner":
return str3.getName();
case "crossroad":
return str4.getName();
case "hallairlock":
return str5.getName();
case "window":
return str6.getName();
case "cupola":
return str7.getName();
case "dockport":
return str8.getName();
case "solarpanel":
return str9.getName();
case "thall":
return str10.getName();
case "bighall":
return str11.getName();
default:
return "";
}
}
}
| |
/**
* Copyright 2017 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.comcast.dawg.helper;
import java.util.ArrayList;
import com.comcast.cereal.CerealException;
import com.comcast.cereal.engines.JsonCerealEngine;
import com.comcast.dawg.DawgRestRequestService;
import com.comcast.dawg.DawgTestException;
import com.comcast.dawg.MetaStbBuilder;
import com.comcast.dawg.config.RestURIConfig;
import com.comcast.dawg.config.TestServerConfig;
import com.comcast.dawg.constants.DawgHouseConstants;
import com.comcast.dawg.constants.TestConstants;
import com.comcast.dawg.utils.DawgCommonUIUtils;
import com.comcast.video.dawg.common.MetaStb;
import com.comcast.zucchini.TestContext;
import com.jayway.restassured.internal.http.Method;
import com.jayway.restassured.response.Response;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper functionalities for accessing Dawg House REST services
* @author Jeeson
*
*/
public class DawgHouseRestHelper {
/**
* Logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(DawgHouseRestHelper.class);
/** lock object */
private static Object lock = new Object();
private static DawgHouseRestHelper dhrestHelper;
/**
* Creates single instance of restHelper
* @return restHelper
*/
public static DawgHouseRestHelper getInstance() {
synchronized (lock) {
if (null == dhrestHelper) {
dhrestHelper = new DawgHouseRestHelper();
}
}
return dhrestHelper;
}
/**
* Add an STB model to dawg house via POST request
* @param modelName
* STB model name
* @param capabilities
* STB model capabilities
* @param family
* STB model family
* @return boolean returns True if response is not null, have status code 200 and contains true
* @throws DawgTestException
*/
public boolean addSTBModelToDawg(String modelName, String capabilities, String family) throws DawgTestException {
ArrayList<String> testStbModels = TestContext.getCurrent().get(DawgHouseConstants.CONTEXT_TEST_STB_MODELS);
String url = RestURIConfig.ADD_UPDATE_MODEL_URI.buildURL(TestServerConfig.getHouse()) + modelName;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.POST);
String reqBody = new String("{\"name\":\"" + modelName + "\",\"capabilities\":" + capabilities + ",\"family\":\"" + family + "\"}");
// Setting content type and request body for POST
Response response = dawgRestReqService.setContentType(DawgHouseConstants.CONTENT_TYPE).setRequestBody(
reqBody).sendRequest();
if (null == testStbModels) {
testStbModels = new ArrayList<String>();
}
if ((null != response) && (HttpStatus.SC_OK == response.getStatusCode()) && ("true".equals(
response.asString()))) {
// Storing added STB models to test context
testStbModels.add(modelName);
TestContext.getCurrent().set(DawgHouseConstants.CONTEXT_TEST_STB_MODELS, testStbModels);
return true;
}
return false;
}
/**
* Send GET request to get an STB model from dawg house
* @param modelId
* STB model id
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean sendGetReqForSTBModel(String modelId) throws DawgTestException {
String url = RestURIConfig.GET_STB_MODEL_URI.buildURL(TestServerConfig.getHouse()) + modelId;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.GET);
// Sending GET request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Get an STB device from dawg house via GET request passing model name as query
* @param stbModelName
* STB model name
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean sendGetReqByQueryForSTBDevice(String stbModelName) throws DawgTestException {
String url = RestURIConfig.GET_STB_BY_QUERY.buildURL(TestServerConfig.getHouse()) + stbModelName;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.GET);
// Sending GET request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Remove an STB model from dawg house
* @param modelId
* STB model id
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean removeSTBModelFromDawg(String modelId) throws DawgTestException {
String url = RestURIConfig.ADD_UPDATE_MODEL_URI.buildURL(TestServerConfig.getHouse()) + modelId;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.DELETE);
// Sending DELETE request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Check if given STB model is present in dawg house
* @param modelId
* STB model id
* @return boolean returns True if response is not null, have status code 200 and contains given model id
* @throws DawgTestException
*/
public boolean stbModelExistsInDawg(String modelId) throws DawgTestException {
String url = RestURIConfig.GET_STB_MODEL_URI.buildURL(TestServerConfig.getHouse()) + modelId;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.GET);
// Sending GET request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode()) && response.asString().contains(
modelId);
}
/**
* Populate STB reservation token via POST request
* @param clientToken
* client token
* @return boolean returns True if response is not null, have status code 200
* @throws DawgTestException
*/
public boolean populateStbInDawg(String clientToken) throws DawgTestException {
String url = RestURIConfig.POPULATE_STB_URI.buildURL(TestServerConfig.getHouse()) + clientToken;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.POST);
// Sending POST request
Response response = dawgRestReqService.sendRequest();
return (null != response);
}
/**
* Check if given STB device is present in dawg house
* @param deviceId
* STB device id
* @return boolean returns True if response is not null, have status code 200 and contains given model id
* @throws DawgTestException
*/
public boolean stbDeviceExistsInDawg(String deviceId) throws DawgTestException {
String url = RestURIConfig.ADD_REMOVE_STB_REST_URI.buildURL(TestServerConfig.getHouse()) + deviceId;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.GET);
// Sending GET request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode()) && response.asString().contains(
deviceId);
}
/**
* Send POST request to retrieve STB from dawg house, passing device id in request body
* @param deviceId
* STB device id
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean sendPostReqToRetrieveSTB(String deviceId) throws DawgTestException {
String url = RestURIConfig.ADD_REMOVE_STB_REST_URI.buildURL(TestServerConfig.getHouse());
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.POST);
// Sending POST request
Response response = dawgRestReqService.setContentType(
TestConstants.URL_ENCODED_CONTENT_TYPE_HEADER_VALUE).setRequestBody("id=" + deviceId).sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Creates MetaStb object for testing purpose.
* @param deviceId
* STB device id
* @param modelName
* STB model name
* @param caps
* STB model capabilities
* @param family
* STB model family name
* @param mac
* STB MAC address
* @return MetaStb
* test STB object.
*/
public MetaStb createTestStb(String deviceId, String modelName, String caps, String family, String mac) {
return MetaStbBuilder.build().id(deviceId).model(modelName).caps(caps).family(family).mac(mac).stb();
}
/**
* Add an STB Device to dawg house via PUT request
* @param id
* STB device id
* @param mac
* STB MAC address
* @param model
* STB model name
* @param capability
* STB model capabilities
* @param family
* STB model family name
* @param make
* STB make
* @param reqType
* RestReqType
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean addStbToDawg(String id, String mac, String model, String capability, String family, String make, TestConstants.RestReqType reqType) throws DawgTestException {
ArrayList<String> testStbs = TestContext.getCurrent().get(DawgHouseConstants.CONTEXT_TEST_STBS);
String url = RestURIConfig.ADD_REMOVE_STB_REST_URI.buildURL(TestServerConfig.getHouse()) + id;
String reqBody = createRestReqBodyStr(id, mac, model, capability, family, make, reqType);
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.PUT);
// Sending PUT request
Response response = dawgRestReqService.setContentType(DawgHouseConstants.CONTENT_TYPE).setRequestBody(
reqBody).sendRequest();
if (null == testStbs) {
testStbs = new ArrayList<String>();
}
if ((null != response) && (HttpStatus.SC_OK == response.getStatusCode()) ) {
// Storing added STBs to test context
testStbs.add(id);
TestContext.getCurrent().set(DawgHouseConstants.CONTEXT_TEST_STBS, testStbs);
return true;
}
return false;
}
/**
* Creates the string equivalent of request body for 'add an STB' rest requests
* @param id
* STB device id
* @param mac
* STB MAC address
* @param model
* STB model name
* @param capability
* STB model capabilities
* @param family
* STB model family name
* @param make
* STB model make
* @param reqType
* Type of request body
* @return String
* String equivalent of REST request body with STB parameters
*/
public String createRestReqBodyStr(String id, String mac, String model, String capability, String family, String make, TestConstants.RestReqType reqType) {
String reqBody = null;
switch (reqType) {
case DETAILED_STB_DEVICE_PARAM:
reqBody = new String("{\"id\":\"" + id + "\",\"macAddress\":\"" + mac + "\",\"model\":\"" + model + "\",\"capabilities\":" + capability + ",\"family\":\"" + family + "\"}");
break;
case BRIEF_STB_DEVICE_PARAM:
reqBody = new String("{\"id\":\"" + id + "\", \"macAddress\":\"" + mac + "\", \"model\":\"" + model + "\", \"make\":\"" + make + "\"}");
break;
default:
LOGGER.error("Invalid Request type received {}", reqType);
}
return reqBody;
}
/**
* Remove STB from dawg house via GET request, passing device id as query param
* @param deviceId
* STB device id
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean removeSTBFromDawgByQuery(String deviceId) throws DawgTestException {
String url = RestURIConfig.REMOVE_STB_BY_QUERY_URI.buildURL(TestServerConfig.getHouse()) + deviceId;
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.GET);
// Sending GET request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Remove the added test STBs from dawg house via DELETE request
* @param deviceId
* STB device Id
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean removeStbFromDawg(String deviceId) throws DawgTestException {
String url = RestURIConfig.ADD_REMOVE_STB_REST_URI.buildURL(TestServerConfig.getHouse()) + deviceId;
DawgRestRequestService dawgReqRunner = new DawgRestRequestService(url, Method.DELETE);
LOGGER.info("Going to remove the test STB{}", deviceId);
// Sending DELETE request
Response response = dawgReqRunner.setContentType(DawgHouseConstants.CONTENT_TYPE).sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Get list of STB devices available in dawg (house/pound) via GET request
* @param dawgServer
* Whether list belong to dawg (house/pound) server
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean sendGetReqForSTBDeviceList(String dawgServer) throws DawgTestException {
RestURIConfig restUriConfig = null;
if (dawgServer.contains(TestConstants.DAWG_HOUSE)) {
// Configuring URI to get STB device list from dawg house
restUriConfig = RestURIConfig.GET_STB_DEVICE_LIST_URI;
} else if (dawgServer.contains(TestConstants.DAWG_POUND)) {
// Configuring URI to get STB reservation list from dawg pound
restUriConfig = RestURIConfig.GET_STB_RESERVATION_LIST_URI;
}
String url = restUriConfig.buildURL(dawgServer);
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.GET);
// Sending GET request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Method to perform assignmodels in dawg house
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean assignModelDawg() throws DawgTestException {
String url = RestURIConfig.ASSIGN_MODELS_URI.buildURL(TestServerConfig.getHouse());
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.GET);
// Sending GET request
Response response = dawgRestReqService.sendRequest();
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Update an already existing STB parameters in dawg house via POST request
* @param testStb
* MetaStb
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean updateStbInDawg(MetaStb testStb) throws DawgTestException {
String url = RestURIConfig.UPDATE_STB_DEVICE_URI.buildURL(TestServerConfig.getHouse()) + testStb.getId();
DawgRestRequestService dawgRestReqService = new DawgRestRequestService(url, Method.POST);
JsonCerealEngine cerealEngine = new JsonCerealEngine();
// Sending POST request
Response response;
try {
response = dawgRestReqService.setContentType(TestConstants.JSON_CONTENT_TYPE_HEADER_VALUE).setRequestBody(
cerealEngine.writeToString(testStb.getData())).sendRequest();
} catch (CerealException e) {
throw new DawgTestException("Failed to convert STB data to string");
}
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Add/Update the tag associated with the STB using POST request.
* @param tagName
* Tag name to be added/updated.
* @param stbId
* STB device id
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean sendPostReqToAddStbTags(String tagName, String stbId) throws DawgTestException{
Response response = DawgCommonUIUtils.getInstance().addTagViaRestRequest(tagName, stbId);
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
/**
* Remove the tag associated with the STB using POST request.
* @param tagName
* Tag name to be removed.
* @param stbId
* STB device id
* @return boolean returns True if response is not null and have status code 200
* @throws DawgTestException
*/
public boolean sendPostReqToRemoveStbTags(String tagName, String stbId) throws DawgTestException{
Response response = DawgCommonUIUtils.getInstance().removeTagViaRestReq(tagName, stbId);
return (null != response) && (HttpStatus.SC_OK == response.getStatusCode());
}
}
| |
/*******************************************************************************
* Copyright (c) 2015
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package jsettlers.graphics.map.minimap;
import java.util.Arrays;
import jsettlers.common.Color;
import jsettlers.common.CommonConstants;
import jsettlers.common.buildings.IBuilding;
import jsettlers.common.map.IGraphicsGrid;
import jsettlers.common.mapobject.EMapObjectType;
import jsettlers.common.mapobject.IMapObject;
import jsettlers.common.movable.IMovable;
import jsettlers.graphics.map.MapDrawContext;
import jsettlers.graphics.map.minimap.MinimapMode.OccupiedAreaMode;
import jsettlers.graphics.map.minimap.MinimapMode.SettlersMode;
class LineLoader implements Runnable {
protected static final short BLACK = 0x0001;
private static final short TRANSPARENT = 0;
private static final int Y_STEP_HEIGHT = 5;
private static final int X_STEP_WIDTH = 5;
private static final int LINES_PER_RUN = 30;
/**
* The minimap we work for.
*/
private final Minimap minimap;
private int currentline = 0;
private boolean stopped;
private final MinimapMode modeSettings;
/**
* The minimap image, including settlers.
*/
private short[][] buffer = new short[1][1];
/**
* The explored landscape.
*/
private short[][] landscape = new short[1][1];
private int currYOffset = 0;
private int currXOffset = 0;
public LineLoader(Minimap minimap, MinimapMode modeSettings) {
this.minimap = minimap;
this.modeSettings = modeSettings;
}
@Override
public void run() {
while (!stopped) {
try {
updateLine();
} catch (Throwable e) {
e.printStackTrace();
}
}
};
/**
* Updates a line by putting it to the update buffer. Next time the gl context is available, it is updated.
*/
private void updateLine() {
minimap.blockUntilUpdateAllowedOrStopped();
for (int i = 0; i < LINES_PER_RUN; i++) {
if (buffer.length != minimap.getHeight() || buffer[currentline].length != minimap.getWidth()) {
buffer = new short[minimap.getHeight()][minimap.getWidth()];
landscape = new short[minimap.getHeight()][minimap.getWidth()];
for (int y = 0; y < minimap.getHeight(); y++) {
Arrays.fill(buffer[y], BLACK);
Arrays.fill(landscape[y], TRANSPARENT);
}
minimap.setBufferArray(buffer);
currentline = 0;
currXOffset = 0;
currYOffset = 0;
}
calculateLineData(currentline);
minimap.setUpdatedLine(currentline);
currentline += Y_STEP_HEIGHT;
if (currentline >= minimap.getHeight()) {
currYOffset++;
if (currYOffset > Y_STEP_HEIGHT) {
currYOffset = 0;
currXOffset += 3;
currXOffset %= X_STEP_WIDTH;
}
currentline = currYOffset;
}
}
}
private void calculateLineData(final int currentline) {
// may change!
final int safeWidth = this.minimap.getWidth();
final int safeHeight = this.minimap.getHeight();
final MapDrawContext context = this.minimap.getContext();
final IGraphicsGrid map = context.getMap();
// for height shades
final short mapWidth = map.getWidth();
final short mapHeight = map.getHeight();
int mapLineHeight = mapHeight / safeHeight + 1;
// first map tile in line
int mapMaxY = (int) ((1 - (float) currentline / safeHeight) * mapHeight);
// first map line not in line
int mapMinY = (int) ((1 - (float) (currentline + 1) / safeHeight) * mapHeight);
if (mapMinY == mapMaxY) {
if (mapMaxY == mapHeight) {
mapMinY = mapHeight - 1;
} else {
mapMaxY = mapMinY - 1;
}
}
int myXOffset = (currXOffset + currentline * 3) % X_STEP_WIDTH;
for (int x = myXOffset; x < safeWidth; x += X_STEP_WIDTH) {
int mapMinX = (int) ((float) x / safeWidth * mapWidth);
int mapMaxX = (int) ((float) (x + 1) / safeWidth * mapWidth);
if (mapMinX != 0 && mapMaxX == mapMinX) {
mapMinX = mapMaxX - 1;
}
int centerX = (mapMaxX + mapMinX) / 2;
int centerY = (mapMaxY + mapMinY) / 2;
short color = TRANSPARENT;
byte visibleStatus = map.getVisibleStatus(centerX, centerY);
if (visibleStatus > CommonConstants.FOG_OF_WAR_EXPLORED) {
color = getSettlerForArea(map, context, mapMinX, mapMinY, mapMaxX, mapMaxY);
}
if (visibleStatus > CommonConstants.FOG_OF_WAR_EXPLORED || landscape[currentline][x] == TRANSPARENT) {
float basecolor = ((float) visibleStatus) / CommonConstants.FOG_OF_WAR_VISIBLE;
int dheight = map.getHeightAt(centerX, mapMinY) - map.getHeightAt(centerX, Math.min(mapMinY + mapLineHeight, mapHeight - 1));
basecolor *= (1 + .15f * dheight);
short landscapeColor;
if (basecolor >= 0) {
landscapeColor = getColorForArea(map, mapMinX, mapMinY, mapMaxX, mapMaxY).toShortColor(basecolor);
} else {
landscapeColor = BLACK;
}
if (color == TRANSPARENT) {
color = landscapeColor;
}
landscape[currentline][x] = landscapeColor;
}
if (color != TRANSPARENT) {
buffer[currentline][x] = color;
} else {
buffer[currentline][x] = landscape[currentline][x];
}
}
}
private Color getColorForArea(IGraphicsGrid map, int mapminX, int mapminY, int mapmaxX, int mapmaxY) {
int centerx = (mapmaxX + mapminX) / 2;
int centery = (mapmaxY + mapminY) / 2;
return map.getLandscapeTypeAt(centerx, centery).color;
}
private short getSettlerForArea(IGraphicsGrid map, MapDrawContext context, int mapminX, int mapminY, int mapmaxX, int mapmaxY) {
SettlersMode displaySettlers = this.modeSettings.getDisplaySettlers();
OccupiedAreaMode displayOccupied = this.modeSettings.getDisplayOccupied();
boolean displayBuildings = this.modeSettings.getDisplayBuildings();
short occupiedColor = TRANSPARENT;
short settlerColor = TRANSPARENT;
short buildingColor = TRANSPARENT;
for (int y = mapminY; y < mapmaxY && (displayOccupied != OccupiedAreaMode.NONE || displayBuildings || displaySettlers != SettlersMode.NONE); y++) {
for (int x = mapminX; x < mapmaxX
&& (displayOccupied != OccupiedAreaMode.NONE || displayBuildings || displaySettlers != SettlersMode.NONE); x++) {
boolean visible = map.getVisibleStatus(x, y) > CommonConstants.FOG_OF_WAR_EXPLORED;
if (visible && displaySettlers != SettlersMode.NONE) {
IMovable settler = map.getMovableAt(x, y);
if (settler != null && (displaySettlers == SettlersMode.ALL || settler.getMovableType().isMoveToAble())) {
settlerColor = context.getPlayerColor(settler.getPlayerId()).toShortColor(1);
// don't search any more.
displaySettlers = SettlersMode.NONE;
} else if (displaySettlers != SettlersMode.NONE) {
IMapObject object = map.getMapObjectsAt(x, y);
IBuilding building = (object != null) ? (IBuilding) object.getMapObject(EMapObjectType.BUILDING) : null;
if (building instanceof IBuilding.IOccupyed) {
IBuilding.IOccupyed occupyed = (IBuilding.IOccupyed) building;
if (occupyed.isOccupied()) {
settlerColor = context.getPlayerColor(occupyed.getPlayerId()).toShortColor(1);
}
}
}
}
if (visible && displayOccupied == OccupiedAreaMode.BORDERS) {
if (map.isBorder(x, y)) {
byte player = map.getPlayerIdAt(x, y);
Color playerColor = context.getPlayerColor(player);
occupiedColor = playerColor.toShortColor(1);
displayOccupied = OccupiedAreaMode.NONE;
}
} else if (visible && displayOccupied == OccupiedAreaMode.AREA) {
byte player = map.getPlayerIdAt(x, y);
if (player >= 0 && !map.getLandscapeTypeAt(x, y).isBlocking) {
Color playerColor = context.getPlayerColor(player);
// Now add a landscape below that....
Color landscape = getColorForArea(map, mapminX, mapminY, mapmaxX, mapmaxY);
playerColor = landscape.toGreyScale().multiply(playerColor);
occupiedColor = playerColor.toShortColor(1);
displayOccupied = OccupiedAreaMode.NONE;
}
}
if (displayBuildings) {
if (map.isBuilding(x, y)) {
buildingColor = BLACK;
}
}
}
}
return settlerColor != TRANSPARENT ? settlerColor : buildingColor != TRANSPARENT ? buildingColor : occupiedColor;
}
/**
* Stops the execution of this line loader.
*/
public void stop() {
stopped = true;
}
}
| |
package rest;
import entity.Flight;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import swarm.SwarmDeployment;
import javax.ws.rs.*;
import java.net.URL;
import java.util.List;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@SuppressWarnings("Duplicates")
@RunWith(Arquillian.class)
@RunAsClient
public class FlightResourceTest {
@Path("flights")
private interface FlightResourceClient {
@GET
@Produces("application/json")
List<Flight> getFlights();
@GET
@Produces("application/json")
@Path("{id}")
Flight getFlight(@PathParam("id") long id);
@DELETE
@Path("{id}")
void deleteFlight(@PathParam("id") long id);
@POST
@Consumes("application/json")
@Produces("application/json")
Flight createFlight(Flight flight);
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{id}")
Flight updateFlight(@PathParam("id") long id, Flight flight);
}
private static final String RESOURCE_PREFIX = ApplicationConfig.class.getAnnotation(ApplicationPath.class).value().substring(1);
@Deployment(testable = false)
public static JAXRSArchive createDeployment() {
return SwarmDeployment.createDeployment();
}
@ArquillianResource
private URL deploymentUrl;
private ResteasyClient resteasyClient;
private FlightResourceClient client;
@Before
public void createRestClient() {
resteasyClient = new ResteasyClientBuilder().build();
ResteasyWebTarget target = resteasyClient.target(deploymentUrl.toString() + RESOURCE_PREFIX);
client = target.proxy(FlightResourceClient.class);
}
@After
public void closeRestClient() {
if (resteasyClient != null)
resteasyClient.close();
}
@Test
public void flightsCanBeAdded() throws Exception {
// given
Flight flight = new Flight("OS202", "GRZ", "DUS");
// when
Flight newFlight = client.createFlight(flight);
// then
assertThat(newFlight.getId(), is(not(0L)));
assertThat(newFlight.getFlightNumber(), is("OS202"));
assertThat(newFlight.getFromAirport(), is("GRZ"));
assertThat(newFlight.getToAirport(), is("DUS"));
}
@Test
public void flightsCanBeUpdated() throws Exception {
// given
Flight oldFlight = client.createFlight(new Flight("ABC1", "FROM1", "TO1"));
// when
Flight newFlight = client.updateFlight(oldFlight.getId(), new Flight("ABC2", "FROM2", "TO2"));
// then
assertThat(newFlight.getId(), is(oldFlight.getId()));
assertThat(newFlight.getFlightNumber(), is("ABC2"));
assertThat(newFlight.getFromAirport(), is("FROM2"));
assertThat(newFlight.getToAirport(), is("TO2"));
newFlight = client.getFlight(oldFlight.getId()); // paranoia
assertThat(newFlight.getId(), is(oldFlight.getId()));
assertThat(newFlight.getFlightNumber(), is("ABC2"));
assertThat(newFlight.getFromAirport(), is("FROM2"));
assertThat(newFlight.getToAirport(), is("TO2"));
}
@Test(expected = NotFoundException.class)
public void tryingToUpdateAFlightWhichDoesNotExistReturnsNotFound() {
// given
Long id = -9999L;
// when
client.updateFlight(id, new Flight("OS202", "GRZ", "DUS"));
}
@Test
public void canGetAFlightByItsId() {
// given
Long id = client.createFlight(new Flight("OS202", "GRZ", "DUS")).getId();
// when
Flight flight = client.getFlight(id);
// then
assertThat(flight.getId(), is(not(0L)));
assertThat(flight.getFlightNumber(), is("OS202"));
assertThat(flight.getFromAirport(), is("GRZ"));
assertThat(flight.getToAirport(), is("DUS"));
}
@Test(expected = NotFoundException.class)
public void tryingToGetAFlightWhichDoesNotExistReturnsNotFound() {
// given
Long id = -9999L;
// when
client.getFlight(id);
}
@Test
public void aFlightCanBeRemoved() {
// given
Long id = client.createFlight(new Flight("OS202", "GRZ", "DUS")).getId();
// when
client.getFlight(id);
client.deleteFlight(id);
// then
try {
client.getFlight(id);
fail("Flight: " + id + " was not removed.");
} catch (NotFoundException ex) {
assertThat(true, is(true));
}
}
@Test(expected = NotFoundException.class)
public void tryingToRemoveAFlightWhichDoesNotExistReturnsNotFound() {
// given
Long id = -9999L;
// when
client.deleteFlight(id);
}
@Test
public void canGetAListOfAllFlights() {
// cleanup
List<Flight> oldFlights = client.getFlights();
oldFlights.forEach(flight -> client.deleteFlight(flight.getId()));
assertThat(client.getFlights().size(), is(0));
// given
Flight flight1 = client.createFlight(new Flight("OS202", "GRZ", "DUS"));
Flight flight2 = client.createFlight(new Flight("LH1234", "GRZ", "VIE"));
// when
List<Flight> newFlights = client.getFlights();
// then
assertThat(newFlights.size(), is(2));
assertThat(newFlights, hasItem(flight1));
assertThat(newFlights, hasItem(flight2));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.trogdor.workload;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.kafka.clients.ApiVersions;
import org.apache.kafka.clients.ClientUtils;
import org.apache.kafka.clients.ManualMetadataUpdater;
import org.apache.kafka.clients.NetworkClient;
import org.apache.kafka.clients.NetworkClientUtils;
import org.apache.kafka.clients.admin.AdminClientConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.internals.KafkaFutureImpl;
import org.apache.kafka.common.metrics.Metrics;
import org.apache.kafka.common.network.ChannelBuilder;
import org.apache.kafka.common.network.Selector;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.trogdor.common.JsonUtil;
import org.apache.kafka.trogdor.common.Platform;
import org.apache.kafka.trogdor.common.ThreadUtils;
import org.apache.kafka.trogdor.common.WorkerUtils;
import org.apache.kafka.trogdor.task.TaskWorker;
import org.apache.kafka.trogdor.task.WorkerStatusTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class ConnectionStressWorker implements TaskWorker {
private static final Logger log = LoggerFactory.getLogger(ConnectionStressWorker.class);
private static final int THROTTLE_PERIOD_MS = 100;
private static final int REPORT_INTERVAL_MS = 20000;
private final String id;
private final ConnectionStressSpec spec;
private final AtomicBoolean running = new AtomicBoolean(false);
private KafkaFutureImpl<String> doneFuture;
private WorkerStatusTracker status;
private long totalConnections;
private long totalFailedConnections;
private long startTimeMs;
private Throttle throttle;
private long nextReportTime;
private ExecutorService workerExecutor;
public ConnectionStressWorker(String id, ConnectionStressSpec spec) {
this.id = id;
this.spec = spec;
}
@Override
public void start(Platform platform, WorkerStatusTracker status,
KafkaFutureImpl<String> doneFuture) throws Exception {
if (!running.compareAndSet(false, true)) {
throw new IllegalStateException("ConnectionStressWorker is already running.");
}
log.info("{}: Activating ConnectionStressWorker with {}", id, spec);
this.doneFuture = doneFuture;
this.status = status;
this.totalConnections = 0;
this.totalFailedConnections = 0;
this.startTimeMs = Time.SYSTEM.milliseconds();
this.throttle = new ConnectStressThrottle(WorkerUtils.
perSecToPerPeriod(spec.targetConnectionsPerSec(), THROTTLE_PERIOD_MS));
this.nextReportTime = 0;
this.workerExecutor = Executors.newFixedThreadPool(spec.numThreads(),
ThreadUtils.createThreadFactory("ConnectionStressWorkerThread%d", false));
for (int i = 0; i < spec.numThreads(); i++) {
this.workerExecutor.submit(new ConnectLoop());
}
}
private static class ConnectStressThrottle extends Throttle {
ConnectStressThrottle(int maxPerPeriod) {
super(maxPerPeriod, THROTTLE_PERIOD_MS);
}
}
public class ConnectLoop implements Runnable {
@Override
public void run() {
try {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, spec.bootstrapServers());
WorkerUtils.addConfigsToProperties(props, spec.commonClientConf(), spec.commonClientConf());
AdminClientConfig conf = new AdminClientConfig(props);
List<InetSocketAddress> addresses = ClientUtils.parseAndValidateAddresses(
conf.getList(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG));
ManualMetadataUpdater updater = new ManualMetadataUpdater(Cluster.bootstrap(addresses).nodes());
while (true) {
if (doneFuture.isDone()) {
break;
}
throttle.increment();
long lastTimeMs = throttle.lastTimeMs();
boolean success = attemptConnection(conf, updater);
synchronized (ConnectionStressWorker.this) {
totalConnections++;
if (!success) {
totalFailedConnections++;
}
if (lastTimeMs > nextReportTime) {
status.update(JsonUtil.JSON_SERDE.valueToTree(
new StatusData(totalConnections,
totalFailedConnections,
(totalConnections * 1000.0) / (lastTimeMs - startTimeMs))));
nextReportTime = lastTimeMs + REPORT_INTERVAL_MS;
}
}
}
} catch (Exception e) {
WorkerUtils.abort(log, "ConnectionStressRunnable", e, doneFuture);
}
}
private boolean attemptConnection(AdminClientConfig conf,
ManualMetadataUpdater updater) throws Exception {
try {
List<Node> nodes = updater.fetchNodes();
Node targetNode = nodes.get(ThreadLocalRandom.current().nextInt(nodes.size()));
try (ChannelBuilder channelBuilder = ClientUtils.createChannelBuilder(conf)) {
try (Metrics metrics = new Metrics()) {
LogContext logContext = new LogContext();
try (Selector selector = new Selector(conf.getLong(AdminClientConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG),
metrics, Time.SYSTEM, "", channelBuilder, logContext)) {
try (NetworkClient client = new NetworkClient(selector,
updater,
"ConnectionStressWorker",
1,
1000,
1000,
4096,
4096,
1000,
Time.SYSTEM,
false,
new ApiVersions(),
logContext)) {
NetworkClientUtils.awaitReady(client, targetNode, Time.SYSTEM, 100);
}
}
}
}
return true;
} catch (IOException e) {
return false;
}
}
}
public static class StatusData {
private final long totalConnections;
private final long totalFailedConnections;
private final double connectsPerSec;
@JsonCreator
StatusData(@JsonProperty("totalConnections") long totalConnections,
@JsonProperty("totalFailedConnections") long totalFailedConnections,
@JsonProperty("connectsPerSec") double connectsPerSec) {
this.totalConnections = totalConnections;
this.totalFailedConnections = totalFailedConnections;
this.connectsPerSec = connectsPerSec;
}
@JsonProperty
public long totalConnections() {
return totalConnections;
}
@JsonProperty
public long totalFailedConnections() {
return totalFailedConnections;
}
@JsonProperty
public double connectsPerSec() {
return connectsPerSec;
}
}
@Override
public void stop(Platform platform) throws Exception {
if (!running.compareAndSet(true, false)) {
throw new IllegalStateException("ConnectionStressWorker is not running.");
}
log.info("{}: Deactivating ConnectionStressWorker.", id);
doneFuture.complete("");
workerExecutor.shutdownNow();
workerExecutor.awaitTermination(1, TimeUnit.DAYS);
this.workerExecutor = null;
this.status = null;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.http.HttpConfig;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.service.CompositeService;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.api.ResourceTracker;
import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse;
import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest;
import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerResponse;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.NodeHealthCheckerService;
import org.apache.hadoop.yarn.server.nodemanager.NodeManager;
import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater;
import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdaterImpl;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceTrackerService;
import org.apache.hadoop.yarn.webapp.util.WebAppUtils;
/**
* Embedded Yarn minicluster for testcases that need to interact with a cluster.
* <p/>
* In a real cluster, resource request matching is done using the hostname, and
* by default Yarn minicluster works in the exact same way as a real cluster.
* <p/>
* If a testcase needs to use multiple nodes and exercise resource request
* matching to a specific node, then the property
* {@YarnConfiguration.RM_SCHEDULER_INCLUDE_PORT_IN_NODE_NAME} should be set
* <code>true</code> in the configuration used to initialize the minicluster.
* <p/>
* With this property set to <code>true</code>, the matching will be done using
* the <code>hostname:port</code> of the namenodes. In such case, the AM must
* do resource request using <code>hostname:port</code> as the location.
*/
public class MiniYARNCluster extends CompositeService {
private static final Log LOG = LogFactory.getLog(MiniYARNCluster.class);
// temp fix until metrics system can auto-detect itself running in unit test:
static {
DefaultMetricsSystem.setMiniClusterMode(true);
}
private NodeManager[] nodeManagers;
private ResourceManager resourceManager;
private ResourceManagerWrapper resourceManagerWrapper;
private File testWorkDir;
// Number of nm-local-dirs per nodemanager
private int numLocalDirs;
// Number of nm-log-dirs per nodemanager
private int numLogDirs;
/**
* @param testName name of the test
* @param noOfNodeManagers the number of node managers in the cluster
* @param numLocalDirs the number of nm-local-dirs per nodemanager
* @param numLogDirs the number of nm-log-dirs per nodemanager
*/
public MiniYARNCluster(String testName, int noOfNodeManagers,
int numLocalDirs, int numLogDirs) {
super(testName.replace("$", ""));
this.numLocalDirs = numLocalDirs;
this.numLogDirs = numLogDirs;
String testSubDir = testName.replace("$", "");
File targetWorkDir = new File("target", testSubDir);
try {
FileContext.getLocalFSFileContext().delete(
new Path(targetWorkDir.getAbsolutePath()), true);
} catch (Exception e) {
LOG.warn("COULD NOT CLEANUP", e);
throw new YarnRuntimeException("could not cleanup test dir: "+ e, e);
}
if (Shell.WINDOWS) {
// The test working directory can exceed the maximum path length supported
// by some Windows APIs and cmd.exe (260 characters). To work around this,
// create a symlink in temporary storage with a much shorter path,
// targeting the full path to the test working directory. Then, use the
// symlink as the test working directory.
String targetPath = targetWorkDir.getAbsolutePath();
File link = new File(System.getProperty("java.io.tmpdir"),
String.valueOf(System.currentTimeMillis()));
String linkPath = link.getAbsolutePath();
try {
FileContext.getLocalFSFileContext().delete(new Path(linkPath), true);
} catch (IOException e) {
throw new YarnRuntimeException("could not cleanup symlink: " + linkPath, e);
}
// Guarantee target exists before creating symlink.
targetWorkDir.mkdirs();
ShellCommandExecutor shexec = new ShellCommandExecutor(
Shell.getSymlinkCommand(targetPath, linkPath));
try {
shexec.execute();
} catch (IOException e) {
throw new YarnRuntimeException(String.format(
"failed to create symlink from %s to %s, shell output: %s", linkPath,
targetPath, shexec.getOutput()), e);
}
this.testWorkDir = link;
} else {
this.testWorkDir = targetWorkDir;
}
resourceManagerWrapper = new ResourceManagerWrapper();
addService(resourceManagerWrapper);
nodeManagers = new CustomNodeManager[noOfNodeManagers];
for(int index = 0; index < noOfNodeManagers; index++) {
addService(new NodeManagerWrapper(index));
nodeManagers[index] = new CustomNodeManager();
}
}
@Override
public void serviceInit(Configuration conf) throws Exception {
super.serviceInit(conf instanceof YarnConfiguration ? conf
: new YarnConfiguration(
conf));
}
public File getTestWorkDir() {
return testWorkDir;
}
public ResourceManager getResourceManager() {
return this.resourceManager;
}
public NodeManager getNodeManager(int i) {
return this.nodeManagers[i];
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException ex) {
throw new RuntimeException(ex);
}
}
private class ResourceManagerWrapper extends AbstractService {
public ResourceManagerWrapper() {
super(ResourceManagerWrapper.class.getName());
}
@Override
public synchronized void serviceStart() throws Exception {
try {
getConfig().setBoolean(YarnConfiguration.IS_MINI_YARN_CLUSTER, true);
if (!getConfig().getBoolean(
YarnConfiguration.YARN_MINICLUSTER_FIXED_PORTS,
YarnConfiguration.DEFAULT_YARN_MINICLUSTER_FIXED_PORTS)) {
// pick free random ports.
String hostname = MiniYARNCluster.getHostname();
getConfig().set(YarnConfiguration.RM_ADDRESS,
hostname + ":0");
getConfig().set(YarnConfiguration.RM_ADMIN_ADDRESS,
hostname + ":0");
getConfig().set(YarnConfiguration.RM_SCHEDULER_ADDRESS,
hostname + ":0");
getConfig().set(YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS,
hostname + ":0");
WebAppUtils.setRMWebAppHostnameAndPort(getConfig(), hostname, 0);
}
resourceManager = new ResourceManager() {
@Override
protected void doSecureLogin() throws IOException {
// Don't try to login using keytab in the testcase.
};
};
resourceManager.init(getConfig());
new Thread() {
public void run() {
resourceManager.start();
};
}.start();
int waitCount = 0;
while (resourceManager.getServiceState() == STATE.INITED
&& waitCount++ < 60) {
LOG.info("Waiting for RM to start...");
Thread.sleep(1500);
}
if (resourceManager.getServiceState() != STATE.STARTED) {
// RM could have failed.
throw new IOException(
"ResourceManager failed to start. Final state is "
+ resourceManager.getServiceState());
}
super.serviceStart();
} catch (Throwable t) {
throw new YarnRuntimeException(t);
}
LOG.info("MiniYARN ResourceManager address: " +
getConfig().get(YarnConfiguration.RM_ADDRESS));
LOG.info("MiniYARN ResourceManager web address: " +
WebAppUtils.getRMWebAppURLWithoutScheme(getConfig()));
}
@Override
public synchronized void serviceStop() throws Exception {
if (resourceManager != null) {
resourceManager.stop();
}
super.serviceStop();
if (Shell.WINDOWS) {
// On Windows, clean up the short temporary symlink that was created to
// work around path length limitation.
String testWorkDirPath = testWorkDir.getAbsolutePath();
try {
FileContext.getLocalFSFileContext().delete(new Path(testWorkDirPath),
true);
} catch (IOException e) {
LOG.warn("could not cleanup symlink: " +
testWorkDir.getAbsolutePath());
}
}
}
}
private class NodeManagerWrapper extends AbstractService {
int index = 0;
public NodeManagerWrapper(int i) {
super(NodeManagerWrapper.class.getName() + "_" + i);
index = i;
}
public synchronized void serviceInit(Configuration conf) throws Exception {
Configuration config = new YarnConfiguration(conf);
super.serviceInit(config);
}
/**
* Create local/log directories
* @param dirType type of directories i.e. local dirs or log dirs
* @param numDirs number of directories
* @return the created directories as a comma delimited String
*/
private String prepareDirs(String dirType, int numDirs) {
File []dirs = new File[numDirs];
String dirsString = "";
for (int i = 0; i < numDirs; i++) {
dirs[i]= new File(testWorkDir, MiniYARNCluster.this.getName()
+ "-" + dirType + "Dir-nm-" + index + "_" + i);
dirs[i].mkdirs();
LOG.info("Created " + dirType + "Dir in " + dirs[i].getAbsolutePath());
String delimiter = (i > 0) ? "," : "";
dirsString = dirsString.concat(delimiter + dirs[i].getAbsolutePath());
}
return dirsString;
}
public synchronized void serviceStart() throws Exception {
try {
// create nm-local-dirs and configure them for the nodemanager
String localDirsString = prepareDirs("local", numLocalDirs);
getConfig().set(YarnConfiguration.NM_LOCAL_DIRS, localDirsString);
// create nm-log-dirs and configure them for the nodemanager
String logDirsString = prepareDirs("log", numLogDirs);
getConfig().set(YarnConfiguration.NM_LOG_DIRS, logDirsString);
File remoteLogDir =
new File(testWorkDir, MiniYARNCluster.this.getName()
+ "-remoteLogDir-nm-" + index);
remoteLogDir.mkdir();
getConfig().set(YarnConfiguration.NM_REMOTE_APP_LOG_DIR,
remoteLogDir.getAbsolutePath());
// By default AM + 2 containers
getConfig().setInt(YarnConfiguration.NM_PMEM_MB, 4*1024);
getConfig().set(YarnConfiguration.NM_ADDRESS,
MiniYARNCluster.getHostname() + ":0");
getConfig().set(YarnConfiguration.NM_LOCALIZER_ADDRESS,
MiniYARNCluster.getHostname() + ":0");
WebAppUtils
.setNMWebAppHostNameAndPort(getConfig(),
MiniYARNCluster.getHostname(), 0);
// Disable resource checks by default
if (!getConfig().getBoolean(
YarnConfiguration.YARN_MINICLUSTER_CONTROL_RESOURCE_MONITORING,
YarnConfiguration.
DEFAULT_YARN_MINICLUSTER_CONTROL_RESOURCE_MONITORING)) {
getConfig().setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
getConfig().setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
}
LOG.info("Starting NM: " + index);
nodeManagers[index].init(getConfig());
new Thread() {
public void run() {
nodeManagers[index].start();
};
}.start();
int waitCount = 0;
while (nodeManagers[index].getServiceState() == STATE.INITED
&& waitCount++ < 60) {
LOG.info("Waiting for NM " + index + " to start...");
Thread.sleep(1000);
}
if (nodeManagers[index].getServiceState() != STATE.STARTED) {
// RM could have failed.
throw new IOException("NodeManager " + index + " failed to start");
}
super.serviceStart();
} catch (Throwable t) {
throw new YarnRuntimeException(t);
}
}
@Override
public synchronized void serviceStop() throws Exception {
if (nodeManagers[index] != null) {
nodeManagers[index].stop();
}
super.serviceStop();
}
}
private class CustomNodeManager extends NodeManager {
@Override
protected void doSecureLogin() throws IOException {
// Don't try to login using keytab in the testcase.
};
@Override
protected NodeStatusUpdater createNodeStatusUpdater(Context context,
Dispatcher dispatcher, NodeHealthCheckerService healthChecker) {
return new NodeStatusUpdaterImpl(context, dispatcher,
healthChecker, metrics) {
@Override
protected ResourceTracker getRMClient() {
final ResourceTrackerService rt = resourceManager
.getResourceTrackerService();
final RecordFactory recordFactory =
RecordFactoryProvider.getRecordFactory(null);
// For in-process communication without RPC
return new ResourceTracker() {
@Override
public NodeHeartbeatResponse nodeHeartbeat(
NodeHeartbeatRequest request) throws YarnException,
IOException {
NodeHeartbeatResponse response = recordFactory.newRecordInstance(
NodeHeartbeatResponse.class);
try {
response = rt.nodeHeartbeat(request);
} catch (YarnException e) {
LOG.info("Exception in heartbeat from node " +
request.getNodeStatus().getNodeId(), e);
throw e;
}
return response;
}
@Override
public RegisterNodeManagerResponse registerNodeManager(
RegisterNodeManagerRequest request)
throws YarnException, IOException {
RegisterNodeManagerResponse response = recordFactory.
newRecordInstance(RegisterNodeManagerResponse.class);
try {
response = rt.registerNodeManager(request);
} catch (YarnException e) {
LOG.info("Exception in node registration from "
+ request.getNodeId().toString(), e);
throw e;
}
return response;
}
};
};
@Override
protected void stopRMProxy() {
return;
}
};
};
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.network;
import org.elasticsearch.action.support.replication.ReplicationTask;
import org.elasticsearch.cluster.routing.allocation.command.AllocateEmptyPrimaryAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.AllocateReplicaAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.AllocateStalePrimaryAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.AllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.CancelAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.PageCacheRecycler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.http.HttpServerTransport;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.plugins.NetworkPlugin;
import org.elasticsearch.tasks.RawTaskStatus;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportInterceptor;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestHandler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
/**
* A module to handle registering and binding all network related classes.
*/
public final class NetworkModule {
public static final String TRANSPORT_TYPE_KEY = "transport.type";
public static final String HTTP_TYPE_KEY = "http.type";
public static final String HTTP_TYPE_DEFAULT_KEY = "http.type.default";
public static final String TRANSPORT_TYPE_DEFAULT_KEY = "transport.type.default";
public static final Setting<String> TRANSPORT_DEFAULT_TYPE_SETTING = Setting.simpleString(TRANSPORT_TYPE_DEFAULT_KEY,
Property.NodeScope);
public static final Setting<String> HTTP_DEFAULT_TYPE_SETTING = Setting.simpleString(HTTP_TYPE_DEFAULT_KEY, Property.NodeScope);
public static final Setting<String> HTTP_TYPE_SETTING = Setting.simpleString(HTTP_TYPE_KEY, Property.NodeScope);
public static final Setting<Boolean> HTTP_ENABLED = Setting.boolSetting("http.enabled", true,
Property.NodeScope, Property.Deprecated);
public static final Setting<String> TRANSPORT_TYPE_SETTING = Setting.simpleString(TRANSPORT_TYPE_KEY, Property.NodeScope);
private final Settings settings;
private final boolean transportClient;
private static final List<NamedWriteableRegistry.Entry> namedWriteables = new ArrayList<>();
private static final List<NamedXContentRegistry.Entry> namedXContents = new ArrayList<>();
static {
registerAllocationCommand(CancelAllocationCommand::new, CancelAllocationCommand::fromXContent,
CancelAllocationCommand.COMMAND_NAME_FIELD);
registerAllocationCommand(MoveAllocationCommand::new, MoveAllocationCommand::fromXContent,
MoveAllocationCommand.COMMAND_NAME_FIELD);
registerAllocationCommand(AllocateReplicaAllocationCommand::new, AllocateReplicaAllocationCommand::fromXContent,
AllocateReplicaAllocationCommand.COMMAND_NAME_FIELD);
registerAllocationCommand(AllocateEmptyPrimaryAllocationCommand::new, AllocateEmptyPrimaryAllocationCommand::fromXContent,
AllocateEmptyPrimaryAllocationCommand.COMMAND_NAME_FIELD);
registerAllocationCommand(AllocateStalePrimaryAllocationCommand::new, AllocateStalePrimaryAllocationCommand::fromXContent,
AllocateStalePrimaryAllocationCommand.COMMAND_NAME_FIELD);
namedWriteables.add(
new NamedWriteableRegistry.Entry(Task.Status.class, ReplicationTask.Status.NAME, ReplicationTask.Status::new));
namedWriteables.add(
new NamedWriteableRegistry.Entry(Task.Status.class, RawTaskStatus.NAME, RawTaskStatus::new));
}
private final Map<String, Supplier<Transport>> transportFactories = new HashMap<>();
private final Map<String, Supplier<HttpServerTransport>> transportHttpFactories = new HashMap<>();
private final List<TransportInterceptor> transportIntercetors = new ArrayList<>();
/**
* Creates a network module that custom networking classes can be plugged into.
* @param settings The settings for the node
* @param transportClient True if only transport classes should be allowed to be registered, false otherwise.
*/
public NetworkModule(Settings settings, boolean transportClient, List<NetworkPlugin> plugins, ThreadPool threadPool,
BigArrays bigArrays,
PageCacheRecycler pageCacheRecycler,
CircuitBreakerService circuitBreakerService,
NamedWriteableRegistry namedWriteableRegistry,
NamedXContentRegistry xContentRegistry,
NetworkService networkService, HttpServerTransport.Dispatcher dispatcher) {
this.settings = settings;
this.transportClient = transportClient;
for (NetworkPlugin plugin : plugins) {
if (transportClient == false && HTTP_ENABLED.get(settings)) {
Map<String, Supplier<HttpServerTransport>> httpTransportFactory = plugin.getHttpTransports(settings, threadPool, bigArrays,
circuitBreakerService, namedWriteableRegistry, xContentRegistry, networkService, dispatcher);
for (Map.Entry<String, Supplier<HttpServerTransport>> entry : httpTransportFactory.entrySet()) {
registerHttpTransport(entry.getKey(), entry.getValue());
}
}
Map<String, Supplier<Transport>> transportFactory = plugin.getTransports(settings, threadPool, bigArrays, pageCacheRecycler,
circuitBreakerService, namedWriteableRegistry, networkService);
for (Map.Entry<String, Supplier<Transport>> entry : transportFactory.entrySet()) {
registerTransport(entry.getKey(), entry.getValue());
}
List<TransportInterceptor> transportInterceptors = plugin.getTransportInterceptors(namedWriteableRegistry,
threadPool.getThreadContext());
for (TransportInterceptor interceptor : transportInterceptors) {
registerTransportInterceptor(interceptor);
}
}
}
public boolean isTransportClient() {
return transportClient;
}
/** Adds a transport implementation that can be selected by setting {@link #TRANSPORT_TYPE_KEY}. */
private void registerTransport(String key, Supplier<Transport> factory) {
if (transportFactories.putIfAbsent(key, factory) != null) {
throw new IllegalArgumentException("transport for name: " + key + " is already registered");
}
}
/** Adds an http transport implementation that can be selected by setting {@link #HTTP_TYPE_KEY}. */
// TODO: we need another name than "http transport"....so confusing with transportClient...
private void registerHttpTransport(String key, Supplier<HttpServerTransport> factory) {
if (transportClient) {
throw new IllegalArgumentException("Cannot register http transport " + key + " for transport client");
}
if (transportHttpFactories.putIfAbsent(key, factory) != null) {
throw new IllegalArgumentException("transport for name: " + key + " is already registered");
}
}
/**
* Register an allocation command.
* <p>
* This lives here instead of the more aptly named ClusterModule because the Transport client needs these to be registered.
* </p>
* @param reader the reader to read it from a stream
* @param parser the parser to read it from XContent
* @param commandName the names under which the command should be parsed. The {@link ParseField#getPreferredName()} is special because
* it is the name under which the command's reader is registered.
*/
private static <T extends AllocationCommand> void registerAllocationCommand(Writeable.Reader<T> reader,
CheckedFunction<XContentParser, T, IOException> parser, ParseField commandName) {
namedXContents.add(new NamedXContentRegistry.Entry(AllocationCommand.class, commandName, parser));
namedWriteables.add(new NamedWriteableRegistry.Entry(AllocationCommand.class, commandName.getPreferredName(), reader));
}
public static List<NamedWriteableRegistry.Entry> getNamedWriteables() {
return Collections.unmodifiableList(namedWriteables);
}
public static List<NamedXContentRegistry.Entry> getNamedXContents() {
return Collections.unmodifiableList(namedXContents);
}
public Supplier<HttpServerTransport> getHttpServerTransportSupplier() {
final String name;
if (HTTP_TYPE_SETTING.exists(settings)) {
name = HTTP_TYPE_SETTING.get(settings);
} else {
name = HTTP_DEFAULT_TYPE_SETTING.get(settings);
}
final Supplier<HttpServerTransport> factory = transportHttpFactories.get(name);
if (factory == null) {
throw new IllegalStateException("Unsupported http.type [" + name + "]");
}
return factory;
}
public boolean isHttpEnabled() {
return transportClient == false && HTTP_ENABLED.get(settings);
}
public Supplier<Transport> getTransportSupplier() {
final String name;
if (TRANSPORT_TYPE_SETTING.exists(settings)) {
name = TRANSPORT_TYPE_SETTING.get(settings);
} else {
name = TRANSPORT_DEFAULT_TYPE_SETTING.get(settings);
}
final Supplier<Transport> factory = transportFactories.get(name);
if (factory == null) {
throw new IllegalStateException("Unsupported transport.type [" + name + "]");
}
return factory;
}
/**
* Registers a new {@link TransportInterceptor}
*/
private void registerTransportInterceptor(TransportInterceptor interceptor) {
this.transportIntercetors.add(Objects.requireNonNull(interceptor, "interceptor must not be null"));
}
/**
* Returns a composite {@link TransportInterceptor} containing all registered interceptors
* @see #registerTransportInterceptor(TransportInterceptor)
*/
public TransportInterceptor getTransportInterceptor() {
return new CompositeTransportInterceptor(this.transportIntercetors);
}
public static final class CompositeTransportInterceptor implements TransportInterceptor {
public final List<TransportInterceptor> transportInterceptors;
private CompositeTransportInterceptor(List<TransportInterceptor> transportInterceptors) {
this.transportInterceptors = new ArrayList<>(transportInterceptors);
}
@Override
public <T extends TransportRequest> TransportRequestHandler<T> interceptHandler(String action, String executor,
boolean forceExecution,
TransportRequestHandler<T> actualHandler) {
for (TransportInterceptor interceptor : this.transportInterceptors) {
actualHandler = interceptor.interceptHandler(action, executor, forceExecution, actualHandler);
}
return actualHandler;
}
@Override
public AsyncSender interceptSender(AsyncSender sender) {
for (TransportInterceptor interceptor : this.transportInterceptors) {
sender = interceptor.interceptSender(sender);
}
return sender;
}
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.tools.util.base;
import com.intellij.diff.DiffContext;
import com.intellij.diff.FrameDiffTool;
import com.intellij.diff.FrameDiffTool.DiffViewer;
import com.intellij.diff.requests.ContentDiffRequest;
import com.intellij.diff.tools.util.DiffDataKeys;
import com.intellij.diff.util.DiffTaskQueue;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.util.ProgressWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.Alarm;
import com.intellij.util.Function;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mustbe.consulo.RequiredDispatchThread;
import javax.swing.*;
import java.util.List;
public abstract class DiffViewerBase implements DiffViewer, DataProvider {
protected static final Logger LOG = Logger.getInstance(DiffViewerBase.class);
@Nullable protected final Project myProject;
@NotNull protected final DiffContext myContext;
@NotNull protected final ContentDiffRequest myRequest;
@NotNull private final DiffTaskQueue myTaskExecutor = new DiffTaskQueue();
@NotNull private final Alarm myTaskAlarm = new Alarm();
private volatile boolean myDisposed;
public DiffViewerBase(@NotNull DiffContext context, @NotNull ContentDiffRequest request) {
myProject = context.getProject();
myContext = context;
myRequest = request;
}
@NotNull
public final FrameDiffTool.ToolbarComponents init() {
processContextHints();
onInit();
FrameDiffTool.ToolbarComponents components = new FrameDiffTool.ToolbarComponents();
components.toolbarActions = createToolbarActions();
components.popupActions = createPopupActions();
components.statusPanel = getStatusPanel();
rediff(true);
return components;
}
@Override
@RequiredDispatchThread
public final void dispose() {
if (myDisposed) return;
Runnable doDispose = new Runnable() {
@Override
public void run() {
if (myDisposed) return;
myDisposed = true;
abortRediff();
updateContextHints();
onDispose();
}
};
if (!ApplicationManager.getApplication().isDispatchThread()) LOG.warn(new Throwable("dispose() not from EDT"));
UIUtil.invokeLaterIfNeeded(doDispose);
}
@RequiredDispatchThread
protected void processContextHints() {
}
@RequiredDispatchThread
protected void updateContextHints() {
}
@RequiredDispatchThread
public final void scheduleRediff() {
if (isDisposed()) return;
abortRediff();
myTaskAlarm.addRequest(new Runnable() {
@Override
public void run() {
rediff();
}
}, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS);
}
@RequiredDispatchThread
public final void abortRediff() {
myTaskExecutor.abort();
myTaskAlarm.cancelAllRequests();
}
@RequiredDispatchThread
public final void rediff() {
rediff(false);
}
@RequiredDispatchThread
public final void rediff(boolean trySync) {
if (isDisposed()) return;
abortRediff();
onBeforeRediff();
// most of performRediff implementations take ReadLock inside. If EDT is holding write lock - this will never happen,
// and diff will not be calculated. This could happen for diff from FileDocumentManager.
boolean forceEDT = ApplicationManager.getApplication().isWriteAccessAllowed();
int waitMillis = trySync || tryRediffSynchronously() ? ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS : 0;
myTaskExecutor.executeAndTryWait(
new Function<ProgressIndicator, Runnable>() {
@Override
public Runnable fun(ProgressIndicator indicator) {
return performRediff(indicator);
}
},
new Runnable() {
@Override
public void run() {
onSlowRediff();
}
},
waitMillis, forceEDT
);
}
//
// Getters
//
@Nullable
public Project getProject() {
return myProject;
}
@NotNull
public ContentDiffRequest getRequest() {
return myRequest;
}
@NotNull
public DiffContext getContext() {
return myContext;
}
public boolean isDisposed() {
return myDisposed;
}
//
// Abstract
//
@RequiredDispatchThread
protected boolean tryRediffSynchronously() {
return myContext.isWindowFocused();
}
@Nullable
protected List<AnAction> createToolbarActions() {
return null;
}
@Nullable
protected List<AnAction> createPopupActions() {
return null;
}
@Nullable
protected JComponent getStatusPanel() {
return null;
}
@RequiredDispatchThread
protected void onInit() {
}
@RequiredDispatchThread
protected void onSlowRediff() {
}
@RequiredDispatchThread
protected void onBeforeRediff() {
}
@NotNull
protected abstract Runnable performRediff(@NotNull ProgressIndicator indicator);
@RequiredDispatchThread
protected void onDispose() {
Disposer.dispose(myTaskAlarm);
}
@Nullable
protected OpenFileDescriptor getOpenFileDescriptor() {
return null;
}
//
// Helpers
//
@Nullable
@Override
public Object getData(@NonNls String dataId) {
if (CommonDataKeys.NAVIGATABLE.is(dataId)) {
return getOpenFileDescriptor();
}
else if (DiffDataKeys.OPEN_FILE_DESCRIPTOR.is(dataId)) {
return getOpenFileDescriptor();
}
else if (CommonDataKeys.PROJECT.is(dataId)) {
return myProject;
}
else {
return null;
}
}
}
| |
/*
* Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print;
import java.util.ArrayList;
import java.util.Iterator;
import javax.print.attribute.AttributeSet;
import sun.awt.AppContext;
import java.util.ServiceLoader;
import java.util.ServiceConfigurationError;
/** Implementations of this class provide lookup services for
* print services (typically equivalent to printers) of a particular type.
* <p>
* Multiple implementations may be installed concurrently.
* All implementations must be able to describe the located printers
* as instances of a PrintService.
* Typically implementations of this service class are located
* automatically in JAR files (see the SPI JAR file specification).
* These classes must be instantiable using a default constructor.
* Alternatively applications may explicitly register instances
* at runtime.
* <p>
* Applications use only the static methods of this abstract class.
* The instance methods are implemented by a service provider in a subclass
* and the unification of the results from all installed lookup classes
* are reported by the static methods of this class when called by
* the application.
* <p>
* A PrintServiceLookup implementor is recommended to check for the
* SecurityManager.checkPrintJobAccess() to deny access to untrusted code.
* Following this recommended policy means that untrusted code may not
* be able to locate any print services. Downloaded applets are the most
* common example of untrusted code.
* <p>
* This check is made on a per lookup service basis to allow flexibility in
* the policy to reflect the needs of different lookup services.
* <p>
* Services which are registered by registerService(PrintService)
* will not be included in lookup results if a security manager is
* installed and its checkPrintJobAccess() method denies access.
*/
public abstract class PrintServiceLookup {
static class Services {
private ArrayList listOfLookupServices = null;
private ArrayList registeredServices = null;
}
private static Services getServicesForContext() {
Services services =
(Services)AppContext.getAppContext().get(Services.class);
if (services == null) {
services = new Services();
AppContext.getAppContext().put(Services.class, services);
}
return services;
}
private static ArrayList getListOfLookupServices() {
return getServicesForContext().listOfLookupServices;
}
private static ArrayList initListOfLookupServices() {
ArrayList listOfLookupServices = new ArrayList();
getServicesForContext().listOfLookupServices = listOfLookupServices;
return listOfLookupServices;
}
private static ArrayList getRegisteredServices() {
return getServicesForContext().registeredServices;
}
private static ArrayList initRegisteredServices() {
ArrayList registeredServices = new ArrayList();
getServicesForContext().registeredServices = registeredServices;
return registeredServices;
}
/**
* Locates print services capable of printing the specified
* {@link DocFlavor}.
*
* @param flavor the flavor to print. If null, this constraint is not
* used.
* @param attributes attributes that the print service must support.
* If null this constraint is not used.
*
* @return array of matching <code>PrintService</code> objects
* representing print services that support the specified flavor
* attributes. If no services match, the array is zero-length.
*/
public static final PrintService[]
lookupPrintServices(DocFlavor flavor,
AttributeSet attributes) {
ArrayList list = getServices(flavor, attributes);
return (PrintService[])(list.toArray(new PrintService[list.size()]));
}
/**
* Locates MultiDoc print Services capable of printing MultiDocs
* containing all the specified doc flavors.
* <P> This method is useful to help locate a service that can print
* a <code>MultiDoc</code> in which the elements may be different
* flavors. An application could perform this itself by multiple lookups
* on each <code>DocFlavor</code> in turn and collating the results,
* but the lookup service may be able to do this more efficiently.
*
* @param flavors the flavors to print. If null or empty this
* constraint is not used.
* Otherwise return only multidoc print services that can print all
* specified doc flavors.
* @param attributes attributes that the print service must
* support. If null this constraint is not used.
*
* @return array of matching {@link MultiDocPrintService} objects.
* If no services match, the array is zero-length.
*
*/
public static final MultiDocPrintService[]
lookupMultiDocPrintServices(DocFlavor[] flavors,
AttributeSet attributes) {
ArrayList list = getMultiDocServices(flavors, attributes);
return (MultiDocPrintService[])
list.toArray(new MultiDocPrintService[list.size()]);
}
/**
* Locates the default print service for this environment.
* This may return null.
* If multiple lookup services each specify a default, the
* chosen service is not precisely defined, but a
* platform native service, rather than an installed service,
* is usually returned as the default. If there is no clearly
* identifiable
* platform native default print service, the default is the first
* to be located in an implementation-dependent manner.
* <p>
* This may include making use of any preferences API that is available
* as part of the Java or native platform.
* This algorithm may be overridden by a user setting the property
* javax.print.defaultPrinter.
* A service specified must be discovered to be valid and currently
* available to be returned as the default.
*
* @return the default PrintService.
*/
public static final PrintService lookupDefaultPrintService() {
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
PrintServiceLookup lus = (PrintServiceLookup)psIterator.next();
PrintService service = lus.getDefaultPrintService();
if (service != null) {
return service;
}
} catch (Exception e) {
}
}
return null;
}
/**
* Allows an application to explicitly register a class that
* implements lookup services. The registration will not persist
* across VM invocations.
* This is useful if an application needs to make a new service
* available that is not part of the installation.
* If the lookup service is already registered, or cannot be registered,
* the method returns false.
* <p>
*
* @param sp an implementation of a lookup service.
* @return <code>true</code> if the new lookup service is newly
* registered; <code>false</code> otherwise.
*/
public static boolean registerServiceProvider(PrintServiceLookup sp) {
synchronized (PrintServiceLookup.class) {
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
Object lus = psIterator.next();
if (lus.getClass() == sp.getClass()) {
return false;
}
} catch (Exception e) {
}
}
getListOfLookupServices().add(sp);
return true;
}
}
/**
* Allows an application to directly register an instance of a
* class which implements a print service.
* The lookup operations for this service will be
* performed by the PrintServiceLookup class using the attribute
* values and classes reported by the service.
* This may be less efficient than a lookup
* service tuned for that service.
* Therefore registering a <code>PrintServiceLookup</code> instance
* instead is recommended.
* The method returns true if this service is not previously
* registered and is now successfully registered.
* This method should not be called with StreamPrintService instances.
* They will always fail to register and the method will return false.
* @param service an implementation of a print service.
* @return <code>true</code> if the service is newly
* registered; <code>false</code> otherwise.
*/
public static boolean registerService(PrintService service) {
synchronized (PrintServiceLookup.class) {
if (service instanceof StreamPrintService) {
return false;
}
ArrayList registeredServices = getRegisteredServices();
if (registeredServices == null) {
registeredServices = initRegisteredServices();
}
else {
if (registeredServices.contains(service)) {
return false;
}
}
registeredServices.add(service);
return true;
}
}
/**
* Locates services that can be positively confirmed to support
* the combination of attributes and DocFlavors specified.
* This method is not called directly by applications.
* <p>
* Implemented by a service provider, used by the static methods
* of this class.
* <p>
* The results should be the same as obtaining all the PrintServices
* and querying each one individually on its support for the
* specified attributes and flavors, but the process can be more
* efficient by taking advantage of the capabilities of lookup services
* for the print services.
*
* @param flavor of document required. If null it is ignored.
* @param attributes required to be supported. If null this
* constraint is not used.
* @return array of matching PrintServices. If no services match, the
* array is zero-length.
*/
public abstract PrintService[] getPrintServices(DocFlavor flavor,
AttributeSet attributes);
/**
* Not called directly by applications.
* Implemented by a service provider, used by the static methods
* of this class.
* @return array of all PrintServices known to this lookup service
* class. If none are found, the array is zero-length.
*/
public abstract PrintService[] getPrintServices() ;
/**
* Not called directly by applications.
* <p>
* Implemented by a service provider, used by the static methods
* of this class.
* <p>
* Locates MultiDoc print services which can be positively confirmed
* to support the combination of attributes and DocFlavors specified.
* <p>
*
* @param flavors of documents required. If null or empty it is ignored.
* @param attributes required to be supported. If null this
* constraint is not used.
* @return array of matching PrintServices. If no services match, the
* array is zero-length.
*/
public abstract MultiDocPrintService[]
getMultiDocPrintServices(DocFlavor[] flavors,
AttributeSet attributes);
/**
* Not called directly by applications.
* Implemented by a service provider, and called by the print lookup
* service
* @return the default PrintService for this lookup service.
* If there is no default, returns null.
*/
public abstract PrintService getDefaultPrintService();
private static ArrayList getAllLookupServices() {
synchronized (PrintServiceLookup.class) {
ArrayList listOfLookupServices = getListOfLookupServices();
if (listOfLookupServices != null) {
return listOfLookupServices;
} else {
listOfLookupServices = initListOfLookupServices();
}
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() {
Iterator<PrintServiceLookup> iterator =
ServiceLoader.load(PrintServiceLookup.class).
iterator();
ArrayList los = getListOfLookupServices();
while (iterator.hasNext()) {
try {
los.add(iterator.next());
} catch (ServiceConfigurationError err) {
/* In the applet case, we continue */
if (System.getSecurityManager() != null) {
err.printStackTrace();
} else {
throw err;
}
}
}
return null;
}
});
} catch (java.security.PrivilegedActionException e) {
}
return listOfLookupServices;
}
}
private static ArrayList getServices(DocFlavor flavor,
AttributeSet attributes) {
ArrayList listOfServices = new ArrayList();
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
PrintServiceLookup lus = (PrintServiceLookup)psIterator.next();
PrintService[] services=null;
if (flavor == null && attributes == null) {
try {
services = lus.getPrintServices();
} catch (Throwable tr) {
}
} else {
services = lus.getPrintServices(flavor, attributes);
}
if (services == null) {
continue;
}
for (int i=0; i<services.length; i++) {
listOfServices.add(services[i]);
}
} catch (Exception e) {
}
}
/* add any directly registered services */
ArrayList registeredServices = null;
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPrintJobAccess();
}
registeredServices = getRegisteredServices();
} catch (SecurityException se) {
}
if (registeredServices != null) {
PrintService[] services = (PrintService[])
registeredServices.toArray(
new PrintService[registeredServices.size()]);
for (int i=0; i<services.length; i++) {
if (!listOfServices.contains(services[i])) {
if (flavor == null && attributes == null) {
listOfServices.add(services[i]);
} else if (((flavor != null &&
services[i].isDocFlavorSupported(flavor)) ||
flavor == null) &&
null == services[i].getUnsupportedAttributes(
flavor, attributes)) {
listOfServices.add(services[i]);
}
}
}
}
return listOfServices;
}
private static ArrayList getMultiDocServices(DocFlavor[] flavors,
AttributeSet attributes) {
ArrayList listOfServices = new ArrayList();
Iterator psIterator = getAllLookupServices().iterator();
while (psIterator.hasNext()) {
try {
PrintServiceLookup lus = (PrintServiceLookup)psIterator.next();
MultiDocPrintService[] services =
lus.getMultiDocPrintServices(flavors, attributes);
if (services == null) {
continue;
}
for (int i=0; i<services.length; i++) {
listOfServices.add(services[i]);
}
} catch (Exception e) {
}
}
/* add any directly registered services */
ArrayList registeredServices = null;
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPrintJobAccess();
}
registeredServices = getRegisteredServices();
} catch (Exception e) {
}
if (registeredServices != null) {
PrintService[] services = (PrintService[])
registeredServices.toArray(
new PrintService[registeredServices.size()]);
for (int i=0; i<services.length; i++) {
if (services[i] instanceof MultiDocPrintService &&
!listOfServices.contains(services[i])) {
if (flavors == null || flavors.length == 0) {
listOfServices.add(services[i]);
} else {
boolean supported = true;
for (int f=0; f<flavors.length; f++) {
if (services[i].isDocFlavorSupported(flavors[f])) {
if (services[i].getUnsupportedAttributes(
flavors[f], attributes) != null) {
supported = false;
break;
}
} else {
supported = false;
break;
}
}
if (supported) {
listOfServices.add(services[i]);
}
}
}
}
}
return listOfServices;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.value;
import static javax.jcr.PropertyType.BINARY;
import static javax.jcr.PropertyType.BOOLEAN;
import static javax.jcr.PropertyType.DATE;
import static javax.jcr.PropertyType.DECIMAL;
import static javax.jcr.PropertyType.DOUBLE;
import static javax.jcr.PropertyType.LONG;
import static javax.jcr.PropertyType.NAME;
import static javax.jcr.PropertyType.PATH;
import static javax.jcr.PropertyType.REFERENCE;
import static javax.jcr.PropertyType.STRING;
import static javax.jcr.PropertyType.UNDEFINED;
import static javax.jcr.PropertyType.WEAKREFERENCE;
import com.google.common.collect.ImmutableSet;
import org.apache.jackrabbit.util.Base64;
import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.util.TransientFileFactory;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.ValueFactory;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FilterInputStream;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* The <code>ValueHelper</code> class provides several <code>Value</code>
* related utility methods.
*/
public class ValueHelper {
/**
* empty private constructor
*/
private ValueHelper() {
}
private static final Map<Integer, Set<Integer>> SUPPORTED_CONVERSIONS = new HashMap<Integer, Set<Integer>>();
static {
SUPPORTED_CONVERSIONS.put(DATE, ImmutableSet.of(STRING, BINARY, DOUBLE, DECIMAL, LONG));
SUPPORTED_CONVERSIONS.put(DOUBLE, ImmutableSet.of(STRING, BINARY, DECIMAL, DATE, LONG));
SUPPORTED_CONVERSIONS.put(DECIMAL, ImmutableSet.of(STRING, BINARY, DOUBLE, DATE, LONG));
SUPPORTED_CONVERSIONS.put(LONG, ImmutableSet.of(STRING, BINARY, DECIMAL, DATE, DOUBLE));
SUPPORTED_CONVERSIONS.put(BOOLEAN, ImmutableSet.of(STRING, BINARY));
SUPPORTED_CONVERSIONS.put(NAME, ImmutableSet.of(STRING, BINARY, PATH, PropertyType.URI));
SUPPORTED_CONVERSIONS.put(PATH, ImmutableSet.of(STRING, BINARY, NAME, PropertyType.URI));
SUPPORTED_CONVERSIONS.put(PropertyType.URI, ImmutableSet.of(STRING, BINARY, NAME, PATH));
SUPPORTED_CONVERSIONS.put(REFERENCE, ImmutableSet.of(STRING, BINARY, WEAKREFERENCE));
SUPPORTED_CONVERSIONS.put(WEAKREFERENCE, ImmutableSet.of(STRING, BINARY, REFERENCE));
}
public static boolean isSupportedConversion(int fromType, int toType) {
if (fromType == toType) {
return true;
} else if (STRING == fromType || BINARY == fromType) {
return true;
} else {
return SUPPORTED_CONVERSIONS.containsKey(fromType) && SUPPORTED_CONVERSIONS.get(fromType).contains(toType);
}
}
public static void checkSupportedConversion(int fromType, int toType) throws ValueFormatException {
if (!isSupportedConversion(fromType, toType)) {
throw new ValueFormatException("Unsupported conversion from '" + PropertyType.nameFromValue(fromType) + "' to '" + PropertyType.nameFromValue(toType) + '\'');
}
}
/**
* @param srcValue
* @param targetType
* @param factory
* @throws ValueFormatException
* @throws IllegalArgumentException
* @see #convert(Value, int, ValueFactory)
*/
public static Value convert(String srcValue, int targetType, ValueFactory factory)
throws ValueFormatException, IllegalArgumentException {
if (srcValue == null) {
return null;
} else {
return factory.createValue(srcValue, targetType);
}
}
/**
* @param srcValue
* @param targetType
* @param factory
* @throws ValueFormatException
* @throws IllegalArgumentException
*/
public static Value convert(InputStream srcValue, int targetType, ValueFactory factory)
throws ValueFormatException, IllegalArgumentException {
if (srcValue == null) {
return null;
} else {
return convert(factory.createValue(srcValue), targetType, factory);
}
}
/**
* Same as {@link #convert(String[], int, ValueFactory)} using
* <code>ValueFactoryImpl</code>.
*
* @param srcValues
* @param targetType
* @throws ValueFormatException
* @throws IllegalArgumentException
* @see #convert(Value, int, ValueFactory)
*/
public static Value[] convert(String[] srcValues, int targetType, ValueFactory factory)
throws ValueFormatException, IllegalArgumentException {
if (srcValues == null) {
return null;
}
Value[] newValues = new Value[srcValues.length];
for (int i = 0; i < srcValues.length; i++) {
newValues[i] = convert(srcValues[i], targetType, factory);
}
return newValues;
}
/**
* @param srcValues
* @param targetType
* @throws ValueFormatException
* @throws IllegalArgumentException
* @see #convert(Value, int, ValueFactory)
*/
public static Value[] convert(InputStream[] srcValues, int targetType,
ValueFactory factory)
throws ValueFormatException, IllegalArgumentException {
if (srcValues == null) {
return null;
}
Value[] newValues = new Value[srcValues.length];
for (int i = 0; i < srcValues.length; i++) {
newValues[i] = convert(srcValues[i], targetType, factory);
}
return newValues;
}
/**
* @param srcValues
* @param targetType
* @param factory
* @throws ValueFormatException
* @throws IllegalArgumentException
* @see #convert(Value, int, ValueFactory)
*/
public static Value[] convert(Value[] srcValues, int targetType,
ValueFactory factory)
throws ValueFormatException, IllegalArgumentException {
if (srcValues == null) {
return null;
}
Value[] newValues = new Value[srcValues.length];
int srcValueType = PropertyType.UNDEFINED;
for (int i = 0; i < srcValues.length; i++) {
if (srcValues[i] == null) {
newValues[i] = null;
continue;
}
// check type of values
if (srcValueType == PropertyType.UNDEFINED) {
srcValueType = srcValues[i].getType();
} else if (srcValueType != srcValues[i].getType()) {
// inhomogeneous types
String msg = "inhomogeneous type of values";
throw new ValueFormatException(msg);
}
newValues[i] = convert(srcValues[i], targetType, factory);
}
return newValues;
}
/**
* Converts the given value to a value of the specified target type.
* The conversion is performed according to the rules described in
* "3.6.4 Property Type Conversion" in the JSR 283 specification.
*
* @param srcValue
* @param targetType
* @param factory
* @throws ValueFormatException
* @throws IllegalStateException
* @throws IllegalArgumentException
*/
public static Value convert(Value srcValue, int targetType, ValueFactory factory)
throws ValueFormatException, IllegalStateException,
IllegalArgumentException {
if (srcValue == null) {
return null;
}
Value val;
int srcType = srcValue.getType();
if (srcType == targetType) {
// no conversion needed, return original value
return srcValue;
}
switch (targetType) {
case PropertyType.STRING:
// convert to STRING
try {
val = factory.createValue(srcValue.getString());
} catch (RepositoryException re) {
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType), re);
}
break;
case PropertyType.BINARY:
// convert to BINARY
try {
val = factory.createValue(srcValue.getBinary());
} catch (RepositoryException re) {
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType), re);
}
break;
case PropertyType.BOOLEAN:
// convert to BOOLEAN
try {
val = factory.createValue(srcValue.getBoolean());
} catch (RepositoryException re) {
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType), re);
}
break;
case PropertyType.DATE:
// convert to DATE
try {
val = factory.createValue(srcValue.getDate());
} catch (RepositoryException re) {
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType), re);
}
break;
case PropertyType.DOUBLE:
// convert to DOUBLE
try {
val = factory.createValue(srcValue.getDouble());
} catch (RepositoryException re) {
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType), re);
}
break;
case PropertyType.LONG:
// convert to LONG
try {
val = factory.createValue(srcValue.getLong());
} catch (RepositoryException re) {
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType), re);
}
break;
case PropertyType.DECIMAL:
// convert to DECIMAL
try {
val = factory.createValue(srcValue.getDecimal());
} catch (RepositoryException re) {
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType), re);
}
break;
case PropertyType.PATH:
// convert to PATH
switch (srcType) {
case PropertyType.PATH:
// no conversion needed, return original value
// (redundant code, just here for the sake of clarity)
return srcValue;
case PropertyType.BINARY:
case PropertyType.STRING:
case PropertyType.NAME: // a name is always also a relative path
// try conversion via string
String path;
try {
// get string value
path = srcValue.getString();
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to PATH value",
re);
}
// the following call will throw ValueFormatException
// if p is not a valid PATH
val = factory.createValue(path, targetType);
break;
case PropertyType.URI:
URI uri;
try {
uri = URI.create(srcValue.getString());
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to PATH value",
re);
}
if (uri.isAbsolute()) {
// uri contains scheme...
throw new ValueFormatException("failed to convert URI value to PATH value");
}
String p = uri.getPath();
if (p.startsWith("./")) {
p = p.substring(2);
}
// the following call will throw ValueFormatException
// if p is not a valid PATH
val = factory.createValue(p, targetType);
break;
case PropertyType.BOOLEAN:
case PropertyType.DATE:
case PropertyType.DOUBLE:
case PropertyType.DECIMAL:
case PropertyType.LONG:
case PropertyType.REFERENCE:
case PropertyType.WEAKREFERENCE:
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType));
default:
throw new IllegalArgumentException("not a valid type constant: " + srcType);
}
break;
case PropertyType.NAME:
// convert to NAME
switch (srcType) {
case PropertyType.NAME:
// no conversion needed, return original value
// (redundant code, just here for the sake of clarity)
return srcValue;
case PropertyType.BINARY:
case PropertyType.STRING:
case PropertyType.PATH: // path might be a name (relative path of length 1)
// try conversion via string
String name;
try {
// get string value
name = srcValue.getString();
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to NAME value",
re);
}
// the following call will throw ValueFormatException
// if p is not a valid NAME
val = factory.createValue(name, targetType);
break;
case PropertyType.URI:
URI uri;
try {
uri = URI.create(srcValue.getString());
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to NAME value",
re);
}
if (uri.isAbsolute()) {
// uri contains scheme...
throw new ValueFormatException("failed to convert URI value to NAME value");
}
String p = uri.getPath();
if (p.startsWith("./")) {
p = p.substring(2);
}
// the following call will throw ValueFormatException
// if p is not a valid NAME
val = factory.createValue(p, targetType);
break;
case PropertyType.BOOLEAN:
case PropertyType.DATE:
case PropertyType.DOUBLE:
case PropertyType.DECIMAL:
case PropertyType.LONG:
case PropertyType.REFERENCE:
case PropertyType.WEAKREFERENCE:
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType));
default:
throw new IllegalArgumentException("not a valid type constant: " + srcType);
}
break;
case PropertyType.REFERENCE:
// convert to REFERENCE
switch (srcType) {
case PropertyType.REFERENCE:
// no conversion needed, return original value
// (redundant code, just here for the sake of clarity)
return srcValue;
case PropertyType.BINARY:
case PropertyType.STRING:
case PropertyType.WEAKREFERENCE:
// try conversion via string
String uuid;
try {
// get string value
uuid = srcValue.getString();
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to REFERENCE value", re);
}
val = factory.createValue(uuid, targetType);
break;
case PropertyType.BOOLEAN:
case PropertyType.DATE:
case PropertyType.DOUBLE:
case PropertyType.LONG:
case PropertyType.DECIMAL:
case PropertyType.PATH:
case PropertyType.URI:
case PropertyType.NAME:
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType));
default:
throw new IllegalArgumentException("not a valid type constant: " + srcType);
}
break;
case PropertyType.WEAKREFERENCE:
// convert to WEAKREFERENCE
switch (srcType) {
case PropertyType.WEAKREFERENCE:
// no conversion needed, return original value
// (redundant code, just here for the sake of clarity)
return srcValue;
case PropertyType.BINARY:
case PropertyType.STRING:
case PropertyType.REFERENCE:
// try conversion via string
String uuid;
try {
// get string value
uuid = srcValue.getString();
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to WEAKREFERENCE value", re);
}
val = factory.createValue(uuid, targetType);
break;
case PropertyType.BOOLEAN:
case PropertyType.DATE:
case PropertyType.DOUBLE:
case PropertyType.LONG:
case PropertyType.DECIMAL:
case PropertyType.URI:
case PropertyType.PATH:
case PropertyType.NAME:
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType));
default:
throw new IllegalArgumentException("not a valid type constant: " + srcType);
}
break;
case PropertyType.URI:
// convert to URI
switch (srcType) {
case PropertyType.URI:
// no conversion needed, return original value
// (redundant code, just here for the sake of clarity)
return srcValue;
case PropertyType.BINARY:
case PropertyType.STRING:
// try conversion via string
String uuid;
try {
// get string value
uuid = srcValue.getString();
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to URI value", re);
}
val = factory.createValue(uuid, targetType);
break;
case PropertyType.NAME:
String name;
try {
// get string value
name = srcValue.getString();
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to URI value", re);
}
// prefix name with "./" (jsr 283 spec 3.6.4.8)
val = factory.createValue("./" + name, targetType);
break;
case PropertyType.PATH:
String path;
try {
// get string value
path = srcValue.getString();
} catch (RepositoryException re) {
// should never happen
throw new ValueFormatException("failed to convert source value to URI value", re);
}
if (!path.startsWith("/")) {
// prefix non-absolute path with "./" (jsr 283 spec 3.6.4.9)
path = "./" + path;
}
val = factory.createValue(path, targetType);
break;
case PropertyType.BOOLEAN:
case PropertyType.DATE:
case PropertyType.DOUBLE:
case PropertyType.LONG:
case PropertyType.DECIMAL:
case PropertyType.REFERENCE:
case PropertyType.WEAKREFERENCE:
throw new ValueFormatException("conversion failed: "
+ PropertyType.nameFromValue(srcType) + " to "
+ PropertyType.nameFromValue(targetType));
default:
throw new IllegalArgumentException("not a valid type constant: " + srcType);
}
break;
default:
throw new IllegalArgumentException("not a valid type constant: " + targetType);
}
return val;
}
/**
*
* @param srcValue
* @param factory
* @throws IllegalStateException
*/
public static Value copy(Value srcValue, ValueFactory factory)
throws IllegalStateException {
if (srcValue == null) {
return null;
}
Value newVal = null;
try {
switch (srcValue.getType()) {
case PropertyType.BINARY:
newVal = factory.createValue(srcValue.getStream());
break;
case PropertyType.BOOLEAN:
newVal = factory.createValue(srcValue.getBoolean());
break;
case PropertyType.DATE:
newVal = factory.createValue(srcValue.getDate());
break;
case PropertyType.DOUBLE:
newVal = factory.createValue(srcValue.getDouble());
break;
case PropertyType.LONG:
newVal = factory.createValue(srcValue.getLong());
break;
case PropertyType.DECIMAL:
newVal = factory.createValue(srcValue.getDecimal());
break;
case PropertyType.PATH:
case PropertyType.NAME:
case PropertyType.REFERENCE:
case PropertyType.WEAKREFERENCE:
case PropertyType.URI:
newVal = factory.createValue(srcValue.getString(), srcValue.getType());
break;
case PropertyType.STRING:
newVal = factory.createValue(srcValue.getString());
break;
}
} catch (RepositoryException re) {
// should never get here
}
return newVal;
}
/**
* @param srcValues
* @param factory
* @throws IllegalStateException
*/
public static Value[] copy(Value[] srcValues, ValueFactory factory)
throws IllegalStateException {
if (srcValues == null) {
return null;
}
Value[] newValues = new Value[srcValues.length];
for (int i = 0; i < srcValues.length; i++) {
newValues[i] = copy(srcValues[i], factory);
}
return newValues;
}
/**
* Serializes the given value to a <code>String</code>. The serialization
* format is the same as used by Document & System View XML, i.e.
* binary values will be Base64-encoded whereas for all others
* <code>{@link Value#getString()}</code> will be used.
*
* @param value the value to be serialized
* @param encodeBlanks if <code>true</code> space characters will be encoded
* as <code>"_x0020_"</code> within he output string.
* @return a string representation of the given value.
* @throws IllegalStateException if the given value is in an illegal state
* @throws RepositoryException if an error occured during the serialization.
*/
public static String serialize(Value value, boolean encodeBlanks)
throws IllegalStateException, RepositoryException {
StringWriter writer = new StringWriter();
try {
serialize(value, encodeBlanks, false, writer);
} catch (IOException ioe) {
throw new RepositoryException("failed to serialize value",
ioe);
}
return writer.toString();
}
/**
* Outputs the serialized value to a <code>Writer</code>. The serialization
* format is the same as used by Document & System View XML, i.e.
* binary values will be Base64-encoded whereas for all others
* <code>{@link Value#getString()}</code> will be used for serialization.
*
* @param value the value to be serialized
* @param encodeBlanks if <code>true</code> space characters will be encoded
* as <code>"_x0020_"</code> within he output string.
* @param enforceBase64 if <code>true</code>, base64 encoding will always be used
* @param writer writer to output the encoded data
* @throws IllegalStateException if the given value is in an illegal state
* @throws IOException if an i/o error occured during the
* serialization
* @throws RepositoryException if an error occured during the serialization.
*/
public static void serialize(Value value, boolean encodeBlanks, boolean enforceBase64,
Writer writer)
throws IllegalStateException, IOException, RepositoryException {
if (value.getType() == PropertyType.BINARY) {
// binary data, base64 encoding required;
// the encodeBlanks flag can be ignored since base64-encoded
// data cannot contain space characters
InputStream in = value.getStream();
try {
Base64.encode(in, writer);
// no need to close StringWriter
//writer.close();
} finally {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
} else {
String textVal = value.getString();
if (enforceBase64) {
byte bytes[] = textVal.getBytes("UTF-8");
Base64.encode(bytes, 0, bytes.length, writer);
}
else {
if (encodeBlanks) {
// enocde blanks in string
textVal = Text.replace(textVal, " ", "_x0020_");
}
writer.write(textVal);
}
}
}
/**
* Deserializes the given string to a <code>Value</code> of the given type.
*
* @param value string to be deserialized
* @param type type of value
* @param decodeBlanks if <code>true</code> <code>"_x0020_"</code>
* character sequences will be decoded to single space
* characters each.
* @param factory ValueFactory used to build the <code>Value</code> object.
* @return the deserialized <code>Value</code>
* @throws ValueFormatException if the string data is not of the required
* format
* @throws RepositoryException if an error occured during the
* deserialization.
*/
public static Value deserialize(String value, int type, boolean decodeBlanks,
ValueFactory factory)
throws ValueFormatException, RepositoryException {
if (type == PropertyType.BINARY) {
// base64 encoded binary value;
// the encodeBlanks flag can be ignored since base64-encoded
// data cannot contain encoded space characters
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
Base64.decode(value, baos);
// no need to close ByteArrayOutputStream
//baos.close();
} catch (IOException ioe) {
throw new RepositoryException("failed to decode binary value",
ioe);
}
// NOTE: for performance reasons the BinaryValue is created directly
// from the byte-array. This is inconsistent with the other calls,
// that delegate the value creation to the ValueFactory.
return new BinaryValue(baos.toByteArray());
} else {
if (decodeBlanks) {
// decode encoded blanks in value
value = Text.replace(value, "_x0020_", " ");
}
return convert(value, type, factory);
}
}
/**
* Deserializes the string data read from the given reader to a
* <code>Value</code> of the given type.
*
* @param reader reader for the string data to be deserialized
* @param type type of value
* @param decodeBlanks if <code>true</code> <code>"_x0020_"</code>
* character sequences will be decoded to single space
* characters each.
* @param factory ValueFactory used to build the <code>Value</code> object.
* @return the deserialized <code>Value</code>
* @throws IOException if an i/o error occured during the
* serialization
* @throws ValueFormatException if the string data is not of the required
* format
* @throws RepositoryException if an error occured during the
* deserialization.
*/
public static Value deserialize(Reader reader, int type,
boolean decodeBlanks, ValueFactory factory)
throws IOException, ValueFormatException, RepositoryException {
if (type == PropertyType.BINARY) {
// base64 encoded binary value;
// the encodeBlanks flag can be ignored since base64-encoded
// data cannot contain encoded space characters
// decode to temp file
TransientFileFactory fileFactory = TransientFileFactory.getInstance();
final File tmpFile = fileFactory.createTransientFile("bin", null, null);
OutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile));
try {
Base64.decode(reader, out);
} finally {
out.close();
}
// create an InputStream that keeps a hard reference to the temp file
// in order to prevent its automatic deletion once the associated
// File object is reclaimed by the garbage collector;
// pass InputStream wrapper to ValueFactory, that creates a BinaryValue.
return factory.createValue(new FilterInputStream(new FileInputStream(tmpFile)) {
public void close() throws IOException {
in.close();
// temp file can now safely be removed
tmpFile.delete();
}
});
/*
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64.decode(reader, baos);
// no need to close ByteArrayOutputStream
//baos.close();
return new BinaryValue(baos.toByteArray());
*/
} else {
char[] chunk = new char[8192];
int read;
StringBuilder buf = new StringBuilder();
while ((read = reader.read(chunk)) > -1) {
buf.append(chunk, 0, read);
}
String value = buf.toString();
if (decodeBlanks) {
// decode encoded blanks in value
value = Text.replace(value, "_x0020_", " ");
}
return convert(value, type, factory);
}
}
/**
* Determine the {@link javax.jcr.PropertyType} of the passed values if all are of
* the same type.
*
* @param values array of values of the same type
* @return {@link javax.jcr.PropertyType#UNDEFINED} if {@code values} is empty,
* {@code values[0].getType()} otherwise.
* @throws javax.jcr.ValueFormatException if not all {@code values} are of the same type
*/
public static int getType(Value[] values) throws ValueFormatException {
int type = UNDEFINED;
for (Value value : values) {
if (value != null) {
if (type == UNDEFINED) {
type = value.getType();
} else if (value.getType() != type) {
throw new ValueFormatException(
"All values of a multi-valued property must be of the same type");
}
}
}
return type;
}
}
| |
// Copyright (C) 2020 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.plugins.codeowners.backend;
import static com.google.common.truth.Truth.assertThat;
import static com.google.gerrit.plugins.codeowners.testing.CodeOwnerSubject.assertThat;
import static com.google.gerrit.plugins.codeowners.testing.OptionalResultWithMessagesSubject.assertThat;
import static com.google.gerrit.testing.GerritJUnit.assertThrows;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.acceptance.TestAccount;
import com.google.gerrit.acceptance.TestMetricMaker;
import com.google.gerrit.acceptance.config.GerritConfig;
import com.google.gerrit.acceptance.testsuite.account.AccountOperations;
import com.google.gerrit.acceptance.testsuite.request.RequestScopeOperations;
import com.google.gerrit.entities.Account;
import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersTest;
import com.google.gerrit.server.ServerInitiated;
import com.google.gerrit.server.account.AccountsUpdate;
import com.google.gerrit.server.account.externalids.ExternalIdFactory;
import com.google.gerrit.server.account.externalids.ExternalIdNotes;
import com.google.gerrit.server.git.meta.MetaDataUpdate;
import com.google.inject.Inject;
import com.google.inject.Key;
import com.google.inject.Provider;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.junit.Before;
import org.junit.Test;
/** Tests for {@link CodeOwnerResolver}. */
public class CodeOwnerResolverTest extends AbstractCodeOwnersTest {
private static final ObjectId TEST_REVISION =
ObjectId.fromString("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef");
@Inject private RequestScopeOperations requestScopeOperations;
@Inject @ServerInitiated private Provider<AccountsUpdate> accountsUpdate;
@Inject private AccountOperations accountOperations;
@Inject private ExternalIdNotes.Factory externalIdNotesFactory;
@Inject private TestMetricMaker testMetricMaker;
@Inject private ExternalIdFactory externalIdFactory;
private Provider<CodeOwnerResolver> codeOwnerResolverProvider;
@Before
public void setUpCodeOwnersPlugin() throws Exception {
codeOwnerResolverProvider =
plugin.getSysInjector().getInstance(new Key<Provider<CodeOwnerResolver>>() {});
}
@Test
public void cannotResolveNullToCodeOwner() throws Exception {
NullPointerException npe =
assertThrows(
NullPointerException.class,
() ->
codeOwnerResolverProvider
.get()
.resolve(/* codeOwnerReference= */ (CodeOwnerReference) null));
assertThat(npe).hasMessageThat().isEqualTo("codeOwnerReference");
npe =
assertThrows(
NullPointerException.class,
() ->
codeOwnerResolverProvider
.get()
.resolve(/* codeOwnerReferences= */ (Set<CodeOwnerReference>) null));
assertThat(npe).hasMessageThat().isEqualTo("codeOwnerReferences");
}
@Test
public void resolveCodeOwnerReferenceForNonExistingEmail() throws Exception {
String nonExistingEmail = "non-existing@example.com";
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(nonExistingEmail));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"cannot resolve code owner email %s: no account with this email exists",
nonExistingEmail));
}
@Test
public void resolveCodeOwnerReferenceForEmail() throws Exception {
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(admin.email()));
assertThat(result.get()).hasAccountIdThat().isEqualTo(admin.id());
assertThat(result)
.hasMessagesThat()
.contains(String.format("account %s is visible to user %s", admin.id(), admin.username()));
}
@Test
public void cannotResolveCodeOwnerReferenceForStarAsEmail() throws Exception {
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(CodeOwnerResolver.ALL_USERS_WILDCARD));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"cannot resolve code owner email %s: no account with this email exists",
CodeOwnerResolver.ALL_USERS_WILDCARD));
}
@Test
public void resolveCodeOwnerReferenceForAmbiguousEmailIfOtherAccountIsInactive()
throws Exception {
// Create an external ID for 'user' account that has the same email as the 'admin' account.
accountsUpdate
.get()
.update(
"Test update",
user.id(),
(a, u) ->
u.addExternalId(
externalIdFactory.create(
"foo", "bar", user.id(), admin.email(), /* hashedPassword= */ null)));
// Deactivate the 'user' account.
accountOperations.account(user.id()).forUpdate().inactive().update();
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(admin.email()));
assertThat(result.get()).hasAccountIdThat().isEqualTo(admin.id());
}
@Test
public void resolveCodeOwnerReferenceForAmbiguousEmail() throws Exception {
// Create an external ID for 'user' account that has the same email as the 'admin' account.
accountsUpdate
.get()
.update(
"Test update",
user.id(),
(a, u) ->
u.addExternalId(
externalIdFactory.create(
"foo", "bar", user.id(), admin.email(), /* hashedPassword= */ null)));
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(admin.email()));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.contains(
String.format("cannot resolve code owner email %s: email is ambiguous", admin.email()));
}
@Test
public void resolveCodeOwnerReferenceForOrphanedEmail() throws Exception {
// Create an external ID with an email for a non-existing account.
String email = "foo.bar@example.com";
Account.Id accountId = Account.id(999999);
try (Repository allUsersRepo = repoManager.openRepository(allUsers);
MetaDataUpdate md = metaDataUpdateFactory.create(allUsers)) {
ExternalIdNotes extIdNotes = externalIdNotesFactory.load(allUsersRepo);
extIdNotes.upsert(externalIdFactory.createEmail(accountId, email));
extIdNotes.commit(md);
}
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider.get().resolveWithMessages(CodeOwnerReference.create(email));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.containsAnyOf(
String.format(
"cannot resolve account %s for email %s: account does not exists",
accountId, email),
String.format(
"cannost resolve code owner email %s: no active account with this email found",
email));
}
@Test
public void resolveCodeOwnerReferenceForInactiveUser() throws Exception {
accountOperations.account(user.id()).forUpdate().inactive().update();
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(user.email()));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.contains(
String.format("ignoring inactive account %s for email %s", user.id(), user.email()));
}
@Test
@GerritConfig(name = "accounts.visibility", value = "SAME_GROUP")
public void resolveCodeOwnerReferenceForNonVisibleAccount() throws Exception {
TestAccount user2 = accountCreator.user2();
// Set user2 as current user.
requestScopeOperations.setApiUser(user2.id());
// user2 cannot see the admin account since they do not share any group and
// "accounts.visibility" is set to "SAME_GROUP".
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(admin.email()));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"cannot resolve code owner email %s: account %s is not visible to user %s",
admin.email(), admin.id(), user2.username()));
}
@Test
public void resolveCodeOwnerReferenceForSecondaryEmail() throws Exception {
TestAccount user2 = accountCreator.user2();
// add secondary email to user account
String secondaryEmail = "user@foo.bar";
accountOperations.account(user.id()).forUpdate().addSecondaryEmail(secondaryEmail).update();
// admin has the "Modify Account" global capability and hence can see the secondary email of the
// user account.
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(secondaryEmail));
assertThat(result.get()).hasAccountIdThat().isEqualTo(user.id());
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"resolved code owner email %s: account %s is referenced by secondary email and the calling user %s can see secondary emails",
secondaryEmail, user.id(), admin.username()));
// admin has the "Modify Account" global capability and hence can see the secondary email of the
// user account if another user is the calling user
requestScopeOperations.setApiUser(user2.id());
result =
codeOwnerResolverProvider
.get()
.forUser(identifiedUserFactory.create(admin.id()))
.resolveWithMessages(CodeOwnerReference.create(secondaryEmail));
assertThat(result.get()).hasAccountIdThat().isEqualTo(user.id());
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"resolved code owner email %s: account %s is referenced by secondary email and user %s can see secondary emails",
secondaryEmail, user.id(), admin.username()));
// user can see its own secondary email.
requestScopeOperations.setApiUser(user.id());
result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(secondaryEmail));
assertThat(result.get()).hasAccountIdThat().isEqualTo(user.id());
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"email %s is visible to the calling user %s: email is a secondary email that is owned by this user",
secondaryEmail, user.username()));
// user can see its own secondary email if another user is the calling user.
requestScopeOperations.setApiUser(user2.id());
result =
codeOwnerResolverProvider
.get()
.forUser(identifiedUserFactory.create(user.id()))
.resolveWithMessages(CodeOwnerReference.create(secondaryEmail));
assertThat(result.get()).hasAccountIdThat().isEqualTo(user.id());
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"email %s is visible to user %s: email is a secondary email that is owned by this user",
secondaryEmail, user.username()));
}
@Test
public void resolveCodeOwnerReferenceForNonVisibleSecondaryEmail() throws Exception {
// add secondary email to admin account
String secondaryEmail = "admin@foo.bar";
accountOperations.account(admin.id()).forUpdate().addSecondaryEmail(secondaryEmail).update();
// user doesn't have the "Modify Account" global capability and hence cannot see the secondary
// email of the admin account.
requestScopeOperations.setApiUser(user.id());
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolverProvider
.get()
.resolveWithMessages(CodeOwnerReference.create(secondaryEmail));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"cannot resolve code owner email %s: account %s is referenced by secondary email but the calling user %s cannot see secondary emails",
secondaryEmail, admin.id(), user.username()));
// user doesn't have the "Modify Account" global capability and hence cannot see the secondary
// email of the admin account if another user is the calling user
requestScopeOperations.setApiUser(admin.id());
result =
codeOwnerResolverProvider
.get()
.forUser(identifiedUserFactory.create(user.id()))
.resolveWithMessages(CodeOwnerReference.create(secondaryEmail));
assertThat(result).isEmpty();
assertThat(result)
.hasMessagesThat()
.contains(
String.format(
"cannot resolve code owner email %s: account %s is referenced by secondary email but user %s cannot see secondary emails",
secondaryEmail, admin.id(), user.username()));
}
@Test
public void resolvePathCodeOwnersForEmptyCodeOwnerConfig() throws Exception {
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.build();
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwners()).isEmpty();
assertThat(result.ownedByAllUsers()).isFalse();
assertThat(result.hasUnresolvedCodeOwners()).isFalse();
}
@Test
public void resolvePathCodeOwners() throws Exception {
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(CodeOwnerSet.createWithoutPathExpressions(admin.email(), user.email()))
.build();
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwnersAccountIds()).containsExactly(admin.id(), user.id());
assertThat(result.ownedByAllUsers()).isFalse();
assertThat(result.hasUnresolvedCodeOwners()).isFalse();
}
@Test
public void resolvePathCodeOwnersWhenStarIsUsedAsEmail() throws Exception {
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(
CodeOwnerSet.createWithoutPathExpressions(CodeOwnerResolver.ALL_USERS_WILDCARD))
.build();
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwnersAccountIds()).isEmpty();
assertThat(result.ownedByAllUsers()).isTrue();
assertThat(result.hasUnresolvedCodeOwners()).isFalse();
}
@Test
public void resolvePathCodeOwnersNonResolvableCodeOwnersAreFilteredOut() throws Exception {
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(
CodeOwnerSet.createWithoutPathExpressions(
admin.email(), "non-existing@example.com"))
.build();
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwnersAccountIds()).containsExactly(admin.id());
assertThat(result.ownedByAllUsers()).isFalse();
assertThat(result.hasUnresolvedCodeOwners()).isTrue();
}
@Test
public void resolvePathCodeOwnersNonResolvableCodeOwnersAreFilteredOutIfOwnedByAllUsers()
throws Exception {
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(
CodeOwnerSet.createWithoutPathExpressions(
"*", admin.email(), "non-existing@example.com"))
.build();
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwnersAccountIds()).containsExactly(admin.id());
assertThat(result.ownedByAllUsers()).isTrue();
assertThat(result.hasUnresolvedCodeOwners()).isTrue();
}
@Test
public void resolvePathCodeOwnersWithAnnotations() throws Exception {
TestAccount user2 = accountCreator.user2();
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(
CodeOwnerSet.builder()
.addCodeOwnerEmail(admin.email())
.addAnnotation(admin.email(), CodeOwnerAnnotation.create("FOO"))
.addAnnotation(admin.email(), CodeOwnerAnnotation.create("BAR"))
.addCodeOwnerEmail(user.email())
.addAnnotation(user.email(), CodeOwnerAnnotation.create("BAZ"))
.addCodeOwnerEmail(user2.email())
.build())
.build();
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwnersAccountIds()).containsExactly(admin.id(), user.id(), user2.id());
assertThat(result.annotations().keySet())
.containsExactly(CodeOwner.create(admin.id()), CodeOwner.create(user.id()));
assertThat(result.annotations().get(CodeOwner.create(admin.id())))
.containsExactly(CodeOwnerAnnotation.create("FOO"), CodeOwnerAnnotation.create("BAR"));
assertThat(result.annotations().get(CodeOwner.create(user.id())))
.containsExactly(CodeOwnerAnnotation.create("BAZ"));
}
@Test
public void resolvePathCodeOwnersWithAnnotations_annotationOnAllUsersWildcard() throws Exception {
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(
CodeOwnerSet.builder()
.addCodeOwnerEmail(admin.email())
.addAnnotation(admin.email(), CodeOwnerAnnotation.create("FOO"))
.addCodeOwnerEmail(CodeOwnerResolver.ALL_USERS_WILDCARD)
.addAnnotation(
CodeOwnerResolver.ALL_USERS_WILDCARD, CodeOwnerAnnotation.create("BAR"))
.addCodeOwnerEmail(user.email())
.build())
.build();
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwnersAccountIds()).containsExactly(admin.id(), user.id());
assertThat(result.annotations().keySet())
.containsExactly(CodeOwner.create(admin.id()), CodeOwner.create(user.id()));
assertThat(result.annotations().get(CodeOwner.create(admin.id())))
.containsExactly(CodeOwnerAnnotation.create("FOO"), CodeOwnerAnnotation.create("BAR"));
assertThat(result.annotations().get(CodeOwner.create(user.id())))
.containsExactly(CodeOwnerAnnotation.create("BAR"));
}
@Test
public void resolvePathCodeOwnersWithAnnotations_annotationOnMultipleEmailsOfTheSameUser()
throws Exception {
// add secondary email to user account
String secondaryEmail = "user@foo.bar";
accountOperations.account(user.id()).forUpdate().addSecondaryEmail(secondaryEmail).update();
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(
CodeOwnerSet.builder()
.addCodeOwnerEmail(user.email())
.addAnnotation(user.email(), CodeOwnerAnnotation.create("FOO"))
.addCodeOwnerEmail(secondaryEmail)
.addAnnotation(secondaryEmail, CodeOwnerAnnotation.create("BAR"))
.build())
.build();
// admin has the "Modify Account" global capability and hence can see the secondary email of the
// user account.
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get("/README.md"));
assertThat(result.codeOwnersAccountIds()).containsExactly(user.id());
assertThat(result.annotations().keySet()).containsExactly(CodeOwner.create(user.id()));
assertThat(result.annotations().get(CodeOwner.create(user.id())))
.containsExactly(CodeOwnerAnnotation.create("FOO"), CodeOwnerAnnotation.create("BAR"));
}
@Test
public void cannotResolvePathCodeOwnersOfNullCodeOwnerConfig() throws Exception {
NullPointerException npe =
assertThrows(
NullPointerException.class,
() ->
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(/* codeOwnerConfig= */ null, Paths.get("/README.md")));
assertThat(npe).hasMessageThat().isEqualTo("codeOwnerConfig");
}
@Test
public void cannotResolvePathCodeOwnersForNullPath() throws Exception {
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(CodeOwnerSet.createWithoutPathExpressions(admin.email()))
.build();
NullPointerException npe =
assertThrows(
NullPointerException.class,
() ->
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, /* absolutePath= */ null));
assertThat(npe).hasMessageThat().isEqualTo("absolutePath");
}
@Test
public void cannotResolvePathCodeOwnersOfNullPathCodeOwners() throws Exception {
NullPointerException npe =
assertThrows(
NullPointerException.class,
() ->
codeOwnerResolverProvider.get().resolvePathCodeOwners(/* pathCodeOwners= */ null));
assertThat(npe).hasMessageThat().isEqualTo("pathCodeOwners");
}
@Test
public void cannotResolvePathCodeOwnersForRelativePath() throws Exception {
String relativePath = "foo/bar.md";
CodeOwnerConfig codeOwnerConfig =
CodeOwnerConfig.builder(CodeOwnerConfig.Key.create(project, "master", "/"), TEST_REVISION)
.addCodeOwnerSet(CodeOwnerSet.createWithoutPathExpressions(admin.email()))
.build();
IllegalStateException npe =
assertThrows(
IllegalStateException.class,
() ->
codeOwnerResolverProvider
.get()
.resolvePathCodeOwners(codeOwnerConfig, Paths.get(relativePath)));
assertThat(npe)
.hasMessageThat()
.isEqualTo(String.format("path %s must be absolute", relativePath));
}
@Test
@GerritConfig(name = "accounts.visibility", value = "SAME_GROUP")
public void nonVisibleCodeOwnerCanBeResolvedIfVisibilityIsNotEnforced() throws Exception {
TestAccount user2 = accountCreator.user2();
// Set user2 as current user.
requestScopeOperations.setApiUser(user2.id());
CodeOwnerReference adminCodeOwnerReference = CodeOwnerReference.create(admin.email());
// user2 cannot see the admin account since they do not share any group and
// "accounts.visibility" is set to "SAME_GROUP".
assertThat(codeOwnerResolverProvider.get().resolve(adminCodeOwnerReference)).isEmpty();
// if visibility is not enforced the code owner reference can be resolved regardless
Optional<CodeOwner> codeOwner =
codeOwnerResolverProvider.get().enforceVisibility(false).resolve(adminCodeOwnerReference);
assertThat(codeOwner).value().hasAccountIdThat().isEqualTo(admin.id());
}
@Test
@GerritConfig(name = "accounts.visibility", value = "SAME_GROUP")
public void codeOwnerVisibilityIsCheckedForGivenAccount() throws Exception {
// Create a new user that is not a member of any group. This means 'user' and 'admin' are not
// visible to this user since they do not share any group.
TestAccount user2 = accountCreator.user2();
// admin is the current user and can see the account
assertThat(codeOwnerResolverProvider.get().resolve(CodeOwnerReference.create(user.email())))
.isPresent();
assertThat(
codeOwnerResolverProvider
.get()
.forUser(identifiedUserFactory.create(admin.id()))
.resolve(CodeOwnerReference.create(user.email())))
.isPresent();
// user2 cannot see the account
assertThat(
codeOwnerResolverProvider
.get()
.forUser(identifiedUserFactory.create(user2.id()))
.resolve(CodeOwnerReference.create(user.email())))
.isEmpty();
}
@Test
@GerritConfig(name = "plugin.code-owners.allowedEmailDomain", value = "example.net")
public void resolveCodeOwnerReferenceForEmailWithNonAllowedEmailDomain() throws Exception {
assertThat(
codeOwnerResolverProvider.get().resolve(CodeOwnerReference.create("foo@example.com")))
.isEmpty();
}
@Test
public void isEmailDomainAllowedRequiresEmailToBeNonNull() throws Exception {
NullPointerException npe =
assertThrows(
NullPointerException.class,
() -> codeOwnerResolverProvider.get().isEmailDomainAllowed(/* email= */ null));
assertThat(npe).hasMessageThat().isEqualTo("email");
}
@Test
@GerritConfig(
name = "plugin.code-owners.allowedEmailDomain",
values = {"example.com", "example.net"})
public void configuredEmailDomainsAreAllowed() throws Exception {
assertIsEmailDomainAllowed(
"foo@example.com", true, "domain example.com of email foo@example.com is allowed");
assertIsEmailDomainAllowed(
"foo@example.net", true, "domain example.net of email foo@example.net is allowed");
assertIsEmailDomainAllowed(
"foo@example.org@example.com",
true,
"domain example.com of email foo@example.org@example.com is allowed");
assertIsEmailDomainAllowed(
"foo@example.org", false, "domain example.org of email foo@example.org is not allowed");
assertIsEmailDomainAllowed("foo", false, "email foo has no domain");
assertIsEmailDomainAllowed(
"foo@example.com@example.org",
false,
"domain example.org of email foo@example.com@example.org is not allowed");
assertIsEmailDomainAllowed(
CodeOwnerResolver.ALL_USERS_WILDCARD, true, "all users wildcard is allowed");
}
@Test
public void allEmailDomainsAreAllowed() throws Exception {
String expectedMessage = "all domains are allowed";
assertIsEmailDomainAllowed("foo@example.com", true, expectedMessage);
assertIsEmailDomainAllowed("foo@example.net", true, expectedMessage);
assertIsEmailDomainAllowed("foo@example.org@example.com", true, expectedMessage);
assertIsEmailDomainAllowed("foo@example.org", true, expectedMessage);
assertIsEmailDomainAllowed("foo", true, expectedMessage);
assertIsEmailDomainAllowed("foo@example.com@example.org", true, expectedMessage);
assertIsEmailDomainAllowed(CodeOwnerResolver.ALL_USERS_WILDCARD, true, expectedMessage);
}
private void assertIsEmailDomainAllowed(
String email, boolean expectedResult, String expectedMessage) {
OptionalResultWithMessages<Boolean> isEmailDomainAllowedResult =
codeOwnerResolverProvider.get().isEmailDomainAllowed(email);
assertThat(isEmailDomainAllowedResult.get()).isEqualTo(expectedResult);
assertThat(isEmailDomainAllowedResult.messages()).containsExactly(expectedMessage);
}
@Test
public void resolveCodeOwnerReferences() throws Exception {
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolve(
ImmutableSet.of(
CodeOwnerReference.create(admin.email()),
CodeOwnerReference.create(user.email())));
assertThat(result.codeOwnersAccountIds()).containsExactly(admin.id(), user.id());
assertThat(result.ownedByAllUsers()).isFalse();
assertThat(result.hasUnresolvedCodeOwners()).isFalse();
}
@Test
public void resolveCodeOwnerReferencesNonResolveableCodeOwnersAreFilteredOut() throws Exception {
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolve(
ImmutableSet.of(
CodeOwnerReference.create(admin.email()),
CodeOwnerReference.create("non-existing@example.com")));
assertThat(result.codeOwnersAccountIds()).containsExactly(admin.id());
assertThat(result.ownedByAllUsers()).isFalse();
assertThat(result.hasUnresolvedCodeOwners()).isTrue();
}
@Test
public void isResolvable() throws Exception {
assertThat(
codeOwnerResolverProvider.get().isResolvable(CodeOwnerReference.create(admin.email())))
.isTrue();
}
@Test
public void isNotResolvable() throws Exception {
assertThat(
codeOwnerResolverProvider
.get()
.isResolvable(CodeOwnerReference.create("unknown@example.com")))
.isFalse();
}
@Test
public void emailIsResolvedOnlyOnce() throws Exception {
testMetricMaker.reset();
CodeOwnerResolver codeOwnerResolver = codeOwnerResolverProvider.get();
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolver.resolveWithMessages(CodeOwnerReference.create(admin.email()));
assertThat(result.get()).hasAccountIdThat().isEqualTo(admin.id());
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_resolutions"))
.isEqualTo(1);
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_cache_reads"))
.isEqualTo(0);
// Doing the same lookup again doesn't resolve the code owner again.
testMetricMaker.reset();
result = codeOwnerResolver.resolveWithMessages(CodeOwnerReference.create(admin.email()));
assertThat(result.get()).hasAccountIdThat().isEqualTo(admin.id());
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_resolutions"))
.isEqualTo(0);
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_cache_reads"))
.isEqualTo(1);
}
@Test
public void nonExistingEmailIsResolvedOnlyOnce() throws Exception {
testMetricMaker.reset();
CodeOwnerResolver codeOwnerResolver = codeOwnerResolverProvider.get();
OptionalResultWithMessages<CodeOwner> result =
codeOwnerResolver.resolveWithMessages(
CodeOwnerReference.create("non-existing@example.com"));
assertThat(result).isEmpty();
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_resolutions"))
.isEqualTo(1);
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_cache_reads"))
.isEqualTo(0);
// Doing the same lookup again doesn't resolve the code owner again.
testMetricMaker.reset();
result =
codeOwnerResolver.resolveWithMessages(
CodeOwnerReference.create("non-existing@example.com"));
assertThat(result).isEmpty();
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_resolutions"))
.isEqualTo(0);
assertThat(testMetricMaker.getCount("plugins/code-owners/count_code_owner_cache_reads"))
.isEqualTo(1);
}
@Test
public void resolveCodeOwnerReferencesThatPointToTheSameAccount() throws Exception {
// add secondary email to user account
String secondaryEmail = "user@foo.bar";
accountOperations.account(user.id()).forUpdate().addSecondaryEmail(secondaryEmail).update();
// admin has the "Modify Account" global capability and hence can see the secondary email of the
// user account.
CodeOwnerResolverResult result =
codeOwnerResolverProvider
.get()
.resolve(
ImmutableSet.of(
CodeOwnerReference.create(user.email()),
CodeOwnerReference.create(secondaryEmail)));
assertThat(result.codeOwnersAccountIds()).containsExactly(user.id());
assertThat(result.ownedByAllUsers()).isFalse();
assertThat(result.hasUnresolvedCodeOwners()).isFalse();
}
}
| |
/*
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.reactivex.netty.protocol.tcp.client.events;
import io.reactivex.netty.events.internal.SafeEventListener;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
final class SafeTcpClientEventListener extends TcpClientEventListener implements SafeEventListener {
private final TcpClientEventListener delegate;
private final AtomicBoolean completed = new AtomicBoolean();
public SafeTcpClientEventListener(TcpClientEventListener delegate) {
this.delegate = delegate;
}
@Override
public void onCompleted() {
if (completed.compareAndSet(false, true)) {
delegate.onCompleted();
}
}
@Override
public void onConnectStart() {
if (!completed.get()) {
delegate.onConnectStart();
}
}
@Override
public void onConnectSuccess(long duration, TimeUnit timeUnit) {
if (!completed.get()) {
delegate.onConnectSuccess(duration, timeUnit);
}
}
@Override
public void onConnectFailed(long duration, TimeUnit timeUnit, Throwable throwable) {
if (!completed.get()) {
delegate.onConnectFailed(duration, timeUnit, throwable);
}
}
@Override
public void onPoolReleaseStart() {
if (!completed.get()) {
delegate.onPoolReleaseStart();
}
}
@Override
public void onPoolReleaseSuccess(long duration, TimeUnit timeUnit) {
if (!completed.get()) {
delegate.onPoolReleaseSuccess(duration, timeUnit);
}
}
@Override
public void onPoolReleaseFailed(long duration, TimeUnit timeUnit,
Throwable throwable) {
if (!completed.get()) {
delegate.onPoolReleaseFailed(duration, timeUnit, throwable);
}
}
@Override
public void onPooledConnectionEviction() {
if (!completed.get()) {
delegate.onPooledConnectionEviction();
}
}
@Override
public void onPooledConnectionReuse() {
if (!completed.get()) {
delegate.onPooledConnectionReuse();
}
}
@Override
public void onPoolAcquireStart() {
if (!completed.get()) {
delegate.onPoolAcquireStart();
}
}
@Override
public void onPoolAcquireSuccess(long duration, TimeUnit timeUnit) {
if (!completed.get()) {
delegate.onPoolAcquireSuccess(duration, timeUnit);
}
}
@Override
public void onPoolAcquireFailed(long duration, TimeUnit timeUnit,
Throwable throwable) {
if (!completed.get()) {
delegate.onPoolAcquireFailed(duration, timeUnit, throwable);
}
}
@Override
public void onByteRead(long bytesRead) {
if (!completed.get()) {
delegate.onByteRead(bytesRead);
}
}
@Override
public void onByteWritten(long bytesWritten) {
if (!completed.get()) {
delegate.onByteWritten(bytesWritten);
}
}
@Override
public void onFlushStart() {
if (!completed.get()) {
delegate.onFlushStart();
}
}
@Override
public void onFlushComplete(long duration, TimeUnit timeUnit) {
if (!completed.get()) {
delegate.onFlushComplete(duration, timeUnit);
}
}
@Override
public void onWriteStart() {
if (!completed.get()) {
delegate.onWriteStart();
}
}
@Override
public void onWriteSuccess(long duration, TimeUnit timeUnit) {
if (!completed.get()) {
delegate.onWriteSuccess(duration, timeUnit);
}
}
@Override
public void onWriteFailed(long duration, TimeUnit timeUnit, Throwable throwable) {
if (!completed.get()) {
delegate.onWriteFailed(duration, timeUnit, throwable);
}
}
@Override
public void onConnectionCloseStart() {
if (!completed.get()) {
delegate.onConnectionCloseStart();
}
}
@Override
public void onConnectionCloseSuccess(long duration, TimeUnit timeUnit) {
if (!completed.get()) {
delegate.onConnectionCloseSuccess(duration, timeUnit);
}
}
@Override
public void onConnectionCloseFailed(long duration, TimeUnit timeUnit,
Throwable throwable) {
if (!completed.get()) {
delegate.onConnectionCloseFailed(duration, timeUnit, throwable);
}
}
@Override
public void onCustomEvent(Object event) {
if (!completed.get()) {
delegate.onCustomEvent(event);
}
}
@Override
public void onCustomEvent(Object event, long duration, TimeUnit timeUnit) {
if (!completed.get()) {
delegate.onCustomEvent(event, duration, timeUnit);
}
}
@Override
public void onCustomEvent(Object event, long duration, TimeUnit timeUnit, Throwable throwable) {
if (!completed.get()) {
delegate.onCustomEvent(event, duration, timeUnit, throwable);
}
}
@Override
public void onCustomEvent(Object event, Throwable throwable) {
if (!completed.get()) {
delegate.onCustomEvent(event, throwable);
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SafeTcpClientEventListener)) {
return false;
}
SafeTcpClientEventListener that = (SafeTcpClientEventListener) o;
return !(delegate != null? !delegate.equals(that.delegate) : that.delegate != null);
}
@Override
public int hashCode() {
return delegate != null? delegate.hashCode() : 0;
}
}
| |
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
*
* Xabber is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.itracker.android.data.connection;
import com.itracker.android.Application;
import com.itracker.android.R;
import com.itracker.android.data.LogManager;
import com.itracker.android.data.account.AccountProtocol;
import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.XMPPConnection;
/**
* Abstract connection.
*
* @author alexander.ivanov
*/
public abstract class ConnectionItem {
/**
* Connection options.
*/
private final ConnectionSettings connectionSettings;
/**
* XMPP connection.
*/
private ConnectionThread connectionThread;
/**
* Connection was requested by user.
*/
private boolean isConnectionRequestedByUser;
/**
* Current state.
*/
private ConnectionState state;
/**
* Whether force reconnection is in progress.
*/
private boolean disconnectionRequested;
/**
* Need to register account on XMPP server.
*/
private boolean registerNewAccount;
public ConnectionItem(AccountProtocol protocol, boolean custom,
String host, int port, String serverName, String userName,
String resource, boolean storePassword, String password,
boolean saslEnabled, TLSMode tlsMode, boolean compression,
ProxyType proxyType, String proxyHost, int proxyPort,
String proxyUser, String proxyPassword) {
connectionSettings = new ConnectionSettings(protocol, userName,
serverName, resource, custom, host, port, password,
saslEnabled, tlsMode, compression, proxyType, proxyHost,
proxyPort, proxyUser, proxyPassword);
isConnectionRequestedByUser = false;
disconnectionRequested = false;
connectionThread = null;
state = ConnectionState.offline;
}
/**
* Register new account on server.
*/
public void registerAccount() {
registerNewAccount = true;
}
/**
* Report if this connection is to register a new account on XMPP server.
*/
public boolean isRegisterAccount() {
return(registerNewAccount);
}
/**
* Gets current connection thread.
*
* @return <code>null</code> if thread doesn't exists.
*/
public ConnectionThread getConnectionThread() {
return connectionThread;
}
/**
* @return connection options.
*/
public ConnectionSettings getConnectionSettings() {
return connectionSettings;
}
public ConnectionState getState() {
return state;
}
/**
* Returns real full jid, that was assigned while login.
*
* @return <code>null</code> if connection is not established.
*/
public String getRealJid() {
ConnectionThread connectionThread = getConnectionThread();
if (connectionThread == null) {
return null;
}
XMPPConnection xmppConnection = connectionThread.getXMPPConnection();
if (xmppConnection == null) {
return null;
}
String user = xmppConnection.getUser();
if (user == null) {
return null;
}
return user;
}
/**
* @param userRequest action was requested by user.
* @return Whether connection is available.
*/
protected boolean isConnectionAvailable(boolean userRequest) {
return true;
}
/**
* Connect or disconnect from server depending on internal flags.
*
* @param userRequest action was requested by user.
* @return Whether state has been changed.
*/
public boolean updateConnection(boolean userRequest) {
boolean available = isConnectionAvailable(userRequest);
if (NetworkManager.getInstance().getState() != NetworkState.available
|| !available || disconnectionRequested) {
ConnectionState target = available ? ConnectionState.waiting : ConnectionState.offline;
if (state == ConnectionState.connected || state == ConnectionState.authentication
|| state == ConnectionState.connecting) {
if (userRequest) {
isConnectionRequestedByUser = false;
}
if (connectionThread != null) {
disconnect(connectionThread);
// Force remove managed connection thread.
onClose(connectionThread);
connectionThread = null;
}
} else if (state == target) {
return false;
}
state = target;
return true;
} else {
if (state == ConnectionState.offline || state == ConnectionState.waiting) {
if (userRequest) {
isConnectionRequestedByUser = true;
}
state = ConnectionState.connecting;
connectionThread = new ConnectionThread(this);
boolean useSRVLookup;
String fullyQualifiedDomainName;
int port;
if (connectionSettings.isCustomHostAndPort()) {
fullyQualifiedDomainName = connectionSettings.getHost();
port = connectionSettings.getPort();
useSRVLookup = false;
} else {
fullyQualifiedDomainName = connectionSettings.getServerName();
port = 5222;
useSRVLookup = true;
}
connectionThread.start(fullyQualifiedDomainName, port, useSRVLookup, registerNewAccount);
return true;
} else {
return false;
}
}
}
/**
* Disconnect and connect using new connection.
*/
public void forceReconnect() {
if (!getState().isConnectable()) {
return;
}
disconnectionRequested = true;
boolean request = isConnectionRequestedByUser;
isConnectionRequestedByUser = false;
updateConnection(false);
isConnectionRequestedByUser = request;
disconnectionRequested = false;
updateConnection(false);
}
/**
* Starts disconnection in another thread.
*/
protected void disconnect(final ConnectionThread connectionThread) {
Thread thread = new Thread("Disconnection thread for " + this) {
@Override
public void run() {
AbstractXMPPConnection xmppConnection = connectionThread.getXMPPConnection();
if (xmppConnection != null)
try {
xmppConnection.disconnect();
} catch (RuntimeException e) {
// connectionClose() in smack can fail.
}
}
};
thread.setPriority(Thread.MIN_PRIORITY);
thread.setDaemon(true);
thread.start();
}
/**
* @param connectionThread
* @return Whether thread is managed by connection.
*/
boolean isManaged(ConnectionThread connectionThread) {
return connectionThread == this.connectionThread;
}
/**
* Update password.
*
* @param password
*/
protected void onPasswordChanged(String password) {
connectionSettings.setPassword(password);
}
/**
* SRV record has been resolved.
*/
protected void onSRVResolved(ConnectionThread connectionThread) {
}
/**
* Invalid certificate has been received.
*/
protected void onInvalidCertificate() {
}
/**
* Connection has been established.
*/
protected void onConnected(ConnectionThread connectionThread) {
if (isRegisterAccount()) {
state = ConnectionState.registration;
} else if (isManaged(connectionThread)) {
state = ConnectionState.authentication;
}
}
/**
* New account has been registered on XMPP server.
*/
protected void onAccountRegistered(ConnectionThread connectionThread) {
registerNewAccount = false;
if (isManaged(connectionThread)) {
state = ConnectionState.authentication;
}
}
/**
* Authorization failed.
*/
protected void onAuthFailed() {
}
/**
* Authorization passed.
*/
protected void onAuthorized(ConnectionThread connectionThread) {
if (isManaged(connectionThread)) {
state = ConnectionState.connected;
}
}
/**
* Called when disconnect should occur.
*
* @param connectionThread
* @return <code>true</code> if connection thread was managed.
*/
private boolean onDisconnect(ConnectionThread connectionThread) {
XMPPConnection xmppConnection = connectionThread.getXMPPConnection();
boolean acceptable = isManaged(connectionThread);
if (xmppConnection == null) {
LogManager.i(this, "onClose " + acceptable);
} else {
LogManager.i(this, "onClose " + xmppConnection.hashCode() + " - "
+ xmppConnection.getConnectionCounter() + ", " + acceptable);
}
ConnectionManager.getInstance().onDisconnect(connectionThread);
if (acceptable) {
connectionThread.shutdown();
}
return acceptable;
}
/**
* Called when connection was closed for some reason.
*/
protected void onClose(ConnectionThread connectionThread) {
if (onDisconnect(connectionThread)) {
state = ConnectionState.waiting;
this.connectionThread = null;
if (isConnectionRequestedByUser) {
Application.getInstance().onError(R.string.CONNECTION_FAILED);
}
isConnectionRequestedByUser = false;
}
}
/**
* Called when another host should be used.
*
* @param connectionThread
* @param fqdn
* @param port
* @param useSrvLookup
*/
protected void onSeeOtherHost(ConnectionThread connectionThread,
String fqdn, int port, boolean useSrvLookup) {
// TODO: Check for number of redirects.
if (onDisconnect(connectionThread)) {
state = ConnectionState.connecting;
this.connectionThread = new ConnectionThread(this);
this.connectionThread.start(fqdn, port, useSrvLookup, registerNewAccount);
}
}
}
| |
package com.viesis.viescraft.client.gui.airship.main;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.input.Keyboard;
import com.viesis.viescraft.api.EnumsVC;
import com.viesis.viescraft.api.GuiVC;
import com.viesis.viescraft.api.References;
import com.viesis.viescraft.api.util.Keybinds;
import com.viesis.viescraft.client.gui.GuiButtonConfirmVC;
import com.viesis.viescraft.client.gui.GuiButtonMenuVC;
import com.viesis.viescraft.common.entity.airshipcolors.EntityAirshipBaseVC;
import com.viesis.viescraft.common.entity.airshipcolors.containers.all.ContainerUpgradeMenu;
import com.viesis.viescraft.init.InitItemsVC;
import com.viesis.viescraft.network.NetworkHandler;
import com.viesis.viescraft.network.server.airship.MessageGuiUpgradeMenu;
import com.viesis.viescraft.network.server.airship.MessageHelperGuiUpgradeBalloonVC;
import com.viesis.viescraft.network.server.airship.MessageHelperGuiUpgradeCoreVC;
import com.viesis.viescraft.network.server.airship.MessageHelperGuiUpgradeEngineVC;
import com.viesis.viescraft.network.server.airship.MessageHelperGuiUpgradeFrameVC;
import com.viesis.viescraft.network.server.airship.main.MessageGuiAirshipMenu;
import com.viesis.viescraft.network.server.airship.main.MessageGuiAirshipMenuMusic;
import com.viesis.viescraft.network.server.airship.main.MessageGuiAirshipMenuStorageGreater;
import com.viesis.viescraft.network.server.airship.main.MessageGuiAirshipMenuStorageLesser;
import com.viesis.viescraft.network.server.airship.main.MessageGuiAirshipMenuStorageNormal;
import com.viesis.viescraft.network.server.airship.main.MessageGuiModuleMenu;
import com.viesis.viescraft.network.server.airship.main.MessageGuiVisualMenu;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
public class GuiUpgradeMenu extends GuiContainer {
private IInventory playerInv;
private EntityAirshipBaseVC airship;
public static int metaUpgradeInfo;
public GuiUpgradeMenu(IInventory playerInv, EntityAirshipBaseVC airshipIn)
{
super(new ContainerUpgradeMenu(playerInv, airshipIn));
this.playerInv = playerInv;
this.airship = airshipIn;
this.xSize = 176;
this.ySize = 202;
}
/**
* Adds the buttons (and other controls) to the screen in question.
*/
@Override
public void initGui()
{
super.initGui();
buttonList.clear();
Keyboard.enableRepeatEvents(true);
GuiVC.buttonM1 = new GuiButtonMenuVC(1, this.guiLeft - 32, this.guiTop + 10, 36, 14, "", 0);
GuiVC.buttonM2 = new GuiButtonMenuVC(2, this.guiLeft - 32, this.guiTop + 24, 36, 14, "", 1);
GuiVC.buttonM3 = new GuiButtonMenuVC(3, this.guiLeft - 32, this.guiTop + 38, 36, 14, "", 2);
GuiVC.buttonM4 = new GuiButtonMenuVC(4, this.guiLeft - 32, this.guiTop + 52, 36, 14, "", 3);
GuiVC.buttonC1 = new GuiButtonConfirmVC(11, this.guiLeft + 24, this.guiTop + 88, 14, 14, "");
GuiVC.buttonC2 = new GuiButtonConfirmVC(12, this.guiLeft + 62, this.guiTop + 88, 14, 14, "");
GuiVC.buttonC3 = new GuiButtonConfirmVC(13, this.guiLeft + 100, this.guiTop + 88, 14, 14, "");
GuiVC.buttonC4 = new GuiButtonConfirmVC(14, this.guiLeft + 138, this.guiTop + 88, 14, 14, "");
this.buttonList.add(GuiVC.buttonM1);
this.buttonList.add(GuiVC.buttonM2);
this.buttonList.add(GuiVC.buttonM3);
this.buttonList.add(GuiVC.buttonM4);
this.buttonList.add(GuiVC.buttonC1);
this.buttonList.add(GuiVC.buttonC2);
this.buttonList.add(GuiVC.buttonC3);
this.buttonList.add(GuiVC.buttonC4);
GuiVC.buttonM2.enabled = false;
}
/**
* Called by the controls from the buttonList when activated. (Mouse pressed for buttons)
*/
@Override
protected void actionPerformed(GuiButton parButton)
{
if (parButton.id == 1)
{
//Lesser Storage
if(this.airship.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_LESSER.getMetadata())
{
NetworkHandler.sendToServer(new MessageGuiAirshipMenuStorageLesser());
}
//Normal Storage
else if(this.airship.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_NORMAL.getMetadata())
{
NetworkHandler.sendToServer(new MessageGuiAirshipMenuStorageNormal());
}
//Greater Storage
else if(this.airship.getModuleVariantSlot1() == EnumsVC.ModuleType.STORAGE_GREATER.getMetadata())
{
NetworkHandler.sendToServer(new MessageGuiAirshipMenuStorageGreater());
}
//Any Music
else if(this.airship.getModuleVariantSlot1() == EnumsVC.ModuleType.MUSIC_LESSER.getMetadata()
|| this.airship.getModuleVariantSlot1() == EnumsVC.ModuleType.MUSIC_NORMAL.getMetadata()
|| this.airship.getModuleVariantSlot1() == EnumsVC.ModuleType.MUSIC_GREATER.getMetadata())
{
NetworkHandler.sendToServer(new MessageGuiAirshipMenuMusic());
}
//Default for airship gui
else
{
NetworkHandler.sendToServer(new MessageGuiAirshipMenu());
}
}
if (parButton.id == 2)
{
NetworkHandler.sendToServer(new MessageGuiUpgradeMenu());
}
if (parButton.id == 3)
{
NetworkHandler.sendToServer(new MessageGuiVisualMenu());
}
if (parButton.id == 4)
{
NetworkHandler.sendToServer(new MessageGuiModuleMenu());
}
this.metaUpgradeInfo = 0;
if (parButton.id == 11)
{
if(this.airship.inventory.getStackInSlot(1) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(1).getMetadata();
if(this.metaUpgradeInfo > this.airship.getMetaTierFrame()
&& this.metaUpgradeInfo == (this.airship.getMetaTierFrame() + 1))
{
NetworkHandler.sendToServer(new MessageHelperGuiUpgradeFrameVC());
}
}
}
if (parButton.id == 12)
{
if(this.airship.inventory.getStackInSlot(2) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(2).getMetadata();
if(this.airship.getMetaTierFrame() > this.airship.getMetaTierCore()
&& this.metaUpgradeInfo > this.airship.getMetaTierCore()
&& this.metaUpgradeInfo == (this.airship.getMetaTierCore() + 1))
{
NetworkHandler.sendToServer(new MessageHelperGuiUpgradeCoreVC());
}
}
}
if (parButton.id == 13)
{
if(this.airship.inventory.getStackInSlot(3) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(3).getMetadata();
if(this.airship.getMetaTierFrame() > this.airship.getMetaTierEngine()
&& this.metaUpgradeInfo > this.airship.getMetaTierEngine()
&& this.metaUpgradeInfo == (this.airship.getMetaTierEngine() + 1))
{
NetworkHandler.sendToServer(new MessageHelperGuiUpgradeEngineVC());
}
}
}
if (parButton.id == 14)
{
if(this.airship.inventory.getStackInSlot(4) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(4).getMetadata();
if(this.airship.getMetaTierFrame() > this.airship.getMetaTierBalloon()
&& this.metaUpgradeInfo > this.airship.getMetaTierBalloon()
&& this.metaUpgradeInfo == (this.airship.getMetaTierBalloon() + 1))
{
NetworkHandler.sendToServer(new MessageHelperGuiUpgradeBalloonVC());
}
}
}
this.buttonList.clear();
this.initGui();
this.updateScreen();
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY)
{
GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
this.mc.getTextureManager().bindTexture(new ResourceLocation(References.MOD_ID + ":" + "textures/gui/container_airship_menu_upgrade.png"));
this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize);
//Draws the checkbox when things are maxed.
if((this.airship.getMetaTierFrame()) >= 5)
{
this.drawTexturedModalRect(this.guiLeft + 23, this.guiTop + 57, 176, 0, 16, 16);
}
else
{
this.drawTexturedModalRect(this.guiLeft + 23, this.guiTop + 83, 176, 16, 16, 20);
}
if((this.airship.getMetaTierCore()) >= 5)
{
this.drawTexturedModalRect(this.guiLeft + 61, this.guiTop + 57, 176, 0, 16, 16);
}
else
{
this.drawTexturedModalRect(this.guiLeft + 61, this.guiTop + 83, 176, 16, 16, 20);
}
if((this.airship.getMetaTierEngine()) >= 5)
{
this.drawTexturedModalRect(this.guiLeft + 99, this.guiTop + 57, 176, 0, 16, 16);
}
else
{
this.drawTexturedModalRect(this.guiLeft + 99, this.guiTop + 83, 176, 16, 16, 20);
}
if((this.airship.getMetaTierBalloon()) >= 5)
{
this.drawTexturedModalRect(this.guiLeft + 137, this.guiTop + 57, 176, 0, 16, 16);
}
else
{
this.drawTexturedModalRect(this.guiLeft + 137, this.guiTop + 83, 176, 16, 16, 20);
}
//Draws the top menu texture extension for the label
this.drawRect(this.guiLeft + 49-4, this.guiTop - 17, this.guiLeft + 127+4, this.guiTop, Color.BLACK.getRGB());
this.drawRect(this.guiLeft + 50-4, this.guiTop - 16, this.guiLeft + 126+4, this.guiTop, Color.LIGHT_GRAY.getRGB());
this.drawRect(this.guiLeft + 52-4, this.guiTop - 14, this.guiLeft + 124+4, this.guiTop, Color.BLACK.getRGB());
//Disable/hides all button on default
GuiVC.buttonC1.enabled = false;
GuiVC.buttonC2.enabled = false;
GuiVC.buttonC3.enabled = false;
GuiVC.buttonC4.enabled = false;
GuiVC.buttonC1.visible = false;
GuiVC.buttonC2.visible = false;
GuiVC.buttonC3.visible = false;
GuiVC.buttonC4.visible = false;
//Enables a button if the conditions are right
if(this.airship.inventory.getStackInSlot(1) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(1).getMetadata();
if(this.metaUpgradeInfo > this.airship.getMetaTierFrame()
&& this.metaUpgradeInfo == (this.airship.getMetaTierFrame() + 1))
{
GuiVC.buttonC1.enabled = true;
GuiVC.buttonC1.visible = true;
}
}
if(this.airship.inventory.getStackInSlot(2) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(2).getMetadata();
if(this.airship.getMetaTierFrame() > this.airship.getMetaTierCore()
&& this.metaUpgradeInfo > this.airship.getMetaTierCore()
&& this.metaUpgradeInfo == (this.airship.getMetaTierCore() + 1))
{
GuiVC.buttonC2.enabled = true;
GuiVC.buttonC2.visible = true;
}
}
if(this.airship.inventory.getStackInSlot(3) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(3).getMetadata();
if(this.airship.getMetaTierFrame() > this.airship.getMetaTierEngine()
&& this.metaUpgradeInfo > this.airship.getMetaTierEngine()
&& this.metaUpgradeInfo == (this.airship.getMetaTierEngine() + 1))
{
GuiVC.buttonC3.enabled = true;
GuiVC.buttonC3.visible = true;
}
}
if(this.airship.inventory.getStackInSlot(4) != null)
{
this.metaUpgradeInfo = this.airship.inventory.getStackInSlot(4).getMetadata();
if(this.airship.getMetaTierFrame() > this.airship.getMetaTierBalloon()
&& this.metaUpgradeInfo > this.airship.getMetaTierBalloon()
&& this.metaUpgradeInfo == (this.airship.getMetaTierBalloon() + 1))
{
GuiVC.buttonC4.enabled = true;
GuiVC.buttonC4.visible = true;
}
}
//Hides the button if airship is maxed
if(this.airship.getMetaTierFrame() >= 5)
{
GuiVC.buttonC1.visible = false;
}
if(this.airship.getMetaTierCore() >= 5)
{
GuiVC.buttonC2.visible = false;
}
if(this.airship.getMetaTierEngine() >= 5)
{
GuiVC.buttonC3.visible = false;
}
if(this.airship.getMetaTierBalloon() >= 5)
{
GuiVC.buttonC4.visible = false;
}
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY)
{
this.fontRendererObj.drawString("Upgrade Menu", 53, -10, 65535);
//Frame
GlStateManager.pushMatrix();
{
GlStateManager.translate(20, 22.2, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRendererObj.drawString("Frame", 0, 0, 16777215);
}
GlStateManager.popMatrix();
if(this.airship.getMetaTierFrame() > 0)
{
GlStateManager.pushMatrix();
{
GlStateManager.translate(21, 32, 0);
GlStateManager.scale(1.25, 1.25, 1.25);
this.drawItemStack(new ItemStack(InitItemsVC.upgrade_frame, 1, this.airship.getMetaTierFrame()), 0, 0, "");
}
GlStateManager.popMatrix();
}
//Core
GlStateManager.pushMatrix();
{
GlStateManager.translate(60, 22.2, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRendererObj.drawString("Core", 0, 0, 16777215);
}
GlStateManager.popMatrix();
if(this.airship.getMetaTierCore() > 0)
{
GlStateManager.pushMatrix();
{
GlStateManager.translate(59, 32, 0);
GlStateManager.scale(1.25, 1.25, 1.25);
this.drawItemStack(new ItemStack(InitItemsVC.upgrade_core, 1, this.airship.getMetaTierCore()), 0, 0, "");
}
GlStateManager.popMatrix();
}
//Engine
GlStateManager.pushMatrix();
{
GlStateManager.translate(95.5, 22.2, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRendererObj.drawString("Engine", 0, 0, 16777215);
}
GlStateManager.popMatrix();
if(this.airship.getMetaTierEngine() > 0)
{
GlStateManager.pushMatrix();
{
GlStateManager.translate(97, 32, 0);
GlStateManager.scale(1.25, 1.25, 1.25);
this.drawItemStack(new ItemStack(InitItemsVC.upgrade_engine, 1, this.airship.getMetaTierEngine()), 0, 0, "");
}
GlStateManager.popMatrix();
}
//Balloon
GlStateManager.pushMatrix();
{
GlStateManager.translate(132, 22.2, 0);
GlStateManager.scale(0.75, 0.75, 0.75);
this.fontRendererObj.drawString("Balloon", 0, 0, 16777215);
}
GlStateManager.popMatrix();
if(this.airship.getMetaTierBalloon() > 0)
{
GlStateManager.pushMatrix();
{
GlStateManager.translate(135, 32, 0);
GlStateManager.scale(1.25, 1.25, 1.25);
this.drawItemStack(new ItemStack(InitItemsVC.upgrade_balloon, 1, this.airship.getMetaTierBalloon()), 0, 0, "");
}
GlStateManager.popMatrix();
}
int tooltipFrameX = 22;
int tooltipFrameY = 33;
//Logic for mouse-over Frame tooltip
if(mouseX >= this.guiLeft + tooltipFrameX + 0 && mouseX <= this.guiLeft + tooltipFrameX + 17
&& mouseY >= this.guiTop + tooltipFrameY + 0 && mouseY <= this.guiTop + tooltipFrameY + 17)
{
List<String> text = new ArrayList<String>();
text.add(TextFormatting.LIGHT_PURPLE + "Frame affects the Core, Engine,");
text.add(TextFormatting.LIGHT_PURPLE + "and Balloon tier upgrades that");
text.add(TextFormatting.LIGHT_PURPLE + "can be applied.");
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 10, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
//Logic for mouse-over Core tooltip
if(mouseX >= this.guiLeft + tooltipFrameX + 38 + 0 && mouseX <= this.guiLeft + tooltipFrameX + 38 + 17
&& mouseY >= this.guiTop + tooltipFrameY + 0 && mouseY <= this.guiTop + tooltipFrameY + 17)
{
List<String> text = new ArrayList<String>();
text.add(TextFormatting.LIGHT_PURPLE + "Core affects an airship's");
text.add(TextFormatting.LIGHT_PURPLE + "base speed.");
text.add(TextFormatting.LIGHT_PURPLE + "");
text.add(TextFormatting.WHITE + "Base bonus: " + TextFormatting.GREEN + "+" + this.airship.metaTierCore);
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 15, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
//Logic for mouse-over Engine tooltip
if(mouseX >= this.guiLeft + tooltipFrameX + 76 + 0 && mouseX <= this.guiLeft + tooltipFrameX + 76 + 17
&& mouseY >= this.guiTop + tooltipFrameY + 0 && mouseY <= this.guiTop + tooltipFrameY + 17)
{
List<String> text = new ArrayList<String>();
text.add(TextFormatting.LIGHT_PURPLE + "Engine affects an airship's");
text.add(TextFormatting.LIGHT_PURPLE + "fuel efficiency.");
text.add(TextFormatting.LIGHT_PURPLE + "");
text.add(TextFormatting.WHITE + "Base bonus: " + TextFormatting.RED + "-" + (EnumsVC.AirshipTierEngine.byId(this.airship.metaTierEngine).getFuelPerTick()));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 15, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
//Logic for mouse-over Balloon tooltip
if(mouseX >= this.guiLeft + tooltipFrameX + 114 + 0 && mouseX <= this.guiLeft + tooltipFrameX + 114 + 17
&& mouseY >= this.guiTop + tooltipFrameY + 0 && mouseY <= this.guiTop + tooltipFrameY + 17)
{
List<String> text = new ArrayList<String>();
text.add(TextFormatting.LIGHT_PURPLE + "Balloon affects an airship's");
text.add(TextFormatting.LIGHT_PURPLE + "maximum elevation.");
text.add(TextFormatting.LIGHT_PURPLE + "");
text.add(TextFormatting.WHITE + "Base bonus: " + TextFormatting.GREEN + (EnumsVC.AirshipTierBalloon.byId(this.airship.metaTierCore).getMaxAltitude()));
FontRenderer fontrenderer = this.getFontRenderer();
GlStateManager.pushMatrix();
{
GlStateManager.translate(mouseX - this.guiLeft - 42, mouseY - this.guiTop - 15, 0);
GlStateManager.scale(0.5, 0.5, 0.5);
this.drawHoveringText(text, 0, 0);
}
GlStateManager.popMatrix();
}
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException
{
if (keyCode == 1
|| keyCode == Keybinds.vcInventory.getKeyCode()
|| this.mc.gameSettings.keyBindInventory.isActiveAndMatches(keyCode))
{
this.mc.thePlayer.closeScreen();
}
}
@Override
public void updateScreen()
{
super.updateScreen();
if (!this.mc.thePlayer.isEntityAlive() || this.mc.thePlayer.isDead
|| !this.mc.thePlayer.isRiding())
{
this.mc.thePlayer.closeScreen();
}
}
/**
* Draws an ItemStack.
*/
private void drawItemStack(ItemStack stack, int x, int y, String altText)
{
GlStateManager.translate(0.0F, 0.0F, 32.0F);
this.zLevel = 200.0F;
this.itemRender.zLevel = 200.0F;
net.minecraft.client.gui.FontRenderer font = stack.getItem().getFontRenderer(stack);
if (font == null) font = fontRendererObj;
this.itemRender.renderItemAndEffectIntoGUI(stack, x, y);
this.zLevel = 0.0F;
this.itemRender.zLevel = 0.0F;
}
public FontRenderer getFontRenderer()
{
return this.mc.fontRendererObj;
}
}
| |
/* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.connectorcommon.throttler;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.connectorcommon.interfaces.*;
import java.util.*;
import java.util.concurrent.atomic.*;
/** A Throttler object creates a virtual pool of connections to resources
* whose access needs to be throttled in number, rate of use, and byte rate.
* This code is modeled on the code for distributed connection pools, and is intended
* to work in a similar manner. Basically, a periodic assessment is done about what the
* local throttling parameters should be (on a per-pool basis), and the local throttling
* activities then adjust what they are doing based on the new parameters. A service
* model is used to keep track of which pools have what clients working with them.
* This implementation has the advantage that:
* (1) Only local throttling ever takes place on a method-by-method basis, which makes
* it possible to use throttling even in streams and background threads;
* (2) Throttling resources are apportioned fairly, on average, between all the various
* cluster members, so it is unlikely that any persistent starvation conditions can
* arise.
*/
public class Throttler
{
public static final String _rcsid = "@(#)$Id$";
/** Throttle group hash table. Keyed by throttle group type, value is throttling groups */
protected final Map<String,ThrottlingGroups> throttleGroupsHash = new HashMap<String,ThrottlingGroups>();
/** Create a throttler instance. Usually there will be one of these per connector
* type that needs throttling.
*/
public Throttler()
{
}
// There are a lot of synchronizers to coordinate here. They are indeed hierarchical. It is not possible to simply
// throw a synchronizer at every level, and require that we hold all of them, because when we wait somewhere in the
// inner level, we will continue to hold locks and block access to all the outer levels.
//
// Instead, I've opted for a model whereby individual resources are protected. This is tricky to coordinate, though,
// because (for instance) after a resource has been removed from the hash table, it had better be cleaned up
// thoroughly before the outer lock is removed, or two versions of the resource might wind up coming into existence.
// The general rule is therefore:
// (1) Creation or deletion of resources involves locking the parent where the resource is being added or removed
// (2) Anything that waits CANNOT also add or remove.
/** Get all existing throttle groups for a throttle group type.
* The throttle group type typically describes a connector class, while the throttle group represents
* a namespace of bin names specific to that connector class.
*@param throttleGroupType is the throttle group type.
*@return the set of throttle groups for that group type.
*/
public Set<String> getThrottleGroups(IThreadContext threadContext, String throttleGroupType)
throws ManifoldCFException
{
synchronized (throttleGroupsHash)
{
return throttleGroupsHash.keySet();
}
}
/** Remove a throttle group.
*@param throttleGroupType is the throttle group type.
*@param throttleGroup is the throttle group.
*/
public void removeThrottleGroup(IThreadContext threadContext, String throttleGroupType, String throttleGroup)
throws ManifoldCFException
{
// Removal. Lock the whole hierarchy.
synchronized (throttleGroupsHash)
{
ThrottlingGroups tg = throttleGroupsHash.get(throttleGroupType);
if (tg != null)
{
tg.removeThrottleGroup(threadContext, throttleGroup);
}
}
}
/** Set or update throttle specification for a throttle group. This creates the
* throttle group if it does not yet exist.
*@param throttleGroupType is the throttle group type.
*@param throttleGroup is the throttle group.
*@param throttleSpec is the desired throttle specification object.
*/
public void createOrUpdateThrottleGroup(IThreadContext threadContext, String throttleGroupType, String throttleGroup, IThrottleSpec throttleSpec)
throws ManifoldCFException
{
// Potential addition. Lock the whole hierarchy.
synchronized (throttleGroupsHash)
{
ThrottlingGroups tg = throttleGroupsHash.get(throttleGroupType);
if (tg == null)
{
tg = new ThrottlingGroups(throttleGroupType);
throttleGroupsHash.put(throttleGroupType, tg);
}
tg.createOrUpdateThrottleGroup(threadContext, throttleGroup, throttleSpec);
}
}
/** Construct connection throttler for connections with specific bin names. This object is meant to be embedded with a connection
* pool of similar objects, and used to gate the creation of new connections in that pool.
*@param throttleGroupType is the throttle group type.
*@param throttleGroup is the throttle group.
*@param binNames are the connection type bin names.
*@return the connection throttling object, or null if the pool is being shut down.
*/
public IConnectionThrottler obtainConnectionThrottler(IThreadContext threadContext, String throttleGroupType, String throttleGroup, String[] binNames)
throws ManifoldCFException
{
// No waiting, so lock the entire tree.
synchronized (throttleGroupsHash)
{
ThrottlingGroups tg = throttleGroupsHash.get(throttleGroupType);
if (tg != null)
return tg.obtainConnectionThrottler(threadContext, throttleGroup, binNames);
return null;
}
}
/** Poll periodically.
*/
public void poll(IThreadContext threadContext, String throttleGroupType)
throws ManifoldCFException
{
// No waiting, so lock the entire tree.
synchronized (throttleGroupsHash)
{
ThrottlingGroups tg = throttleGroupsHash.get(throttleGroupType);
if (tg != null)
tg.poll(threadContext);
}
}
/** Poll ALL bins periodically.
*/
public void poll(IThreadContext threadContext)
throws ManifoldCFException
{
// No waiting, so lock the entire tree.
synchronized (throttleGroupsHash)
{
for (ThrottlingGroups tg : throttleGroupsHash.values())
{
tg.poll(threadContext);
}
}
}
/** Free unused resources.
*/
public void freeUnusedResources(IThreadContext threadContext)
throws ManifoldCFException
{
// This potentially affects the entire hierarchy.
// Go through the whole pool and clean it out
synchronized (throttleGroupsHash)
{
Iterator<ThrottlingGroups> iter = throttleGroupsHash.values().iterator();
while (iter.hasNext())
{
ThrottlingGroups p = iter.next();
p.freeUnusedResources(threadContext);
}
}
}
/** Shut down all throttlers and deregister them.
*/
public void destroy(IThreadContext threadContext)
throws ManifoldCFException
{
// This affects the entire hierarchy, so lock the whole thing.
// Go through the whole pool and clean it out
synchronized (throttleGroupsHash)
{
Iterator<ThrottlingGroups> iter = throttleGroupsHash.values().iterator();
while (iter.hasNext())
{
ThrottlingGroups p = iter.next();
p.destroy(threadContext);
iter.remove();
}
}
}
// Protected methods and classes
protected static String buildThrottlingGroupName(String throttlingGroupType, String throttlingGroupName)
{
return throttlingGroupType + "_" + throttlingGroupName;
}
/** This class represents a throttling group pool */
protected class ThrottlingGroups
{
/** The throttling group type for this throttling group pool */
protected final String throttlingGroupTypeName;
/** The pool of individual throttle group services for this pool, keyed by throttle group name */
protected final Map<String,ThrottlingGroup> groups = new HashMap<String,ThrottlingGroup>();
public ThrottlingGroups(String throttlingGroupTypeName)
{
this.throttlingGroupTypeName = throttlingGroupTypeName;
}
/** Update throttle specification */
public void createOrUpdateThrottleGroup(IThreadContext threadContext, String throttleGroup, IThrottleSpec throttleSpec)
throws ManifoldCFException
{
synchronized (groups)
{
ThrottlingGroup g = groups.get(throttleGroup);
if (g == null)
{
g = new ThrottlingGroup(threadContext, throttlingGroupTypeName, throttleGroup, throttleSpec);
groups.put(throttleGroup, g);
}
else
{
g.updateThrottleSpecification(throttleSpec);
}
}
}
/** Obtain connection throttler.
*@return the throttler, or null of the hierarchy has changed.
*/
public IConnectionThrottler obtainConnectionThrottler(IThreadContext threadContext, String throttleGroup, String[] binNames)
throws ManifoldCFException
{
synchronized (groups)
{
ThrottlingGroup g = groups.get(throttleGroup);
if (g == null)
return null;
return g.obtainConnectionThrottler(threadContext, binNames);
}
}
/** Remove specified throttle group */
public void removeThrottleGroup(IThreadContext threadContext, String throttleGroup)
throws ManifoldCFException
{
// Must synch the whole thing, because otherwise there would be a risk of someone recreating the
// group right after we removed it from the map, and before we destroyed it.
synchronized (groups)
{
ThrottlingGroup g = groups.remove(throttleGroup);
if (g != null)
{
g.destroy(threadContext);
}
}
}
/** Poll this set of throttle groups.
*/
public void poll(IThreadContext threadContext)
throws ManifoldCFException
{
synchronized (groups)
{
Iterator<String> iter = groups.keySet().iterator();
while (iter.hasNext())
{
String throttleGroup = iter.next();
ThrottlingGroup p = groups.get(throttleGroup);
p.poll(threadContext);
}
}
}
/** Free unused resources */
public void freeUnusedResources(IThreadContext threadContext)
throws ManifoldCFException
{
synchronized (groups)
{
Iterator<ThrottlingGroup> iter = groups.values().iterator();
while (iter.hasNext())
{
ThrottlingGroup g = iter.next();
g.freeUnusedResources(threadContext);
}
}
}
/** Destroy and shutdown all */
public void destroy(IThreadContext threadContext)
throws ManifoldCFException
{
synchronized (groups)
{
Iterator<ThrottlingGroup> iter = groups.values().iterator();
while (iter.hasNext())
{
ThrottlingGroup p = iter.next();
p.destroy(threadContext);
iter.remove();
}
}
}
}
/** This class represents a throttling group, of a specific throttling group type. It basically
* describes an entire self-consistent throttling environment.
*/
protected class ThrottlingGroup
{
/** The throttling group name */
protected final String throttlingGroupName;
/** The current throttle spec */
protected IThrottleSpec throttleSpec;
/** The connection bins */
protected final Map<String,ConnectionBin> connectionBins = new HashMap<String,ConnectionBin>();
/** The fetch bins */
protected final Map<String,FetchBin> fetchBins = new HashMap<String,FetchBin>();
/** The throttle bins */
protected final Map<String,ThrottleBin> throttleBins = new HashMap<String,ThrottleBin>();
// For synchronization, we use several in this class.
// Modification to the connectionBins, fetchBins, or throttleBins hashes uses the appropriate local synchronizer.
// Changes to other local variables use the main synchronizer.
/** Constructor
*/
public ThrottlingGroup(IThreadContext threadContext, String throttlingGroupType, String throttleGroup, IThrottleSpec throttleSpec)
throws ManifoldCFException
{
this.throttlingGroupName = buildThrottlingGroupName(throttlingGroupType, throttleGroup);
this.throttleSpec = throttleSpec;
// Once all that is done, perform the initial setting of all the bin cutoffs
poll(threadContext);
}
/** Create a bunch of bins, corresponding to the bin names specified.
* Note that this also registers them as services etc.
*@param binNames describes the set of bins to create.
*/
public synchronized IConnectionThrottler obtainConnectionThrottler(IThreadContext threadContext, String[] binNames)
throws ManifoldCFException
{
synchronized (connectionBins)
{
for (String binName : binNames)
{
ConnectionBin bin = connectionBins.get(binName);
if (bin == null)
{
bin = new ConnectionBin(threadContext, throttlingGroupName, binName);
connectionBins.put(binName, bin);
}
}
}
synchronized (fetchBins)
{
for (String binName : binNames)
{
FetchBin bin = fetchBins.get(binName);
if (bin == null)
{
bin = new FetchBin(threadContext, throttlingGroupName, binName);
fetchBins.put(binName, bin);
}
}
}
synchronized (throttleBins)
{
for (String binName : binNames)
{
ThrottleBin bin = throttleBins.get(binName);
if (bin == null)
{
bin = new ThrottleBin(threadContext, throttlingGroupName, binName);
throttleBins.put(binName, bin);
}
}
}
return new ConnectionThrottler(this, binNames);
}
/** Update the throttle spec.
*@param throttleSpec is the new throttle spec for this throttle group.
*/
public synchronized void updateThrottleSpecification(IThrottleSpec throttleSpec)
throws ManifoldCFException
{
this.throttleSpec = throttleSpec;
}
// IConnectionThrottler support methods
/** Wait for a connection to become available.
*@param poolCount is a description of how many connections
* are available in the current pool, across all bins.
*@return the IConnectionThrottler codes for results.
*/
public int waitConnectionAvailable(String[] binNames, AtomicInteger[] poolCounts, IBreakCheck breakCheck)
throws InterruptedException, BreakException
{
// Each bin can signal something different. Bins that signal
// CONNECTION_FROM_NOWHERE are shutting down, but there's also
// apparently the conflicting possibilities of distinct answers of
// CONNECTION_FROM_POOL and CONNECTION_FROM_CREATION.
// However: the pool count we track is in fact N * the actual pool count,
// where N is the number of bins in each connection. This means that a conflict
// is ALWAYS due to two entities simultaneously calling waitConnectionAvailable(),
// and deadlocking each other. The solution is therefore to back off and retry.
// This is the retry loop
while (true)
{
int currentRecommendation = IConnectionThrottler.CONNECTION_FROM_NOWHERE;
boolean retry = false;
// First, make sure all the bins exist, and reserve a slot in each
int i = 0;
while (i < binNames.length)
{
String binName = binNames[i];
ConnectionBin bin;
synchronized (connectionBins)
{
bin = connectionBins.get(binName);
}
if (bin != null)
{
// Reserve a slot
int result;
try
{
result = bin.waitConnectionAvailable(poolCounts[i],breakCheck);
}
catch (Throwable e)
{
while (i > 0)
{
i--;
binName = binNames[i];
synchronized (connectionBins)
{
bin = connectionBins.get(binName);
}
if (bin != null)
bin.undoReservation(currentRecommendation, poolCounts[i]);
}
if (e instanceof BreakException)
throw (BreakException)e;
if (e instanceof InterruptedException)
throw (InterruptedException)e;
if (e instanceof Error)
throw (Error)e;
if (e instanceof RuntimeException)
throw (RuntimeException)e;
throw new RuntimeException("Unexpected exception of type '"+e.getClass().getName()+"': "+e.getMessage(),e);
}
if (result == IConnectionThrottler.CONNECTION_FROM_NOWHERE)
{
// Release previous reservations, and either return, or retry
while (i > 0)
{
i--;
binName = binNames[i];
synchronized (connectionBins)
{
bin = connectionBins.get(binName);
}
if (bin != null)
bin.undoReservation(currentRecommendation, poolCounts[i]);
}
return result;
}
if (currentRecommendation != IConnectionThrottler.CONNECTION_FROM_NOWHERE && currentRecommendation != result)
{
// Release all previous reservations, including this one, and either return, or retry
bin.undoReservation(result, poolCounts[i]);
while (i > 0)
{
i--;
binName = binNames[i];
synchronized (connectionBins)
{
bin = connectionBins.get(binName);
}
if (bin != null)
bin.undoReservation(currentRecommendation, poolCounts[i]);
}
// Break out of the outer loop so we can retry
retry = true;
break;
}
if (currentRecommendation == IConnectionThrottler.CONNECTION_FROM_NOWHERE)
currentRecommendation = result;
}
i++;
}
if (retry)
continue;
// Complete the reservation process (if that is what we decided)
if (currentRecommendation == IConnectionThrottler.CONNECTION_FROM_CREATION)
{
// All reservations have been made! Convert them.
for (String binName : binNames)
{
ConnectionBin bin;
synchronized (connectionBins)
{
bin = connectionBins.get(binName);
}
if (bin != null)
bin.noteConnectionCreation();
}
}
return currentRecommendation;
}
}
public IFetchThrottler getNewConnectionFetchThrottler(String[] binNames)
{
return new FetchThrottler(this, binNames);
}
public boolean noteReturnedConnection(String[] binNames)
{
// If ANY of the bins think the connection should be destroyed, then that will be
// the recommendation.
synchronized (connectionBins)
{
boolean destroyConnection = false;
for (String binName : binNames)
{
ConnectionBin bin = connectionBins.get(binName);
if (bin != null)
{
destroyConnection |= bin.shouldReturnedConnectionBeDestroyed();
}
}
return destroyConnection;
}
}
public boolean checkDestroyPooledConnection(String[] binNames, AtomicInteger[] poolCounts)
{
// Only if all believe we can destroy a pool connection, will we do it.
// This is because some pools may be empty, etc.
synchronized (connectionBins)
{
boolean destroyConnection = false;
int i = 0;
while (i < binNames.length)
{
String binName = binNames[i];
ConnectionBin bin = connectionBins.get(binName);
if (bin != null)
{
int result = bin.shouldPooledConnectionBeDestroyed(poolCounts[i]);
if (result == ConnectionBin.CONNECTION_POOLEMPTY)
{
// Give up now, and undo all the other bins
while (i > 0)
{
i--;
binName = binNames[i];
bin = connectionBins.get(binName);
bin.undoPooledConnectionDecision(poolCounts[i]);
}
return false;
}
else if (result == ConnectionBin.CONNECTION_DESTROY)
{
destroyConnection = true;
}
}
i++;
}
if (destroyConnection)
return true;
// Undo pool reservation, since everything is apparently within bounds.
for (int j = 0; j < binNames.length; j++)
{
ConnectionBin bin = connectionBins.get(binNames[j]);
if (bin != null)
bin.undoPooledConnectionDecision(poolCounts[j]);
}
return false;
}
}
/** Connection expiration is tricky, because even though a connection may be identified as
* being expired, at the very same moment it could be handed out in another thread. So there
* is a natural race condition present.
* The way the connection throttler deals with that is to allow the caller to reserve a connection
* for expiration. This must be called BEFORE the actual identified connection is removed from the
* connection pool. If the value returned by this method is "true", then a connection MUST be removed
* from the pool and destroyed, whether or not the identified connection is actually still available for
* destruction or not.
*@return true if a connection from the pool can be expired. If true is returned, noteConnectionDestruction()
* MUST be called once the connection has actually been destroyed.
*/
public boolean checkExpireConnection(String[] binNames, AtomicInteger[] poolCounts)
{
synchronized (connectionBins)
{
int i = 0;
while (i < binNames.length)
{
String binName = binNames[i];
ConnectionBin bin = connectionBins.get(binName);
if (bin != null)
{
if (!bin.hasPooledConnection(poolCounts[i]))
{
// Give up now, and undo all the other bins
while (i > 0)
{
i--;
binName = binNames[i];
bin = connectionBins.get(binName);
bin.undoPooledConnectionDecision(poolCounts[i]);
}
return false;
}
}
i++;
}
return true;
}
}
public void noteConnectionReturnedToPool(String[] binNames, AtomicInteger[] poolCounts)
{
synchronized (connectionBins)
{
for (int j = 0; j < binNames.length; j++)
{
ConnectionBin bin = connectionBins.get(binNames[j]);
if (bin != null)
bin.noteConnectionReturnedToPool(poolCounts[j]);
}
}
}
public void noteConnectionDestroyed(String[] binNames)
{
synchronized (connectionBins)
{
for (String binName : binNames)
{
ConnectionBin bin = connectionBins.get(binName);
if (bin != null)
bin.noteConnectionDestroyed();
}
}
}
// IFetchThrottler support methods
/** Get permission to fetch a document. This grants permission to start
* fetching a single document, within the connection that has already been
* granted permission that created this object.
*@param binNames are the names of the bins.
*@return false if being shut down
*/
public boolean obtainFetchDocumentPermission(String[] binNames, IBreakCheck breakCheck)
throws InterruptedException, BreakException
{
// First, make sure all the bins exist, and reserve a slot in each
int i = 0;
while (i < binNames.length)
{
String binName = binNames[i];
FetchBin bin;
synchronized (fetchBins)
{
bin = fetchBins.get(binName);
}
// Reserve a slot
try
{
if (bin == null || !bin.reserveFetchRequest(breakCheck))
{
// Release previous reservations, and return null
while (i > 0)
{
i--;
binName = binNames[i];
synchronized (fetchBins)
{
bin = fetchBins.get(binName);
}
if (bin != null)
bin.clearReservation();
}
return false;
}
}
catch (BreakException e)
{
// Release previous reservations, and rethrow
while (i > 0)
{
i--;
binName = binNames[i];
synchronized (fetchBins)
{
bin = fetchBins.get(binName);
}
if (bin != null)
bin.clearReservation();
}
throw e;
}
i++;
}
// All reservations have been made! Convert them.
// (These are guaranteed to succeed - but they may wait)
i = 0;
while (i < binNames.length)
{
String binName = binNames[i];
FetchBin bin;
synchronized (fetchBins)
{
bin = fetchBins.get(binName);
}
if (bin != null)
{
try
{
if (!bin.waitNextFetch(breakCheck))
{
// Undo the reservations we haven't processed yet
while (i < binNames.length)
{
binName = binNames[i];
synchronized (fetchBins)
{
bin = fetchBins.get(binName);
}
if (bin != null)
bin.clearReservation();
i++;
}
return false;
}
}
catch (BreakException e)
{
// Undo the reservations we haven't processed yet
while (i < binNames.length)
{
binName = binNames[i];
synchronized (fetchBins)
{
bin = fetchBins.get(binName);
}
if (bin != null)
bin.clearReservation();
i++;
}
throw e;
}
}
i++;
}
return true;
}
public IStreamThrottler createFetchStream(String[] binNames)
{
// Do a "begin fetch" for all throttle bins
synchronized (throttleBins)
{
for (String binName : binNames)
{
ThrottleBin bin = throttleBins.get(binName);
if (bin != null)
bin.beginFetch();
}
}
return new StreamThrottler(this, binNames);
}
// IStreamThrottler support methods
/** Obtain permission to read a block of bytes. This method may wait until it is OK to proceed.
* The throttle group, bin names, etc are already known
* to this specific interface object, so it is unnecessary to include them here.
*@param byteCount is the number of bytes to get permissions to read.
*@return true if the wait took place as planned, or false if the system is being shut down.
*/
public boolean obtainReadPermission(String[] binNames, int byteCount, IBreakCheck breakCheck)
throws InterruptedException, BreakException
{
int i = 0;
while (i < binNames.length)
{
String binName = binNames[i];
ThrottleBin bin;
synchronized (throttleBins)
{
bin = throttleBins.get(binName);
}
try
{
if (bin == null || !bin.beginRead(byteCount, breakCheck))
{
// End bins we've already done, and exit
while (i > 0)
{
i--;
binName = binNames[i];
synchronized (throttleBins)
{
bin = throttleBins.get(binName);
}
if (bin != null)
bin.endRead(byteCount,0);
}
return false;
}
}
catch (BreakException e)
{
// End bins we've already done, and exit
while (i > 0)
{
i--;
binName = binNames[i];
synchronized (throttleBins)
{
bin = throttleBins.get(binName);
}
if (bin != null)
bin.endRead(byteCount,0);
}
throw e;
}
i++;
}
return true;
}
/** Note the completion of the read of a block of bytes. Call this after
* obtainReadPermission() was successfully called, and bytes were successfully read.
*@param origByteCount is the originally requested number of bytes to get permissions to read.
*@param actualByteCount is the number of bytes actually read.
*/
public void releaseReadPermission(String[] binNames, int origByteCount, int actualByteCount)
{
synchronized (throttleBins)
{
for (String binName : binNames)
{
ThrottleBin bin = throttleBins.get(binName);
if (bin != null)
bin.endRead(origByteCount, actualByteCount);
}
}
}
/** Note the stream being closed.
*/
public void closeStream(String[] binNames)
{
synchronized (throttleBins)
{
for (String binName : binNames)
{
ThrottleBin bin = throttleBins.get(binName);
if (bin != null)
bin.endFetch();
}
}
}
// Bookkeeping methods
/** Call this periodically.
*/
public synchronized void poll(IThreadContext threadContext)
throws ManifoldCFException
{
// Go through all existing bins and update each one.
synchronized (connectionBins)
{
for (ConnectionBin bin : connectionBins.values())
{
bin.updateMaxActiveConnections(throttleSpec.getMaxOpenConnections(bin.getBinName()));
bin.poll(threadContext);
}
}
synchronized (fetchBins)
{
for (FetchBin bin : fetchBins.values())
{
bin.updateMinTimeBetweenFetches(throttleSpec.getMinimumMillisecondsPerFetch(bin.getBinName()));
bin.poll(threadContext);
}
}
synchronized (throttleBins)
{
for (ThrottleBin bin : throttleBins.values())
{
bin.updateMinimumMillisecondsPerByte(throttleSpec.getMinimumMillisecondsPerByte(bin.getBinName()));
bin.poll(threadContext);
}
}
}
/** Free unused resources.
*/
public synchronized void freeUnusedResources(IThreadContext threadContext)
throws ManifoldCFException
{
// Does nothing; there are not really resources to free
}
/** Destroy this pool.
*/
public synchronized void destroy(IThreadContext threadContext)
throws ManifoldCFException
{
synchronized (connectionBins)
{
Iterator<ConnectionBin> binIter = connectionBins.values().iterator();
while (binIter.hasNext())
{
ConnectionBin bin = binIter.next();
bin.shutDown(threadContext);
binIter.remove();
}
}
synchronized (fetchBins)
{
Iterator<FetchBin> binIter = fetchBins.values().iterator();
while (binIter.hasNext())
{
FetchBin bin = binIter.next();
bin.shutDown(threadContext);
binIter.remove();
}
}
synchronized (throttleBins)
{
Iterator<ThrottleBin> binIter = throttleBins.values().iterator();
while (binIter.hasNext())
{
ThrottleBin bin = binIter.next();
bin.shutDown(threadContext);
binIter.remove();
}
}
}
}
/** Connection throttler implementation class.
* This class instance stores some parameters and links back to ThrottlingGroup. But each class instance
* models a connection pool with the specified bins. But the description of each pool consists of more than just
* the bin names that describe the throttling - it also may include connection parameters which we have
* no insight into at this level.
*
* Thus, in order to do pool tracking properly, we cannot simply rely on the individual connection bin instances
* to do all the work, since they cannot distinguish between different pools properly. So that leaves us with
* two choices. (1) We can somehow push the separate pool instance parameters down to the connection bin
* level, or (2) the connection bins cannot actually do any waiting or blocking.
*
* The benefit of having blocking take place in connection bins is that they are in fact designed to be precisely
* the thing you would want to synchronize on. If we presume that the waits happen in those classes,
* then we need the ability to send in our local pool count to them, and we need to be able to "wake up"
* those underlying classes when the local pool count changes.
*/
protected static class ConnectionThrottler implements IConnectionThrottler
{
protected final ThrottlingGroup parent;
protected final String[] binNames;
protected final AtomicInteger[] poolCounts;
// Keep track of local pool parameters.
public ConnectionThrottler(ThrottlingGroup parent, String[] binNames)
{
this.parent = parent;
this.binNames = binNames;
this.poolCounts = new AtomicInteger[binNames.length];
for (int i = 0; i < poolCounts.length; i++)
poolCounts[i] = new AtomicInteger(0);
}
/** Get permission to grab a connection for use. If this object believes there is a connection
* available in the pool, it will update its pool size variable and return If not, this method
* evaluates whether a new connection should be created. If neither condition is true, it
* waits until a connection is available.
*@return whether to take the connection from the pool, or create one, or whether the
* throttler is being shut down.
*/
@Override
public int waitConnectionAvailable()
throws InterruptedException
{
try
{
return waitConnectionAvailable(null);
}
catch (BreakException e)
{
throw new RuntimeException("Unexpected break exception: "+e.getMessage(),e);
}
}
/** Get permission to grab a connection for use. If this object believes there is a connection
* available in the pool, it will update its pool size variable and return If not, this method
* evaluates whether a new connection should be created. If neither condition is true, it
* waits until a connection is available.
*@return whether to take the connection from the pool, or create one, or whether the
* throttler is being shut down.
*/
@Override
public int waitConnectionAvailable(IBreakCheck breakCheck)
throws InterruptedException, BreakException
{
return parent.waitConnectionAvailable(binNames, poolCounts, breakCheck);
}
/** For a new connection, obtain the fetch throttler to use for the connection.
* If the result from waitConnectionAvailable() is CONNECTION_FROM_CREATION,
* the calling code is expected to create a connection using the result of this method.
*@return the fetch throttler for a new connection.
*/
@Override
public IFetchThrottler getNewConnectionFetchThrottler()
{
return parent.getNewConnectionFetchThrottler(binNames);
}
/** For returning a connection from use, there is only one method. This method signals
/* whether a formerly in-use connection should be placed back in the pool or destroyed.
*@return true if the connection should NOT be put into the pool but should instead
* simply be destroyed. If true is returned, the caller MUST call noteConnectionDestroyed()
* (below) in order for the bookkeeping to work.
*/
@Override
public boolean noteReturnedConnection()
{
return parent.noteReturnedConnection(binNames);
}
/** This method calculates whether a connection should be taken from the pool and destroyed
/* in order to meet quota requirements. If this method returns
/* true, you MUST remove a connection from the pool, and you MUST call
/* noteConnectionDestroyed() afterwards.
*@return true if a pooled connection should be destroyed. If true is returned, the
* caller MUST call noteConnectionDestroyed() (below) in order for the bookkeeping to work.
*/
@Override
public boolean checkDestroyPooledConnection()
{
return parent.checkDestroyPooledConnection(binNames, poolCounts);
}
/** Connection expiration is tricky, because even though a connection may be identified as
* being expired, at the very same moment it could be handed out in another thread. So there
* is a natural race condition present.
* The way the connection throttler deals with that is to allow the caller to reserve a connection
* for expiration. This must be called BEFORE the actual identified connection is removed from the
* connection pool. If the value returned by this method is "true", then a connection MUST be removed
* from the pool and destroyed, whether or not the identified connection is actually still available for
* destruction or not.
*@return true if a connection from the pool can be expired. If true is returned, noteConnectionDestruction()
* MUST be called once the connection has actually been destroyed.
*/
@Override
public boolean checkExpireConnection()
{
return parent.checkExpireConnection(binNames, poolCounts);
}
/** Note that a connection has been returned to the pool. Call this method after a connection has been
* placed back into the pool and is available for use.
*/
@Override
public void noteConnectionReturnedToPool()
{
parent.noteConnectionReturnedToPool(binNames, poolCounts);
}
/** Note that a connection has been destroyed. Call this method ONLY after noteReturnedConnection()
* or checkDestroyPooledConnection() returns true, AND the connection has been already
* destroyed.
*/
@Override
public void noteConnectionDestroyed()
{
parent.noteConnectionDestroyed(binNames);
}
}
/** Fetch throttler implementation class.
* This basically stores some parameters and links back to ThrottlingGroup.
*/
protected static class FetchThrottler implements IFetchThrottler
{
protected final ThrottlingGroup parent;
protected final String[] binNames;
public FetchThrottler(ThrottlingGroup parent, String[] binNames)
{
this.parent = parent;
this.binNames = binNames;
}
/** Get permission to fetch a document. This grants permission to start
* fetching a single document, within the connection that has already been
* granted permission that created this object.
*@return false if the throttler is being shut down.
*/
@Override
public boolean obtainFetchDocumentPermission()
throws InterruptedException
{
try
{
return obtainFetchDocumentPermission(null);
}
catch (BreakException e)
{
throw new RuntimeException("Unexpected break exception: "+e.getMessage(),e);
}
}
/** Get permission to fetch a document. This grants permission to start
* fetching a single document, within the connection that has already been
* granted permission that created this object.
*@return false if the throttler is being shut down.
*/
@Override
public boolean obtainFetchDocumentPermission(IBreakCheck breakCheck)
throws InterruptedException, BreakException
{
return parent.obtainFetchDocumentPermission(binNames,breakCheck);
}
/** Open a fetch stream. When done (or aborting), call
* IStreamThrottler.closeStream() to note the completion of the document
* fetch activity.
*@return the stream throttler to use to throttle the actual data access.
*/
@Override
public IStreamThrottler createFetchStream()
{
return parent.createFetchStream(binNames);
}
}
/** Stream throttler implementation class.
* This basically stores some parameters and links back to ThrottlingGroup.
*/
protected static class StreamThrottler implements IStreamThrottler
{
protected final ThrottlingGroup parent;
protected final String[] binNames;
public StreamThrottler(ThrottlingGroup parent, String[] binNames)
{
this.parent = parent;
this.binNames = binNames;
}
/** Obtain permission to read a block of bytes. This method may wait until it is OK to proceed.
* The throttle group, bin names, etc are already known
* to this specific interface object, so it is unnecessary to include them here.
*@param byteCount is the number of bytes to get permissions to read.
*@return true if the wait took place as planned, or false if the system is being shut down.
*/
@Override
public boolean obtainReadPermission(int byteCount)
throws InterruptedException
{
try
{
return obtainReadPermission(byteCount, null);
}
catch (BreakException e)
{
throw new RuntimeException("Unexpected break exception: "+e.getMessage(),e);
}
}
/** Obtain permission to read a block of bytes. This method may wait until it is OK to proceed.
* The throttle group, bin names, etc are already known
* to this specific interface object, so it is unnecessary to include them here.
*@param byteCount is the number of bytes to get permissions to read.
*@param breakCheck is the break check object.
*@return true if the wait took place as planned, or false if the system is being shut down.
*/
@Override
public boolean obtainReadPermission(int byteCount, IBreakCheck breakCheck)
throws InterruptedException, BreakException
{
return parent.obtainReadPermission(binNames, byteCount, breakCheck);
}
/** Note the completion of the read of a block of bytes. Call this after
* obtainReadPermission() was successfully called, and bytes were successfully read.
*@param origByteCount is the originally requested number of bytes to get permissions to read.
*@param actualByteCount is the number of bytes actually read.
*/
@Override
public void releaseReadPermission(int origByteCount, int actualByteCount)
{
parent.releaseReadPermission(binNames, origByteCount, actualByteCount);
}
/** Note the stream being closed.
*/
@Override
public void closeStream()
{
parent.closeStream(binNames);
}
}
}
| |
//=====================================================================
//
//File: $RCSfile: UIUtil.java,v $
//Version: $Revision: 1.29 $
//Modified: $Date: 2013/06/12 13:08:18 $
//
//(c) Copyright 2004-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//=====================================================================
package com.mentor.nucleus.bp.core.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.properties.PropertySheet;
import org.osgi.framework.Bundle;
import com.mentor.nucleus.bp.core.CorePlugin;
import com.mentor.nucleus.bp.core.Ooaofooa;
import com.mentor.nucleus.bp.core.SystemModel_c;
import com.mentor.nucleus.bp.core.common.ClassQueryInterface_c;
import com.mentor.nucleus.bp.core.common.ModelElement;
import com.mentor.nucleus.bp.core.common.NonRootModelElement;
import com.mentor.nucleus.bp.core.common.PersistenceManager;
import com.mentor.nucleus.bp.core.ui.RenameAction;
import com.mentor.nucleus.bp.core.ui.dialogs.ScrolledTextDialog;
/**
* Utility methods related to this product's UI.
*/
public class UIUtil
{
private static boolean displayYesNoQuestion_isYes = true;
private static volatile boolean booleanDialogResult = false;
/**
*
* @param element null to refresh whole tree
*/
public static void refresh(final Object element) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
StructuredViewer viewer = null;
Class<?> explorerViewClass = null;
Object elementToRefresh = element;
try {
Bundle ui_explorer = Platform
.getBundle("com.mentor.nucleus.bp.ui.explorer");//$NON-NLS-1$
explorerViewClass = ui_explorer
.loadClass("com.mentor.nucleus.bp.ui.explorer.ExplorerView"); //$NON-NLS-1$
} catch (Exception cnf) {
CorePlugin.logError(
"Problem accessing GraphicsUtil class ", cnf); //$NON-NLS-1$
return;
}
Class<?>[] type;
try {
type = new Class<?>[] {};
Method getExplorerTreeViewer = explorerViewClass.getMethod(
"getExplorerTreeViewer", type); //$NON-NLS-1$
Object[] args = new Object[] {};
viewer = (StructuredViewer) getExplorerTreeViewer.invoke(
explorerViewClass, args);
} catch (Exception e) {
CorePlugin
.logError(
"Error invoking getCanvasEditorTitle(NRME) in GraphicsUtil ", e); //$NON-NLS-1$
}
if (element instanceof IProject) {
elementToRefresh = SystemModel_c.SystemModelInstance(
Ooaofooa.getDefaultInstance(),
new ClassQueryInterface_c() {
public boolean evaluate(Object c) {
return ((SystemModel_c) c).getName()
.equals(
((IProject) element)
.getName());
}
}, false);
}
refreshViewer(viewer, elementToRefresh);
IEditorReference[] editorReferences = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.getEditorReferences();
for (IEditorReference reference : editorReferences) {
IEditorPart editor = reference.getEditor(false);
if (editor != null) {
Method method = null;
try {
method = editor.getClass().getMethod(
"refresh", new Class[0]); //$NON-NLS-1$
} catch (SecurityException e) {
CorePlugin.logError("Unable to locate method for refreshing graphical editors.", e);
} catch (NoSuchMethodException e) {
// most editors will not have this method, for those we do not
// want to refresh anyway
}
if (method != null) {
try {
method.invoke(editor, new Object[0]);
} catch (IllegalArgumentException e) {
CorePlugin.logError("Unable to invoke refresh method for graphical editor.", e);
} catch (IllegalAccessException e) {
CorePlugin.logError("Unable to invoke refresh method for graphical editor.", e);
} catch (InvocationTargetException e) {
CorePlugin.logError("Unable to invoke refresh method for graphical editor.", e);
}
}
}
}
}
});
}
public static void refreshViewer(final StructuredViewer viewer)
{
refreshViewer(viewer, null);
}
/**
* Performs a refresh of the given viewer, on the UI thread,
* starting with the given element. If no element is given,
* the refresh starts with the viewer's root element.
*/
private static HashMap<StructuredViewer, ArrayList<Object>> updateList =
new HashMap<StructuredViewer, ArrayList<Object>>();
public static void refreshViewer(final StructuredViewer viewer,
final Object element)
{
Object target = element;
if (viewer == null)
return;
// if the given viewer hasn't been disposed
Control control = viewer.getControl();
if (!control.isDisposed()) {
if (target instanceof NonRootModelElement) {
IFile f = ((NonRootModelElement) target).getFile();
if (f == null || !f.getProject().isOpen()) {
target = null;
}
} else if (target instanceof Ooaofooa) {
IFile f = ((Ooaofooa) target).getFile();
if (f == null || !f.getProject().isOpen()) {
refresh(viewer, null);
}
}
boolean queueRefresh = true;
if (updateList.containsKey(viewer)) {
// if the element is already scheduled for a refresh or if the whole
// tree is going to be refreshed, don't repeat the refresh
if(updateList.get(viewer).contains(target) || updateList.get(viewer).contains(null)) {
queueRefresh = false;
}
}
if (queueRefresh) {
synchronized(updateList) {
Display display = control.getDisplay();
// ask the viewer's UI thread to perform the refresh
final Object f_target = target;
display.asyncExec(
new Runnable() {
public void run() {
updateList.get(viewer).remove(f_target);
refresh(viewer, f_target);
}
});
if (!updateList.containsKey(viewer)) {
updateList.put(viewer, new ArrayList<Object>());
}
updateList.get(viewer).add(f_target);
}
}
}
}
/**
* Makes the appropriate call to refresh() on the given viewer, depending on
* whether the given element is non-null.
*/
private static void refresh(final StructuredViewer viewer,
final Object element)
{
WorkspaceJob job = new WorkspaceJob("Refreshing views") {
@Override
public IStatus runInWorkspace(IProgressMonitor monitor)
throws CoreException {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if(!viewer.getControl().isDisposed()){
if (element != null) viewer.refresh(element);
else viewer.refresh();
}
}
});
return Status.OK_STATUS;
}
};
job.setRule(ResourcesPlugin.getWorkspace().getRoot());
job.schedule();
}
/**
* Makes a call to the given control's redraw() method, ensuring
* that the call occurs on the UI thread. If the calling thread
* is not the UI thread, the UI thread is asked to make the call.
*/
public static void redrawControl(final Control control)
{
// if the given control has been disposed, there is nothing to do
if (control.isDisposed()) return;
// if we're running on the UI thread
Display display = control.getDisplay();
if (Display.getCurrent() == display) {
// make the redraw call directly
control.redraw();
}
// otherwise
else {
// ask the UI thread to make the redraw call
display.asyncExec(
new Runnable() {
public void run() {
control.redraw();
}
});
}
}
public static Menu getMenuForTreeItem(TreeViewer viewer, TreeItem item) {
Tree sevTree = viewer.getTree();
viewer.setSelection(new StructuredSelection(item.getData()));
sevTree.setSelection(item);
UIUtil.dispatchAll();
Menu menu = viewer.getTree().getMenu();
return menu;
}
/**
* Causes the context menu for the given control to be populated,
* by temporarily having it displayed.
*/
public static void getContextMenuPopulated(Control control)
{
// have the menu closed a short while after it's displayed, below,
// once it's very likely to have been fully populated
final Menu menu = control.getMenu();
Display display = control.getDisplay();
display.timerExec(10,
new Runnable() {
public void run() {
menu.setVisible(false);
}
});
// display the context menu to get it populated
menu.setVisible(true);
while (display.readAndDispatch());
}
/**
* Is a shorthand method for the enclosed code.
*/
public static void dispatchAll()
{
if (PlatformUI.isWorkbenchRunning()) { // If we are running in "truly headless" more there is no workbench
if (Display.getCurrent() != null) {
while (Display.getCurrent().readAndDispatch());
}
}
}
/**
* Returns the tree control displayed for the currently active properties
* sheet page. This method requires that the properties view is currently
* visible within the workbench.
*/
public static Tree getPropertyTree()
{
PropertySheet sheet = (PropertySheet)PlatformUI.getWorkbench().
getActiveWorkbenchWindow().getActivePage().findView(
IPageLayout.ID_PROP_SHEET);
return (Tree)sheet.getCurrentPage().getControl();
}
private static void outputTextForheadlessRun(BPMessageTypes type, String title, String text, String value) {
String outputString = type.getText() + ": " + title + ". " + text;
if (!value.isEmpty()) {
outputString += ". Value: " + value;
}
CorePlugin.out.println(outputString);
}
/**
* Opens a scrollable dialog with the given data
*/
public static boolean openScrollableTextDialog(Shell parentShell,
boolean allowCancel, String title, String textContents,
String message, String optionalText, String preferenceKey,
boolean defaultReturn) {
if (CoreUtil.IsRunningHeadless) {
outputTextForheadlessRun(BPMessageTypes.QUESTION, title, message, String.valueOf(defaultReturn));
} else {
ScrolledTextDialog dialog = new ScrolledTextDialog(parentShell, allowCancel, title, textContents, message, optionalText, preferenceKey);
int result = dialog.open();
if(result == Window.OK) {
return true;
} else {
return false;
}
}
return defaultReturn;
}
/**
* Shows an error dialog with the given title and message.
*/
public static void showErrorDialog(String title, String message)
{
IWorkbenchWindow activeWindow = null;
Shell parentShell = null;
if (!CoreUtil.IsRunningHeadless) {
activeWindow = CorePlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
}
if (activeWindow != null) {
parentShell = activeWindow.getShell();
}
openError(parentShell, title, message);
}
public enum BPMessageTypes {
INFORMATION("Information"), WARNING("Warning"), ERROR("Error"), CONFIRM("Confirm"), QUESTION("Question"), INPUT("Input");
private String description;
BPMessageTypes(String p_description) {
description = p_description;
}
public String getText() {
return description;
}
};
public static void openError(Shell parent, String title, final String message) {
openError(parent, title, message, false );
}
public static void openError(Shell parent, String title, final String message, boolean showTechSupportContactInfo) {
internalDialogHandler(parent, title, message, BPMessageTypes.ERROR, showTechSupportContactInfo );
}
public static void openErrorWithContactInfo(final String message) {
openError(null, null, message, true );
}
public static void openError(final String message) {
openError(null, null, message, false );
}
public static void displayError(final String message) {
openError(message);
}
public static void openWarning(Shell parent, String title, final String message) {
internalDialogHandler(parent, title, message, BPMessageTypes.WARNING, false);
}
public static void openWarning(final String message) {
openWarning(null, null, message);
}
public static void displayWarning(final String message) {
openWarning(message);
}
public static void openInformation(Shell parent, String title, final String message) {
internalDialogHandler(parent, title, message, BPMessageTypes.INFORMATION, false);
}
public static void openInformation(final String message) {
openInformation(null, null, message);
}
public static boolean openConfirm(Shell parent, String title, final String message, boolean defaultValue) {
booleanDialogResult = defaultValue;
return internalDialogHandler(parent, title, message, BPMessageTypes.CONFIRM, false);
}
public static boolean openConfirm(final String message, boolean defaultValue) {
return openConfirm(null, null, message, defaultValue);
}
public static boolean openQuestion(Shell parent, String title, final String message, boolean defaultValue) {
booleanDialogResult = defaultValue;
return internalDialogHandler(parent, title, message, BPMessageTypes.QUESTION, false);
}
public static boolean openQuestion(final String message, boolean defaultValue) {
return openQuestion(null, null, message, defaultValue);
}
public static void showMessageDialoginLaunch(Shell p_parent, String p_title,
String p_msg, BPMessageTypes p_type) {
internalDialogHandler(p_parent, p_title, p_msg, p_type, false);
}
/**
* Note this "MessageDialog" currently only supports an array of 2 dialog button
* labels. This is why the result is a boolean. It simply behaves in
* a similar manner as if a yes/no question had been asked (offset 0 is
* yes and offset 1 is no). If additional buttons are ever needed this
* will need to be modified to handle it.
*/
public static boolean openMessageDialog(Shell parentShell, String dialogTitle,
Image dialogTitleImage, String dialogMessage, BPMessageTypes dialogType,
String[] dialogButtonLabels, int defaultIndex) {
int standardDialogType = MessageDialog.WARNING;
if (dialogType == BPMessageTypes.ERROR) {
standardDialogType = MessageDialog.ERROR;
} else if ((dialogType == BPMessageTypes.INFORMATION)) {
standardDialogType = MessageDialog.INFORMATION;
}
boolean result = (defaultIndex == MessageDialog.OK);
if (CoreUtil.IsRunningHeadless) {
outputTextForheadlessRun(dialogType, dialogTitle, dialogMessage, "");
} else {
MessageDialog dialog = new MessageDialog(parentShell, dialogTitle,
dialogTitleImage, dialogMessage, standardDialogType,
dialogButtonLabels, defaultIndex);
dialog.setBlockOnOpen(true);
int actualResult = dialog.open();
result = MessageDialog.OK == actualResult;
}
return result;
}
private static class BPMessageDialog implements Runnable {
Shell m_parent;
final String m_title;
final String m_msg;
final BPMessageTypes m_type;
BPMessageDialog(Shell p_parent, final String p_title,
final String p_msg, final BPMessageTypes p_type) {
m_parent = p_parent;
m_title = p_title;
m_msg = p_msg;
m_type = p_type;
}
public void run() {
boolean logTheMessage = false;
if (m_type == BPMessageTypes.ERROR) {
logTheMessage = true;
}
if (m_parent == null && !CoreUtil.IsRunningHeadless) {
IWorkbenchWindow activeWBWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
Shell parentShell = null;
if (activeWBWindow != null) {
m_parent = activeWBWindow.getShell();
}
}
if (CoreUtil.IsRunningHeadless) {
// if headless there shouldn't be a parent shell, but this is just to be sure
m_parent = null;
}
if (m_parent != null && !CoreUtil.IsRunningHeadless) {
if ( m_type == BPMessageTypes.INFORMATION ) {
org.eclipse.jface.dialogs.MessageDialog.openInformation(
m_parent,
m_title,
m_msg
);
} else if (m_type == BPMessageTypes.WARNING ) {
org.eclipse.jface.dialogs.MessageDialog
.openWarning(
m_parent,
m_title,
m_msg
);
} else if ( m_type == BPMessageTypes.ERROR ) {
org.eclipse.jface.dialogs.MessageDialog
.openError(
m_parent,
m_title,
m_msg
);
} else if ( m_type == BPMessageTypes.CONFIRM ) {
booleanDialogResult = org.eclipse.jface.dialogs.MessageDialog
.openConfirm(
m_parent,
m_title,
m_msg
);
} else if ( m_type == BPMessageTypes.QUESTION ) {
booleanDialogResult = org.eclipse.jface.dialogs.MessageDialog
.openQuestion(
m_parent,
m_title,
m_msg
);
}
} else if (CoreUtil.IsRunningHeadless) {
outputTextForheadlessRun(m_type, m_title, m_msg, "");
} else{
// No Active shell is available for a UI dialog.
logTheMessage = true;
}
if (logTheMessage) {
CorePlugin.logError(m_title + "\n" + m_msg,
null);
}
}
}
private static boolean internalDialogHandler(Shell p_parent, String p_title,
String p_msg, BPMessageTypes p_type,
boolean p_showTechSupportContact) {
booleanDialogResult = false;
p_title = (p_title == null) ? "BridgePoint UML Suite" : p_title;
if (p_showTechSupportContact) {
p_msg = p_msg + "\n\n" + UIUtil.getTechSupportMessage();
}
if (CoreUtil.IsRunningHeadless) {
p_parent = null;
}
Runnable dialog = new BPMessageDialog(p_parent, p_title, p_msg, p_type);
if (p_parent!= null || CoreUtil.IsRunningHeadless) {
dialog.run();
} else {
PlatformUI.getWorkbench().getDisplay().syncExec(dialog);
}
return booleanDialogResult;
}
public static String getTechSupportMessage() {
String msg =
"Please visit the xtUML Forum for a searchable knowledgebase of technical issues,"
+ "the ability to open a service request online, and many other useful tools:\n\n"
+ "\thttps://www.xtuml.org/community/forum/xtuml-forum/\n";
return msg;
}
/**
*
* @param msg
* @return true if the user responds yes and false if the user responds no
*/
public static boolean displayYesNoQuestion(final String msg) {
displayYesNoQuestion_isYes = true;
if (CoreUtil.IsRunningHeadless) {
displayYesNoQuestion_isYes = UIUtil.openMessageDialog(null,
"BridgePoint UML Suite", null, msg,
UIUtil.BPMessageTypes.QUESTION,
new String[] { "Yes", "No" }, 0); // yes is he default
} else {
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
public void run() {
org.eclipse.swt.widgets.Shell sh = PlatformUI.getWorkbench()
.getDisplay().getActiveShell();
MessageDialog dialog = new MessageDialog(
sh, "BridgePoint UML Suite", null,
msg,
MessageDialog.QUESTION,
new String[] {"Yes", "No"},
0); // yes is the default
displayYesNoQuestion_isYes = (dialog.open() == 0);
}
});
}
return displayYesNoQuestion_isYes;
}
/**
* Mirror the functionality of the jface InputDialog. If the user cancels
* then dialog then false is returned. If the users select OK, then
* true is returned, and the text entered is found in
* UIUtil.inputDialogResult.
*/
public static String inputDialogResult = "";
public static boolean inputDialog(Shell parentShell, String dialogTitle,
String dialogMessage, String initialValue, IInputValidator validator) {
inputDialogResult = "";
if(CoreUtil.IsRunningHeadless) {
outputTextForheadlessRun(BPMessageTypes.INPUT, dialogTitle, dialogMessage, initialValue);
} else {
InputDialog id = new InputDialog(parentShell, dialogTitle,
dialogMessage, initialValue, validator);
int result = id.open();
id.getValue();
if (result == InputDialog.OK) {
inputDialogResult = id.getValue();
return true;
} else {
return false;
}
}
return false;
}
/**
* A simple utility function that passes-along call to class RenameAction.
*
* Returns null if the given name is valid for the given model element.
* Otherwise, returns a message stating why the name is invalid.
*/
public static String validateNameUsingRenameAction(String name, ModelElement element) {
String result = RenameAction.isNameValid(name, element);
if(result == null) {
// if the element adapts to a file then we
// must validate with the OS
if(element instanceof NonRootModelElement) {
NonRootModelElement nrme = (NonRootModelElement) element;
if(PersistenceManager.getHierarchyMetaData().isComponentRoot(nrme)) {
IStatus validateName = RenameAction.validateName(nrme, name, IResource.FILE);
if(!validateName.isOK()) {
result = validateName.getMessage();
}
}
}
}
if(result != null && result.equals("")) {
return null;
}
return result;
}
static class NameInputValidator implements IInputValidator {
private ModelElement element;
public NameInputValidator(ModelElement element) {
this.element = element;
}
@Override
public String isValid(String newText) {
return validateNameUsingRenameAction(newText, element);
}
}
public static IInputValidator newRenameValidator(ModelElement element) {
return new NameInputValidator(element);
}
public static Object[] openSelectionDialog(Object[] objects, String message, String title) {
if(CoreUtil.IsRunningHeadless) {
return new Object[0];
}
UIUtil ui = new UIUtil();
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
new WorkbenchLabelProvider(), ui.new ProjectContentProvider(
objects));
dialog.setHelpAvailable(false);
dialog.setInput(new Object());
dialog.setMessage(message);
dialog.setTitle(title);
dialog.setAllowMultiple(true);
dialog.setValidator(ui.new SelectionDialogValidator());
int result = dialog.open();
if (result == Dialog.OK) {
return dialog.getResult();
}
return new Object[0];
}
class SelectionDialogValidator implements ISelectionStatusValidator {
@Override
public IStatus validate(Object[] selection) {
if (selection.length == 0) {
return new Status(IStatus.ERROR, CorePlugin.getName(), "");
} else {
return Status.CANCEL_STATUS;
}
}
}
class ProjectContentProvider implements ITreeContentProvider {
Object[] projects;
public ProjectContentProvider(Object[] projects) {
this.projects = projects;
}
@Override
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IProject) {
return new Object[0];
} else {
return projects;
}
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
@Override
public Object[] getElements(Object inputElement) {
if (inputElement instanceof IProject) {
return new Object[0];
} else {
return projects;
}
}
@Override
public void dispose() {
// nothing to do
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// nothing to do
}
}
}
| |
package com.ivan.materialdesign.views;
import com.ivan.materialdesign.R;
import com.ivan.materialdesign.utils.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.TextView;
public abstract class Button extends CustomView {
final static String ANDROIDXML = "http://schemas.android.com/apk/res/android";
// Complete in child class
int minWidth;
int minHeight;
int background;
float rippleSpeed = 12f;
int rippleSize = 3;
Integer rippleColor;
OnClickListener onClickListener;
boolean clickAfterRipple = true;
int backgroundColor = Color.parseColor("#1E88E5");
TextView textButton;
public Button(Context context, AttributeSet attrs) {
super(context, attrs);
setDefaultProperties();
clickAfterRipple = attrs.getAttributeBooleanValue(MATERIALDESIGNXML,
"animate", true);
setAttributes(attrs);
beforeBackground = backgroundColor;
if (rippleColor == null)
rippleColor = makePressColor();
}
protected void setDefaultProperties() {
// Min size
setMinimumHeight(Utils.dpToPx(minHeight, getResources()));
setMinimumWidth(Utils.dpToPx(minWidth, getResources()));
// Background shape
setBackgroundResource(background);
setBackgroundColor(backgroundColor);
}
// Set atributtes of XML to View
abstract protected void setAttributes(AttributeSet attrs);
// ### RIPPLE EFFECT ###
float x = -1, y = -1;
float radius = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
invalidate();
if (isEnabled()) {
isLastTouch = true;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
radius = getHeight() / rippleSize;
x = event.getX();
y = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
radius = getHeight() / rippleSize;
x = event.getX();
y = event.getY();
if (!((event.getX() <= getWidth() && event.getX() >= 0) && (event
.getY() <= getHeight() && event.getY() >= 0))) {
isLastTouch = false;
x = -1;
y = -1;
}
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if ((event.getX() <= getWidth() && event.getX() >= 0)
&& (event.getY() <= getHeight() && event.getY() >= 0)) {
radius++;
if (!clickAfterRipple && onClickListener != null) {
onClickListener.onClick(this);
}
} else {
isLastTouch = false;
x = -1;
y = -1;
}
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
isLastTouch = false;
x = -1;
y = -1;
}
}
return true;
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction,
Rect previouslyFocusedRect) {
if (!gainFocus) {
x = -1;
y = -1;
}
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// super.onInterceptTouchEvent(ev);
return true;
}
public Bitmap makeCircle() {
Bitmap output = Bitmap.createBitmap(
getWidth() - Utils.dpToPx(6, getResources()), getHeight()
- Utils.dpToPx(7, getResources()), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawARGB(0, 0, 0, 0);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(rippleColor);
canvas.drawCircle(x, y, radius, paint);
if (radius > getHeight() / rippleSize)
radius += rippleSpeed;
if (radius >= getWidth()) {
x = -1;
y = -1;
radius = getHeight() / rippleSize;
if (onClickListener != null && clickAfterRipple)
onClickListener.onClick(this);
}
return output;
}
/**
* Make a dark color to ripple effect
*
* @return
*/
protected int makePressColor() {
int r = (this.backgroundColor >> 16) & 0xFF;
int g = (this.backgroundColor >> 8) & 0xFF;
int b = (this.backgroundColor >> 0) & 0xFF;
r = (r - 30 < 0) ? 0 : r - 30;
g = (g - 30 < 0) ? 0 : g - 30;
b = (b - 30 < 0) ? 0 : b - 30;
return Color.rgb(r, g, b);
}
@Override
public void setOnClickListener(OnClickListener l) {
onClickListener = l;
}
// Set color of background
public void setBackgroundColor(int color) {
this.backgroundColor = color;
if (isEnabled())
beforeBackground = backgroundColor;
try {
LayerDrawable layer = (LayerDrawable) getBackground();
GradientDrawable shape = (GradientDrawable) layer
.findDrawableByLayerId(R.id.shape_bacground);
shape.setColor(backgroundColor);
rippleColor = makePressColor();
} catch (Exception ex) {
// Without bacground
}
}
public void setRippleSpeed(float rippleSpeed) {
this.rippleSpeed = rippleSpeed;
}
public float getRippleSpeed() {
return this.rippleSpeed;
}
public void setText(String text) {
textButton.setText(text);
}
public void setTextColor(int color) {
textButton.setTextColor(color);
}
public TextView getTextView() {
return textButton;
}
public String getText() {
return textButton.getText().toString();
}
public void setTypeFace(Typeface typeFace) {
textButton.setTypeface(typeFace);
}
}
| |
/*
Copyright (c) 2012, 2014, Credit Suisse (Anatole Tresch), Werner Keil and others by the @author tag.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
*/
package org.javamoney.moneta.convert;
import javax.money.CurrencyUnit;
import javax.money.NumberValue;
import javax.money.convert.ConversionContext;
import javax.money.convert.ExchangeRate;
import javax.money.convert.RateType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* Builder for creating new instances of {@link javax.money.convert.ExchangeRate}. Note that
* instances of this class are not thread-safe.
*
* @author Anatole Tresch
* @author Werner Keil
*/
public class ExchangeRateBuilder {
/**
* The {@link javax.money.convert.ConversionContext}.
*/
ConversionContext conversionContext;
/**
* The base (source) currency.
*/
CurrencyUnit base;
/**
* The term (target) currency.
*/
CurrencyUnit term;
/**
* The conversion factor.
*/
NumberValue factor;
/**
* The chain of invovled rates.
*/
List<ExchangeRate> rateChain = new ArrayList<>();
/**
* Sets the exchange rate type
*
* @param rateType the {@link javax.money.convert.RateType} contained
*/
public ExchangeRateBuilder(String provider, RateType rateType) {
this(ConversionContext.of(provider, rateType));
}
/**
* Sets the exchange rate type
*
* @param context the {@link javax.money.convert.ConversionContext} to be applied
*/
public ExchangeRateBuilder(ConversionContext context) {
setContext(context);
}
/**
* Sets the exchange rate type
*
* @param rate the {@link javax.money.convert.ExchangeRate} to be applied
*/
public ExchangeRateBuilder(ExchangeRate rate) {
setContext(rate.getContext());
setFactor(rate.getFactor());
setTerm(rate.getCurrency());
setBase(rate.getBaseCurrency());
setRateChain(rate.getExchangeRateChain());
}
/**
* Sets the base {@link javax.money.CurrencyUnit}
*
* @param base to base (source) {@link javax.money.CurrencyUnit} to be applied
* @return the builder instance
*/
public ExchangeRateBuilder setBase(CurrencyUnit base) {
this.base = base;
return this;
}
/**
* Sets the terminating (target) {@link javax.money.CurrencyUnit}
*
* @param term to terminating {@link javax.money.CurrencyUnit} to be applied
* @return the builder instance
*/
public ExchangeRateBuilder setTerm(CurrencyUnit term) {
this.term = term;
return this;
}
/**
* Sets the {@link javax.money.convert.ExchangeRate} chain.
*
* @param exchangeRates the {@link javax.money.convert.ExchangeRate} chain to be applied
* @return the builder instance
*/
public ExchangeRateBuilder setRateChain(ExchangeRate... exchangeRates) {
this.rateChain.clear();
if (exchangeRates!=null) {
this.rateChain.addAll(Arrays.asList(exchangeRates.clone()));
}
return this;
}
/**
* Sets the {@link javax.money.convert.ExchangeRate} chain.
*
* @param exchangeRates the {@link javax.money.convert.ExchangeRate} chain to be applied
* @return the builder instance
*/
public ExchangeRateBuilder setRateChain(List<ExchangeRate> exchangeRates) {
this.rateChain.clear();
if (exchangeRates!=null) {
this.rateChain.addAll(exchangeRates);
}
return this;
}
/**
* Sets the conversion factor, as the factor
* {@code base * factor = target}.
*
* @param factor the factor.
* @return The builder instance.
*/
public ExchangeRateBuilder setFactor(NumberValue factor) {
this.factor = factor;
return this;
}
/**
* Sets the provider to be applied.
*
* @param conversionContext the {@link javax.money.convert.ConversionContext}, not null.
* @return The builder.
*/
public ExchangeRateBuilder setContext(ConversionContext conversionContext) {
Objects.requireNonNull(conversionContext);
this.conversionContext = conversionContext;
return this;
}
/**
* Builds a new instance of {@link javax.money.convert.ExchangeRate}.
*
* @return a new instance of {@link javax.money.convert.ExchangeRate}.
* @throws IllegalArgumentException if the rate could not be built.
*/
public ExchangeRate build() {
return new DefaultExchangeRate(this);
}
/**
* Initialize the {@link ExchangeRateBuilder} with an {@link javax.money.convert.ExchangeRate}. This is
* useful for creating a new rate, reusing some properties from an
* existing one.
*
* @param rate the base rate
* @return the Builder, for chaining.
*/
public ExchangeRateBuilder setRate(ExchangeRate rate) {
this.base = rate.getBaseCurrency();
this.term = rate.getCurrency();
this.conversionContext = rate.getContext();
this.factor = rate.getFactor();
this.rateChain = rate.getExchangeRateChain();
this.term = rate.getCurrency();
return this;
}
@Override
public String toString() {
String sb = "org.javamoney.moneta.ExchangeRateBuilder: " +
"[conversionContext" + conversionContext + ',' +
"base" + base + ',' +
"term" + term + ',' +
"factor" + factor + ',' +
"rateChain" + rateChain + ']';
return sb;
}
}
| |
/*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package oic.simulator.serviceprovider.view;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import oic.simulator.serviceprovider.Activator;
import oic.simulator.serviceprovider.listener.IObserverListChangedUIListener;
import oic.simulator.serviceprovider.listener.IResourceSelectionChangedUIListener;
import oic.simulator.serviceprovider.manager.ResourceManager;
import oic.simulator.serviceprovider.resource.ObserverDetail;
import oic.simulator.serviceprovider.resource.SimulatorResource;
import oic.simulator.serviceprovider.utils.Constants;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.part.ViewPart;
/**
* This class manages and shows the resource observer view in the perspective.
*/
public class ResourceObserverView extends ViewPart {
public static final String VIEW_ID = "oic.simulator.serviceprovider.view.observer";
private TableViewer tblViewer;
private final String[] columnHeaders = {
"Client Address", "Port", "Notify" };
private final Integer[] columnWidth = { 150, 75, 50 };
private IResourceSelectionChangedUIListener resourceSelectionChangedListener;
private IObserverListChangedUIListener resourceObserverListChangedListener;
private ResourceManager resourceManagerRef;
public ResourceObserverView() {
resourceManagerRef = Activator.getDefault().getResourceManager();
resourceSelectionChangedListener = new IResourceSelectionChangedUIListener() {
@Override
public void onResourceSelectionChange() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (null != tblViewer) {
changeButtonStatus();
updateViewer(getData(resourceManagerRef
.getCurrentResourceInSelection()));
}
}
});
}
};
resourceObserverListChangedListener = new IObserverListChangedUIListener() {
@Override
public void onObserverListChanged(final String resourceURI) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (null == resourceURI) {
return;
}
SimulatorResource resource = resourceManagerRef
.getCurrentResourceInSelection();
if (null == resource) {
return;
}
if (resource.getResourceURI().equals(resourceURI)) {
if (null != tblViewer) {
updateViewer(getData(resource));
}
}
}
});
}
};
}
private Map<Integer, ObserverDetail> getData(SimulatorResource resource) {
if (null == resource) {
return null;
}
return resource.getObserver();
}
private void updateViewer(Map<Integer, ObserverDetail> observer) {
if (null != tblViewer) {
Table tbl = tblViewer.getTable();
if (null != observer && observer.size() > 0) {
tblViewer.setInput(observer.entrySet().toArray());
if (!tbl.isDisposed()) {
tbl.setLinesVisible(true);
}
} else {
if (!tbl.isDisposed()) {
tbl.removeAll();
tbl.setLinesVisible(false);
}
}
}
}
@Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(1, false));
tblViewer = new TableViewer(parent, SWT.SINGLE | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
createColumns(tblViewer);
// make lines and header visible
final Table table = tblViewer.getTable();
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
table.setHeaderVisible(true);
table.setLinesVisible(true);
tblViewer.setContentProvider(new ObserverContentProvider());
addManagerListeners();
// Check whether there is any resource selected already
Map<Integer, ObserverDetail> observerList = getData(resourceManagerRef
.getCurrentResourceInSelection());
if (null != observerList) {
updateViewer(observerList);
}
}
public void createColumns(TableViewer tableViewer) {
TableViewerColumn addressColumn = new TableViewerColumn(tableViewer,
SWT.NONE);
addressColumn.getColumn().setWidth(columnWidth[0]);
addressColumn.getColumn().setText(columnHeaders[0]);
addressColumn.setLabelProvider(new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
if (element instanceof Map.Entry) {
@SuppressWarnings("unchecked")
Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
cell.setText(observer.getValue().getObserverInfo()
.getAddress());
}
}
});
TableViewerColumn portColumn = new TableViewerColumn(tableViewer,
SWT.NONE);
portColumn.getColumn().setWidth(columnWidth[1]);
portColumn.getColumn().setText(columnHeaders[1]);
portColumn.setLabelProvider(new StyledCellLabelProvider() {
@Override
public void update(ViewerCell cell) {
Object element = cell.getElement();
if (element instanceof Map.Entry) {
@SuppressWarnings("unchecked")
Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
cell.setText(String.valueOf(observer.getValue()
.getObserverInfo().getPort()));
}
}
});
TableViewerColumn notifyColumn = new TableViewerColumn(tableViewer,
SWT.NONE);
notifyColumn.getColumn().setWidth(columnWidth[2]);
notifyColumn.getColumn().setText(columnHeaders[2]);
notifyColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return "";
}
@Override
public Image getImage(Object element) {
@SuppressWarnings("unchecked")
Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
if (observer.getValue().isClicked()) {
return Activator.getDefault().getImageRegistry()
.get(Constants.NOTIFY_BUTTON_SELECTED);
}
return Activator.getDefault().getImageRegistry()
.get(Constants.NOTIFY_BUTTON_UNSELECTED);
}
});
notifyColumn.setEditingSupport(new NotifyEditor(tableViewer));
}
private void addManagerListeners() {
resourceManagerRef
.addResourceSelectionChangedUIListener(resourceSelectionChangedListener);
resourceManagerRef
.addObserverListChangedUIListener(resourceObserverListChangedListener);
}
class ObserverContentProvider implements IStructuredContentProvider {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer arg0, Object arg1, Object arg2) {
}
@Override
public Object[] getElements(Object element) {
return (Object[]) element;
}
}
class NotifyEditor extends EditingSupport {
private final TableViewer viewer;
public NotifyEditor(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
@Override
protected boolean canEdit(Object arg0) {
return true;
}
@Override
protected CellEditor getCellEditor(Object element) {
return new CheckboxCellEditor(null, SWT.CHECK | SWT.READ_ONLY);
}
@Override
protected Object getValue(Object element) {
System.out.println("getValue()");
@SuppressWarnings("unchecked")
Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
return observer.getValue().isClicked();
}
@Override
protected void setValue(Object element, Object value) {
System.out.println("setValue()");
// Change the button status of all the resources
changeButtonStatus();
@SuppressWarnings("unchecked")
Map.Entry<Integer, ObserverDetail> observer = (Map.Entry<Integer, ObserverDetail>) element;
observer.getValue().setClicked(true);
viewer.refresh();
// Call Native Method
resourceManagerRef.notifyObserverRequest(
resourceManagerRef.getCurrentResourceInSelection(),
observer.getValue().getObserverInfo().getId());
}
}
private void changeButtonStatus() {
SimulatorResource resource = resourceManagerRef
.getCurrentResourceInSelection();
if (null == resource) {
return;
}
Map<Integer, ObserverDetail> observerMap = resource.getObserver();
if (null == observerMap) {
return;
}
Set<Integer> keySet = observerMap.keySet();
Iterator<Integer> itr = keySet.iterator();
while (itr.hasNext()) {
observerMap.get(itr.next()).setClicked(false);
}
}
@Override
public void dispose() {
// Unregister the listener
if (null != resourceSelectionChangedListener) {
resourceManagerRef
.removeResourceSelectionChangedUIListener(resourceSelectionChangedListener);
}
if (null != resourceObserverListChangedListener) {
resourceManagerRef
.removeObserverListChangedUIListener(resourceObserverListChangedListener);
}
super.dispose();
}
@Override
public void setFocus() {
}
}
| |
/*
* Copyright 2005 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.reteoo;
import org.drools.core.base.evaluators.IsAEvaluatorDefinition;
import org.drools.core.common.InternalFactHandle;
import org.drools.core.common.InternalWorkingMemory;
import org.drools.core.common.RuleBasePartitionId;
import org.drools.core.reteoo.builder.BuildContext;
import org.drools.core.rule.constraint.EvaluatorConstraint;
import org.drools.core.rule.constraint.MvelConstraint;
import org.drools.core.spi.AlphaNodeFieldConstraint;
import org.drools.core.spi.PropagationContext;
import org.drools.core.util.bitmask.AllSetBitMask;
import org.drools.core.util.bitmask.BitMask;
import org.kie.api.definition.rule.Rule;
import org.kie.api.runtime.rule.Operator;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.List;
import static org.drools.core.reteoo.PropertySpecificUtil.allSetButTraitBitMask;
/**
* <code>AlphaNodes</code> are nodes in the <code>Rete</code> network used
* to apply <code>FieldConstraint<.code>s on asserted fact
* objects where the <code>FieldConstraint</code>s have no dependencies on any other of the facts in the current <code>Rule</code>.
*
* @see AlphaNodeFieldConstraint
*/
public class AlphaNode extends ObjectSource
implements
ObjectSinkNode {
private static final long serialVersionUID = 510l;
/**
* The <code>FieldConstraint</code>
*/
private AlphaNodeFieldConstraint constraint;
private ObjectSinkNode previousRightTupleSinkNode;
private ObjectSinkNode nextRightTupleSinkNode;
public AlphaNode() {
}
/**
* Construct an <code>AlphaNode</code> with a unique id using the provided
* <code>FieldConstraint</code> and the given <code>ObjectSource</code>.
* Set the boolean flag to true if the node is supposed to have local
* memory, or false otherwise. Memory is optional for <code>AlphaNode</code>s
* and is only of benefic when adding additional <code>Rule</code>s at runtime.
*
* @param id Node's ID
* @param constraint Node's constraints
* @param objectSource Node's object source
*/
public AlphaNode(final int id,
final AlphaNodeFieldConstraint constraint,
final ObjectSource objectSource,
final BuildContext context) {
super(id,
context.getPartitionId(),
context.getKnowledgeBase().getConfiguration().isMultithreadEvaluation(),
objectSource,
context.getKnowledgeBase().getConfiguration().getAlphaNodeHashingThreshold());
this.constraint = constraint.cloneIfInUse();
if (this.constraint instanceof MvelConstraint) {
((MvelConstraint) this.constraint).registerEvaluationContext(context);
}
initDeclaredMask(context);
hashcode = calculateHashCode();
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal(in);
constraint = (AlphaNodeFieldConstraint) in.readObject();
declaredMask = (BitMask) in.readObject();
inferredMask = (BitMask) in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeObject(constraint);
out.writeObject(declaredMask);
out.writeObject(inferredMask);
}
/**
* Retruns the <code>FieldConstraint</code>
*
* @return <code>FieldConstraint</code>
*/
public AlphaNodeFieldConstraint getConstraint() {
return this.constraint;
}
public short getType() {
return NodeTypeEnums.AlphaNode;
}
public void attach(BuildContext context) {
this.source.addObjectSink(this);
}
public void assertObject(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if (this.constraint.isAllowed(factHandle,
workingMemory)) {
this.sink.propagateAssertObject(factHandle,
context,
workingMemory);
}
}
public void modifyObject(final InternalFactHandle factHandle,
final ModifyPreviousTuples modifyPreviousTuples,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
if (context.getModificationMask().intersects(inferredMask)) {
if (this.constraint.isAllowed(factHandle, workingMemory)) {
this.sink.propagateModifyObject(factHandle,
modifyPreviousTuples,
context,
workingMemory);
}
} else {
byPassModifyToBetaNode(factHandle, modifyPreviousTuples, context, workingMemory);
}
}
public void byPassModifyToBetaNode(final InternalFactHandle factHandle,
final ModifyPreviousTuples modifyPreviousTuples,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
sink.byPassModifyToBetaNode(factHandle, modifyPreviousTuples, context, workingMemory);
}
public void updateSink(final ObjectSink sink,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
// get the objects from the parent
ObjectSinkUpdateAdapter adapter = new ObjectSinkUpdateAdapter(sink,
this.constraint);
this.source.updateSink(adapter,
context,
workingMemory);
}
public String toString() {
return "[AlphaNode(" + this.id + ") constraint=" + this.constraint + "]";
}
private int calculateHashCode() {
return (this.source != null ? this.source.hashCode() : 0) * 37 + (this.constraint != null ? this.constraint.hashCode() : 0) * 31;
}
@Override
public boolean equals(Object object) {
return this == object ||
(internalEquals((AlphaNode)object) &&
(this.source != null ?
this.source.thisNodeEquals(((AlphaNode) object).source) :
((AlphaNode) object).source == null) );
}
@Override
protected boolean internalEquals( Object object ) {
if ( object == null || !(object instanceof AlphaNode) || this.hashCode() != object.hashCode() ) {
return false;
}
return (constraint instanceof MvelConstraint ?
((MvelConstraint) constraint).equals(((AlphaNode)object).constraint, getKnowledgeBase()) :
constraint.equals(((AlphaNode)object).constraint));
}
/**
* Returns the next node
*
* @return The next ObjectSinkNode
*/
public ObjectSinkNode getNextObjectSinkNode() {
return this.nextRightTupleSinkNode;
}
/**
* Sets the next node
*
* @param next The next ObjectSinkNode
*/
public void setNextObjectSinkNode(final ObjectSinkNode next) {
this.nextRightTupleSinkNode = next;
}
/**
* Returns the previous node
*
* @return The previous ObjectSinkNode
*/
public ObjectSinkNode getPreviousObjectSinkNode() {
return this.previousRightTupleSinkNode;
}
/**
* Sets the previous node
*
* @param previous The previous ObjectSinkNode
*/
public void setPreviousObjectSinkNode(final ObjectSinkNode previous) {
this.previousRightTupleSinkNode = previous;
}
/**
* Used with the updateSink method, so that the parent ObjectSource
* can update the TupleSink
*/
private static class ObjectSinkUpdateAdapter
implements
ObjectSink {
private final ObjectSink sink;
private final AlphaNodeFieldConstraint constraint;
public ObjectSinkUpdateAdapter(final ObjectSink sink,
final AlphaNodeFieldConstraint constraint) {
this.sink = sink;
this.constraint = constraint;
}
public void assertObject(final InternalFactHandle handle,
final PropagationContext propagationContext,
final InternalWorkingMemory workingMemory) {
if (this.constraint.isAllowed(handle,
workingMemory)) {
this.sink.assertObject(handle,
propagationContext,
workingMemory);
}
}
public int getId() {
return 0;
}
public RuleBasePartitionId getPartitionId() {
return this.sink.getPartitionId();
}
public void writeExternal(ObjectOutput out) throws IOException {
// this is a short living adapter class, so no need for serialization
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
// this is a short living adapter class, so no need for serialization
}
public void modifyObject(final InternalFactHandle factHandle,
final ModifyPreviousTuples modifyPreviousTuples,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
throw new UnsupportedOperationException("This method should NEVER EVER be called");
}
public void byPassModifyToBetaNode(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory) {
}
public short getType() {
return NodeTypeEnums.AlphaNode;
}
public int getAssociationsSize() {
return sink.getAssociationsSize();
}
public int getAssociatedRuleSize() {
return sink.getAssociatedRuleSize();
}
public int getAssociationsSize(Rule rule) {
return sink.getAssociationsSize(rule);
}
public boolean isAssociatedWith(Rule rule) {
return sink.isAssociatedWith(rule);
}
public boolean thisNodeEquals(final Object object) {
return false;
}
public int nodeHashCode() {
return this.hashCode();
}
}
public BitMask calculateDeclaredMask(List<String> settableProperties) {
boolean typeBit = false;
if (constraint instanceof EvaluatorConstraint && ((EvaluatorConstraint) constraint).isSelf()) {
Operator op = ((EvaluatorConstraint) constraint).getEvaluator().getOperator();
if (op == IsAEvaluatorDefinition.ISA || op == IsAEvaluatorDefinition.NOT_ISA) {
typeBit = true;
}
}
if (settableProperties == null || !(constraint instanceof MvelConstraint)) {
return typeBit ? AllSetBitMask.get() : allSetButTraitBitMask();
}
BitMask mask = ((MvelConstraint) constraint).getListenedPropertyMask(settableProperties);
return typeBit ? mask.set(PropertySpecificUtil.TRAITABLE_BIT) : mask;
}
@Override
public BitMask getDeclaredMask() {
return declaredMask;
}
public BitMask getInferredMask() {
return inferredMask;
}
@Override
public void addObjectSink(final ObjectSink objectSink) {
super.addObjectSink(objectSink);
}
}
| |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.model;
import java.io.Serializable;
/**
* <p>
* Provides details of the <code>ChildWorkflowExecutionTerminated</code> event.
* </p>
*/
public class ChildWorkflowExecutionTerminatedEventAttributes implements
Serializable, Cloneable {
/**
* <p>
* The child workflow execution that was terminated.
* </p>
*/
private WorkflowExecution workflowExecution;
/**
* <p>
* The type of the child workflow execution.
* </p>
*/
private WorkflowType workflowType;
/**
* <p>
* The ID of the <code>StartChildWorkflowExecutionInitiated</code> event
* corresponding to the <code>StartChildWorkflowExecution</code> decision to
* start this child workflow execution. This information can be useful for
* diagnosing problems by tracing back the chain of events leading up to
* this event.
* </p>
*/
private Long initiatedEventId;
/**
* <p>
* The ID of the <code>ChildWorkflowExecutionStarted</code> event recorded
* when this child workflow execution was started. This information can be
* useful for diagnosing problems by tracing back the chain of events
* leading up to this event.
* </p>
*/
private Long startedEventId;
/**
* <p>
* The child workflow execution that was terminated.
* </p>
*
* @param workflowExecution
* The child workflow execution that was terminated.
*/
public void setWorkflowExecution(WorkflowExecution workflowExecution) {
this.workflowExecution = workflowExecution;
}
/**
* <p>
* The child workflow execution that was terminated.
* </p>
*
* @return The child workflow execution that was terminated.
*/
public WorkflowExecution getWorkflowExecution() {
return this.workflowExecution;
}
/**
* <p>
* The child workflow execution that was terminated.
* </p>
*
* @param workflowExecution
* The child workflow execution that was terminated.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ChildWorkflowExecutionTerminatedEventAttributes withWorkflowExecution(
WorkflowExecution workflowExecution) {
setWorkflowExecution(workflowExecution);
return this;
}
/**
* <p>
* The type of the child workflow execution.
* </p>
*
* @param workflowType
* The type of the child workflow execution.
*/
public void setWorkflowType(WorkflowType workflowType) {
this.workflowType = workflowType;
}
/**
* <p>
* The type of the child workflow execution.
* </p>
*
* @return The type of the child workflow execution.
*/
public WorkflowType getWorkflowType() {
return this.workflowType;
}
/**
* <p>
* The type of the child workflow execution.
* </p>
*
* @param workflowType
* The type of the child workflow execution.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ChildWorkflowExecutionTerminatedEventAttributes withWorkflowType(
WorkflowType workflowType) {
setWorkflowType(workflowType);
return this;
}
/**
* <p>
* The ID of the <code>StartChildWorkflowExecutionInitiated</code> event
* corresponding to the <code>StartChildWorkflowExecution</code> decision to
* start this child workflow execution. This information can be useful for
* diagnosing problems by tracing back the chain of events leading up to
* this event.
* </p>
*
* @param initiatedEventId
* The ID of the <code>StartChildWorkflowExecutionInitiated</code>
* event corresponding to the
* <code>StartChildWorkflowExecution</code> decision to start this
* child workflow execution. This information can be useful for
* diagnosing problems by tracing back the chain of events leading up
* to this event.
*/
public void setInitiatedEventId(Long initiatedEventId) {
this.initiatedEventId = initiatedEventId;
}
/**
* <p>
* The ID of the <code>StartChildWorkflowExecutionInitiated</code> event
* corresponding to the <code>StartChildWorkflowExecution</code> decision to
* start this child workflow execution. This information can be useful for
* diagnosing problems by tracing back the chain of events leading up to
* this event.
* </p>
*
* @return The ID of the <code>StartChildWorkflowExecutionInitiated</code>
* event corresponding to the
* <code>StartChildWorkflowExecution</code> decision to start this
* child workflow execution. This information can be useful for
* diagnosing problems by tracing back the chain of events leading
* up to this event.
*/
public Long getInitiatedEventId() {
return this.initiatedEventId;
}
/**
* <p>
* The ID of the <code>StartChildWorkflowExecutionInitiated</code> event
* corresponding to the <code>StartChildWorkflowExecution</code> decision to
* start this child workflow execution. This information can be useful for
* diagnosing problems by tracing back the chain of events leading up to
* this event.
* </p>
*
* @param initiatedEventId
* The ID of the <code>StartChildWorkflowExecutionInitiated</code>
* event corresponding to the
* <code>StartChildWorkflowExecution</code> decision to start this
* child workflow execution. This information can be useful for
* diagnosing problems by tracing back the chain of events leading up
* to this event.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ChildWorkflowExecutionTerminatedEventAttributes withInitiatedEventId(
Long initiatedEventId) {
setInitiatedEventId(initiatedEventId);
return this;
}
/**
* <p>
* The ID of the <code>ChildWorkflowExecutionStarted</code> event recorded
* when this child workflow execution was started. This information can be
* useful for diagnosing problems by tracing back the chain of events
* leading up to this event.
* </p>
*
* @param startedEventId
* The ID of the <code>ChildWorkflowExecutionStarted</code> event
* recorded when this child workflow execution was started. This
* information can be useful for diagnosing problems by tracing back
* the chain of events leading up to this event.
*/
public void setStartedEventId(Long startedEventId) {
this.startedEventId = startedEventId;
}
/**
* <p>
* The ID of the <code>ChildWorkflowExecutionStarted</code> event recorded
* when this child workflow execution was started. This information can be
* useful for diagnosing problems by tracing back the chain of events
* leading up to this event.
* </p>
*
* @return The ID of the <code>ChildWorkflowExecutionStarted</code> event
* recorded when this child workflow execution was started. This
* information can be useful for diagnosing problems by tracing back
* the chain of events leading up to this event.
*/
public Long getStartedEventId() {
return this.startedEventId;
}
/**
* <p>
* The ID of the <code>ChildWorkflowExecutionStarted</code> event recorded
* when this child workflow execution was started. This information can be
* useful for diagnosing problems by tracing back the chain of events
* leading up to this event.
* </p>
*
* @param startedEventId
* The ID of the <code>ChildWorkflowExecutionStarted</code> event
* recorded when this child workflow execution was started. This
* information can be useful for diagnosing problems by tracing back
* the chain of events leading up to this event.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ChildWorkflowExecutionTerminatedEventAttributes withStartedEventId(
Long startedEventId) {
setStartedEventId(startedEventId);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getWorkflowExecution() != null)
sb.append("WorkflowExecution: " + getWorkflowExecution() + ",");
if (getWorkflowType() != null)
sb.append("WorkflowType: " + getWorkflowType() + ",");
if (getInitiatedEventId() != null)
sb.append("InitiatedEventId: " + getInitiatedEventId() + ",");
if (getStartedEventId() != null)
sb.append("StartedEventId: " + getStartedEventId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ChildWorkflowExecutionTerminatedEventAttributes == false)
return false;
ChildWorkflowExecutionTerminatedEventAttributes other = (ChildWorkflowExecutionTerminatedEventAttributes) obj;
if (other.getWorkflowExecution() == null
^ this.getWorkflowExecution() == null)
return false;
if (other.getWorkflowExecution() != null
&& other.getWorkflowExecution().equals(
this.getWorkflowExecution()) == false)
return false;
if (other.getWorkflowType() == null ^ this.getWorkflowType() == null)
return false;
if (other.getWorkflowType() != null
&& other.getWorkflowType().equals(this.getWorkflowType()) == false)
return false;
if (other.getInitiatedEventId() == null
^ this.getInitiatedEventId() == null)
return false;
if (other.getInitiatedEventId() != null
&& other.getInitiatedEventId().equals(
this.getInitiatedEventId()) == false)
return false;
if (other.getStartedEventId() == null
^ this.getStartedEventId() == null)
return false;
if (other.getStartedEventId() != null
&& other.getStartedEventId().equals(this.getStartedEventId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getWorkflowExecution() == null) ? 0
: getWorkflowExecution().hashCode());
hashCode = prime
* hashCode
+ ((getWorkflowType() == null) ? 0 : getWorkflowType()
.hashCode());
hashCode = prime
* hashCode
+ ((getInitiatedEventId() == null) ? 0 : getInitiatedEventId()
.hashCode());
hashCode = prime
* hashCode
+ ((getStartedEventId() == null) ? 0 : getStartedEventId()
.hashCode());
return hashCode;
}
@Override
public ChildWorkflowExecutionTerminatedEventAttributes clone() {
try {
return (ChildWorkflowExecutionTerminatedEventAttributes) super
.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.ml.regressions;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.decompositions.QRDecomposition;
import org.apache.ignite.ml.math.exceptions.MathIllegalArgumentException;
import org.apache.ignite.ml.math.exceptions.SingularMatrixException;
import org.apache.ignite.ml.math.functions.Functions;
import org.apache.ignite.ml.math.util.MatrixUtil;
/**
* This class is based on the corresponding class from Apache Common Math lib.
* <p>Implements ordinary least squares (OLS) to estimate the parameters of a
* multiple linear regression model.</p>
*
* <p>The regression coefficients, <code>b</code>, satisfy the normal equations:
* <pre><code> X<sup>T</sup> X b = X<sup>T</sup> y </code></pre></p>
*
* <p>To solve the normal equations, this implementation uses QR decomposition
* of the <code>X</code> matrix. (See {@link QRDecomposition} for details on the
* decomposition algorithm.) The <code>X</code> matrix, also known as the <i>design matrix,</i>
* has rows corresponding to sample observations and columns corresponding to independent
* variables. When the model is estimated using an intercept term (i.e. when
* {@link #isNoIntercept() isNoIntercept} is false as it is by default), the <code>X</code>
* matrix includes an initial column identically equal to 1. We solve the normal equations
* as follows:
* <pre><code> X<sup>T</sup>X b = X<sup>T</sup> y
* (QR)<sup>T</sup> (QR) b = (QR)<sup>T</sup>y
* R<sup>T</sup> (Q<sup>T</sup>Q) R b = R<sup>T</sup> Q<sup>T</sup> y
* R<sup>T</sup> R b = R<sup>T</sup> Q<sup>T</sup> y
* (R<sup>T</sup>)<sup>-1</sup> R<sup>T</sup> R b = (R<sup>T</sup>)<sup>-1</sup> R<sup>T</sup> Q<sup>T</sup> y
* R b = Q<sup>T</sup> y </code></pre></p>
*
* <p>Given <code>Q</code> and <code>R</code>, the last equation is solved by back-substitution.</p>
*/
public class OLSMultipleLinearRegression extends AbstractMultipleLinearRegression {
/** Cached QR decomposition of X matrix */
private QRDecomposition qr = null;
/** Singularity threshold for QR decomposition */
private final double threshold;
/**
* Create an empty OLSMultipleLinearRegression instance.
*/
public OLSMultipleLinearRegression() {
this(0d);
}
/**
* Create an empty OLSMultipleLinearRegression instance, using the given
* singularity threshold for the QR decomposition.
*
* @param threshold the singularity threshold
*/
public OLSMultipleLinearRegression(final double threshold) {
this.threshold = threshold;
}
/**
* Loads model x and y sample data, overriding any previous sample.
*
* Computes and caches QR decomposition of the X matrix.
*
* @param y the {@code n}-sized vector representing the y sample
* @param x the {@code n x k} matrix representing the x sample
* @throws MathIllegalArgumentException if the x and y array data are not compatible for the regression
*/
public void newSampleData(Vector y, Matrix x) throws MathIllegalArgumentException {
validateSampleData(x, y);
newYSampleData(y);
newXSampleData(x);
}
/**
* {@inheritDoc}
* <p>This implementation computes and caches the QR decomposition of the X matrix.</p>
*/
@Override public void newSampleData(double[] data, int nobs, int nvars, Matrix like) {
super.newSampleData(data, nobs, nvars, like);
qr = new QRDecomposition(getX(), threshold);
}
/**
* <p>Compute the "hat" matrix.
* </p>
* <p>The hat matrix is defined in terms of the design matrix X
* by X(X<sup>T</sup>X)<sup>-1</sup>X<sup>T</sup>
* </p>
* <p>The implementation here uses the QR decomposition to compute the
* hat matrix as Q I<sub>p</sub>Q<sup>T</sup> where I<sub>p</sub> is the
* p-dimensional identity matrix augmented by 0's. This computational
* formula is from "The Hat Matrix in Regression and ANOVA",
* David C. Hoaglin and Roy E. Welsch,
* <i>The American Statistician</i>, Vol. 32, No. 1 (Feb., 1978), pp. 17-22.
* </p>
* <p>Data for the model must have been successfully loaded using one of
* the {@code newSampleData} methods before invoking this method; otherwise
* a {@code NullPointerException} will be thrown.</p>
*
* @return the hat matrix
* @throws NullPointerException unless method {@code newSampleData} has been called beforehand.
*/
public Matrix calculateHat() {
// Create augmented identity matrix
// No try-catch or advertised NotStrictlyPositiveException - NPE above if n < 3
Matrix q = qr.getQ();
Matrix augI = MatrixUtil.like(q, q.columnSize(), q.columnSize());
int n = augI.columnSize();
int p = qr.getR().columnSize();
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i == j && i < p)
augI.setX(i, j, 1d);
else
augI.setX(i, j, 0d);
// Compute and return Hat matrix
// No DME advertised - args valid if we get here
return q.times(augI).times(q.transpose());
}
/**
* <p>Returns the sum of squared deviations of Y from its mean.</p>
*
* <p>If the model has no intercept term, <code>0</code> is used for the
* mean of Y - i.e., what is returned is the sum of the squared Y values.</p>
*
* <p>The value returned by this method is the SSTO value used in
* the {@link #calculateRSquared() R-squared} computation.</p>
*
* @return SSTO - the total sum of squares
* @throws NullPointerException if the sample has not been set
* @see #isNoIntercept()
*/
public double calculateTotalSumOfSquares() {
if (isNoIntercept())
return getY().foldMap(Functions.PLUS, Functions.SQUARE, 0.0);
else {
// TODO: IGNITE-5826, think about incremental update formula.
final double mean = getY().sum() / getY().size();
return getY().foldMap(Functions.PLUS, x -> (mean - x) * (mean - x), 0.0);
}
}
/**
* Returns the sum of squared residuals.
*
* @return residual sum of squares
* @throws SingularMatrixException if the design matrix is singular
* @throws NullPointerException if the data for the model have not been loaded
*/
public double calculateResidualSumOfSquares() {
final Vector residuals = calculateResiduals();
// No advertised DME, args are valid
return residuals.dot(residuals);
}
/**
* Returns the R-Squared statistic, defined by the formula <pre>
* R<sup>2</sup> = 1 - SSR / SSTO
* </pre>
* where SSR is the {@link #calculateResidualSumOfSquares() sum of squared residuals}
* and SSTO is the {@link #calculateTotalSumOfSquares() total sum of squares}
*
* <p>If there is no variance in y, i.e., SSTO = 0, NaN is returned.</p>
*
* @return R-square statistic
* @throws NullPointerException if the sample has not been set
* @throws SingularMatrixException if the design matrix is singular
*/
public double calculateRSquared() {
return 1 - calculateResidualSumOfSquares() / calculateTotalSumOfSquares();
}
/**
* <p>Returns the adjusted R-squared statistic, defined by the formula <pre>
* R<sup>2</sup><sub>adj</sub> = 1 - [SSR (n - 1)] / [SSTO (n - p)]
* </pre>
* where SSR is the {@link #calculateResidualSumOfSquares() sum of squared residuals},
* SSTO is the {@link #calculateTotalSumOfSquares() total sum of squares}, n is the number
* of observations and p is the number of parameters estimated (including the intercept).</p>
*
* <p>If the regression is estimated without an intercept term, what is returned is <pre>
* <code> 1 - (1 - {@link #calculateRSquared()}) * (n / (n - p)) </code>
* </pre></p>
*
* <p>If there is no variance in y, i.e., SSTO = 0, NaN is returned.</p>
*
* @return adjusted R-Squared statistic
* @throws NullPointerException if the sample has not been set
* @throws SingularMatrixException if the design matrix is singular
* @see #isNoIntercept()
*/
public double calculateAdjustedRSquared() {
final double n = getX().rowSize();
if (isNoIntercept())
return 1 - (1 - calculateRSquared()) * (n / (n - getX().columnSize()));
else
return 1 - (calculateResidualSumOfSquares() * (n - 1)) /
(calculateTotalSumOfSquares() * (n - getX().columnSize()));
}
/**
* {@inheritDoc}
* <p>This implementation computes and caches the QR decomposition of the X matrix
* once it is successfully loaded.</p>
*/
@Override protected void newXSampleData(Matrix x) {
super.newXSampleData(x);
qr = new QRDecomposition(getX());
}
/**
* Calculates the regression coefficients using OLS.
*
* <p>Data for the model must have been successfully loaded using one of
* the {@code newSampleData} methods before invoking this method; otherwise
* a {@code NullPointerException} will be thrown.</p>
*
* @return beta
* @throws SingularMatrixException if the design matrix is singular
* @throws NullPointerException if the data for the model have not been loaded
*/
@Override protected Vector calculateBeta() {
return qr.solve(getY());
}
/**
* <p>Calculates the variance-covariance matrix of the regression parameters.
* </p>
* <p>Var(b) = (X<sup>T</sup>X)<sup>-1</sup>
* </p>
* <p>Uses QR decomposition to reduce (X<sup>T</sup>X)<sup>-1</sup>
* to (R<sup>T</sup>R)<sup>-1</sup>, with only the top p rows of
* R included, where p = the length of the beta vector.</p>
*
* <p>Data for the model must have been successfully loaded using one of
* the {@code newSampleData} methods before invoking this method; otherwise
* a {@code NullPointerException} will be thrown.</p>
*
* @return The beta variance-covariance matrix
* @throws SingularMatrixException if the design matrix is singular
* @throws NullPointerException if the data for the model have not been loaded
*/
@Override protected Matrix calculateBetaVariance() {
int p = getX().columnSize();
Matrix rAug = MatrixUtil.copy(qr.getR().viewPart(0, p, 0, p));
Matrix rInv = rAug.inverse();
return rInv.times(rInv.transpose());
}
}
| |
/*
* RESTful API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.logsentinel.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* AlertRuleRun
*/
public class AlertRuleRun {
@JsonProperty("actorIds")
private List<String> actorIds = null;
@JsonProperty("actualValue")
private Double actualValue = null;
@JsonProperty("affectedHosts")
private List<String> affectedHosts = null;
@JsonProperty("alertRuleId")
private UUID alertRuleId = null;
@JsonProperty("alertRuleName")
private String alertRuleName = null;
/**
* Gets or Sets alertType
*/
public enum AlertTypeEnum {
STATISTICAL("STATISTICAL"),
CORRELATION("CORRELATION"),
ANOMALY("ANOMALY"),
LOG_LEVEL_BASED("LOG_LEVEL_BASED"),
THREAT_INTEL_MATCH("THREAT_INTEL_MATCH"),
HEALTHCHECK("HEALTHCHECK"),
WEBSITE_STATIC_RESOURCE_CHANGE("WEBSITE_STATIC_RESOURCE_CHANGE");
private String value;
AlertTypeEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static AlertTypeEnum fromValue(String text) {
for (AlertTypeEnum b : AlertTypeEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
@JsonProperty("alertType")
private AlertTypeEnum alertType = null;
@JsonProperty("applicationName")
private String applicationName = null;
@JsonProperty("countryCodes")
private List<String> countryCodes = null;
@JsonProperty("created")
private LocalDateTime created = null;
@JsonProperty("details")
private String details = null;
@JsonProperty("domains")
private List<String> domains = null;
@JsonProperty("emails")
private List<String> emails = null;
@JsonProperty("entryIds")
private List<UUID> entryIds = null;
@JsonProperty("executionDuration")
private Long executionDuration = null;
@JsonProperty("externalIps")
private List<String> externalIps = null;
@JsonProperty("fileHashes")
private List<String> fileHashes = null;
@JsonProperty("fired")
private Boolean fired = null;
@JsonProperty("id")
private UUID id = null;
@JsonProperty("internalIps")
private List<String> internalIps = null;
@JsonProperty("ioc")
private List<String> ioc = null;
@JsonProperty("iocTypes")
private List<String> iocTypes = null;
@JsonProperty("notified")
private Boolean notified = null;
@JsonProperty("organizationId")
private UUID organizationId = null;
@JsonProperty("previousAlerts")
private Map<String, List<UUID>> previousAlerts = null;
@JsonProperty("resolutionTime")
private Long resolutionTime = null;
@JsonProperty("resultDisplayAggregationField")
private String resultDisplayAggregationField = null;
@JsonProperty("riskLevel")
private Integer riskLevel = null;
/**
* Gets or Sets status
*/
public enum StatusEnum {
NEW_ALERT("NEW_ALERT"),
IN_TRIAGE("IN_TRIAGE"),
CONFIRMED("CONFIRMED"),
RESOLVED("RESOLVED"),
DISMISSED("DISMISSED");
private String value;
StatusEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static StatusEnum fromValue(String text) {
for (StatusEnum b : StatusEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
@JsonProperty("status")
private StatusEnum status = null;
@JsonProperty("tags")
private List<String> tags = null;
@JsonProperty("threshold")
private Double threshold = null;
/**
* Gets or Sets thresholdType
*/
public enum ThresholdTypeEnum {
ABOVE("ABOVE"),
BELOW("BELOW"),
BOTH("BOTH");
private String value;
ThresholdTypeEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static ThresholdTypeEnum fromValue(String text) {
for (ThresholdTypeEnum b : ThresholdTypeEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
}
@JsonProperty("thresholdType")
private ThresholdTypeEnum thresholdType = null;
@JsonProperty("topFields")
private Map<String, Long> topFields = null;
@JsonProperty("topFieldsCount")
private Integer topFieldsCount = null;
@JsonProperty("triageStartTime")
private LocalDateTime triageStartTime = null;
@JsonProperty("urls")
private List<String> urls = null;
public AlertRuleRun actorIds(List<String> actorIds) {
this.actorIds = actorIds;
return this;
}
public AlertRuleRun addActorIdsItem(String actorIdsItem) {
if (this.actorIds == null) {
this.actorIds = new ArrayList<>();
}
this.actorIds.add(actorIdsItem);
return this;
}
/**
* Get actorIds
* @return actorIds
**/
@ApiModelProperty(value = "")
public List<String> getActorIds() {
return actorIds;
}
public void setActorIds(List<String> actorIds) {
this.actorIds = actorIds;
}
public AlertRuleRun actualValue(Double actualValue) {
this.actualValue = actualValue;
return this;
}
/**
* Get actualValue
* @return actualValue
**/
@ApiModelProperty(value = "")
public Double getActualValue() {
return actualValue;
}
public void setActualValue(Double actualValue) {
this.actualValue = actualValue;
}
public AlertRuleRun affectedHosts(List<String> affectedHosts) {
this.affectedHosts = affectedHosts;
return this;
}
public AlertRuleRun addAffectedHostsItem(String affectedHostsItem) {
if (this.affectedHosts == null) {
this.affectedHosts = new ArrayList<>();
}
this.affectedHosts.add(affectedHostsItem);
return this;
}
/**
* Get affectedHosts
* @return affectedHosts
**/
@ApiModelProperty(value = "")
public List<String> getAffectedHosts() {
return affectedHosts;
}
public void setAffectedHosts(List<String> affectedHosts) {
this.affectedHosts = affectedHosts;
}
public AlertRuleRun alertRuleId(UUID alertRuleId) {
this.alertRuleId = alertRuleId;
return this;
}
/**
* Get alertRuleId
* @return alertRuleId
**/
@ApiModelProperty(value = "")
public UUID getAlertRuleId() {
return alertRuleId;
}
public void setAlertRuleId(UUID alertRuleId) {
this.alertRuleId = alertRuleId;
}
public AlertRuleRun alertRuleName(String alertRuleName) {
this.alertRuleName = alertRuleName;
return this;
}
/**
* Get alertRuleName
* @return alertRuleName
**/
@ApiModelProperty(value = "")
public String getAlertRuleName() {
return alertRuleName;
}
public void setAlertRuleName(String alertRuleName) {
this.alertRuleName = alertRuleName;
}
public AlertRuleRun alertType(AlertTypeEnum alertType) {
this.alertType = alertType;
return this;
}
/**
* Get alertType
* @return alertType
**/
@ApiModelProperty(value = "")
public AlertTypeEnum getAlertType() {
return alertType;
}
public void setAlertType(AlertTypeEnum alertType) {
this.alertType = alertType;
}
public AlertRuleRun applicationName(String applicationName) {
this.applicationName = applicationName;
return this;
}
/**
* Get applicationName
* @return applicationName
**/
@ApiModelProperty(value = "")
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public AlertRuleRun countryCodes(List<String> countryCodes) {
this.countryCodes = countryCodes;
return this;
}
public AlertRuleRun addCountryCodesItem(String countryCodesItem) {
if (this.countryCodes == null) {
this.countryCodes = new ArrayList<>();
}
this.countryCodes.add(countryCodesItem);
return this;
}
/**
* Get countryCodes
* @return countryCodes
**/
@ApiModelProperty(value = "")
public List<String> getCountryCodes() {
return countryCodes;
}
public void setCountryCodes(List<String> countryCodes) {
this.countryCodes = countryCodes;
}
public AlertRuleRun created(LocalDateTime created) {
this.created = created;
return this;
}
/**
* Get created
* @return created
**/
@ApiModelProperty(value = "")
public LocalDateTime getCreated() {
return created;
}
public void setCreated(LocalDateTime created) {
this.created = created;
}
public AlertRuleRun details(String details) {
this.details = details;
return this;
}
/**
* Get details
* @return details
**/
@ApiModelProperty(value = "")
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public AlertRuleRun domains(List<String> domains) {
this.domains = domains;
return this;
}
public AlertRuleRun addDomainsItem(String domainsItem) {
if (this.domains == null) {
this.domains = new ArrayList<>();
}
this.domains.add(domainsItem);
return this;
}
/**
* Get domains
* @return domains
**/
@ApiModelProperty(value = "")
public List<String> getDomains() {
return domains;
}
public void setDomains(List<String> domains) {
this.domains = domains;
}
public AlertRuleRun emails(List<String> emails) {
this.emails = emails;
return this;
}
public AlertRuleRun addEmailsItem(String emailsItem) {
if (this.emails == null) {
this.emails = new ArrayList<>();
}
this.emails.add(emailsItem);
return this;
}
/**
* Get emails
* @return emails
**/
@ApiModelProperty(value = "")
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
public AlertRuleRun entryIds(List<UUID> entryIds) {
this.entryIds = entryIds;
return this;
}
public AlertRuleRun addEntryIdsItem(UUID entryIdsItem) {
if (this.entryIds == null) {
this.entryIds = new ArrayList<>();
}
this.entryIds.add(entryIdsItem);
return this;
}
/**
* Get entryIds
* @return entryIds
**/
@ApiModelProperty(value = "")
public List<UUID> getEntryIds() {
return entryIds;
}
public void setEntryIds(List<UUID> entryIds) {
this.entryIds = entryIds;
}
public AlertRuleRun executionDuration(Long executionDuration) {
this.executionDuration = executionDuration;
return this;
}
/**
* Get executionDuration
* @return executionDuration
**/
@ApiModelProperty(value = "")
public Long getExecutionDuration() {
return executionDuration;
}
public void setExecutionDuration(Long executionDuration) {
this.executionDuration = executionDuration;
}
public AlertRuleRun externalIps(List<String> externalIps) {
this.externalIps = externalIps;
return this;
}
public AlertRuleRun addExternalIpsItem(String externalIpsItem) {
if (this.externalIps == null) {
this.externalIps = new ArrayList<>();
}
this.externalIps.add(externalIpsItem);
return this;
}
/**
* Get externalIps
* @return externalIps
**/
@ApiModelProperty(value = "")
public List<String> getExternalIps() {
return externalIps;
}
public void setExternalIps(List<String> externalIps) {
this.externalIps = externalIps;
}
public AlertRuleRun fileHashes(List<String> fileHashes) {
this.fileHashes = fileHashes;
return this;
}
public AlertRuleRun addFileHashesItem(String fileHashesItem) {
if (this.fileHashes == null) {
this.fileHashes = new ArrayList<>();
}
this.fileHashes.add(fileHashesItem);
return this;
}
/**
* Get fileHashes
* @return fileHashes
**/
@ApiModelProperty(value = "")
public List<String> getFileHashes() {
return fileHashes;
}
public void setFileHashes(List<String> fileHashes) {
this.fileHashes = fileHashes;
}
public AlertRuleRun fired(Boolean fired) {
this.fired = fired;
return this;
}
/**
* Get fired
* @return fired
**/
@ApiModelProperty(value = "")
public Boolean isFired() {
return fired;
}
public void setFired(Boolean fired) {
this.fired = fired;
}
public AlertRuleRun id(UUID id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@ApiModelProperty(value = "")
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public AlertRuleRun internalIps(List<String> internalIps) {
this.internalIps = internalIps;
return this;
}
public AlertRuleRun addInternalIpsItem(String internalIpsItem) {
if (this.internalIps == null) {
this.internalIps = new ArrayList<>();
}
this.internalIps.add(internalIpsItem);
return this;
}
/**
* Get internalIps
* @return internalIps
**/
@ApiModelProperty(value = "")
public List<String> getInternalIps() {
return internalIps;
}
public void setInternalIps(List<String> internalIps) {
this.internalIps = internalIps;
}
public AlertRuleRun ioc(List<String> ioc) {
this.ioc = ioc;
return this;
}
public AlertRuleRun addIocItem(String iocItem) {
if (this.ioc == null) {
this.ioc = new ArrayList<>();
}
this.ioc.add(iocItem);
return this;
}
/**
* Get ioc
* @return ioc
**/
@ApiModelProperty(value = "")
public List<String> getIoc() {
return ioc;
}
public void setIoc(List<String> ioc) {
this.ioc = ioc;
}
public AlertRuleRun iocTypes(List<String> iocTypes) {
this.iocTypes = iocTypes;
return this;
}
public AlertRuleRun addIocTypesItem(String iocTypesItem) {
if (this.iocTypes == null) {
this.iocTypes = new ArrayList<>();
}
this.iocTypes.add(iocTypesItem);
return this;
}
/**
* Get iocTypes
* @return iocTypes
**/
@ApiModelProperty(value = "")
public List<String> getIocTypes() {
return iocTypes;
}
public void setIocTypes(List<String> iocTypes) {
this.iocTypes = iocTypes;
}
public AlertRuleRun notified(Boolean notified) {
this.notified = notified;
return this;
}
/**
* Get notified
* @return notified
**/
@ApiModelProperty(value = "")
public Boolean isNotified() {
return notified;
}
public void setNotified(Boolean notified) {
this.notified = notified;
}
public AlertRuleRun organizationId(UUID organizationId) {
this.organizationId = organizationId;
return this;
}
/**
* Get organizationId
* @return organizationId
**/
@ApiModelProperty(value = "")
public UUID getOrganizationId() {
return organizationId;
}
public void setOrganizationId(UUID organizationId) {
this.organizationId = organizationId;
}
public AlertRuleRun previousAlerts(Map<String, List<UUID>> previousAlerts) {
this.previousAlerts = previousAlerts;
return this;
}
public AlertRuleRun putPreviousAlertsItem(String key, List<UUID> previousAlertsItem) {
if (this.previousAlerts == null) {
this.previousAlerts = new HashMap<>();
}
this.previousAlerts.put(key, previousAlertsItem);
return this;
}
/**
* Get previousAlerts
* @return previousAlerts
**/
@ApiModelProperty(value = "")
public Map<String, List<UUID>> getPreviousAlerts() {
return previousAlerts;
}
public void setPreviousAlerts(Map<String, List<UUID>> previousAlerts) {
this.previousAlerts = previousAlerts;
}
public AlertRuleRun resolutionTime(Long resolutionTime) {
this.resolutionTime = resolutionTime;
return this;
}
/**
* Get resolutionTime
* @return resolutionTime
**/
@ApiModelProperty(value = "")
public Long getResolutionTime() {
return resolutionTime;
}
public void setResolutionTime(Long resolutionTime) {
this.resolutionTime = resolutionTime;
}
public AlertRuleRun resultDisplayAggregationField(String resultDisplayAggregationField) {
this.resultDisplayAggregationField = resultDisplayAggregationField;
return this;
}
/**
* Get resultDisplayAggregationField
* @return resultDisplayAggregationField
**/
@ApiModelProperty(value = "")
public String getResultDisplayAggregationField() {
return resultDisplayAggregationField;
}
public void setResultDisplayAggregationField(String resultDisplayAggregationField) {
this.resultDisplayAggregationField = resultDisplayAggregationField;
}
public AlertRuleRun riskLevel(Integer riskLevel) {
this.riskLevel = riskLevel;
return this;
}
/**
* Get riskLevel
* @return riskLevel
**/
@ApiModelProperty(value = "")
public Integer getRiskLevel() {
return riskLevel;
}
public void setRiskLevel(Integer riskLevel) {
this.riskLevel = riskLevel;
}
public AlertRuleRun status(StatusEnum status) {
this.status = status;
return this;
}
/**
* Get status
* @return status
**/
@ApiModelProperty(value = "")
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
public AlertRuleRun tags(List<String> tags) {
this.tags = tags;
return this;
}
public AlertRuleRun addTagsItem(String tagsItem) {
if (this.tags == null) {
this.tags = new ArrayList<>();
}
this.tags.add(tagsItem);
return this;
}
/**
* Get tags
* @return tags
**/
@ApiModelProperty(value = "")
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public AlertRuleRun threshold(Double threshold) {
this.threshold = threshold;
return this;
}
/**
* Get threshold
* @return threshold
**/
@ApiModelProperty(value = "")
public Double getThreshold() {
return threshold;
}
public void setThreshold(Double threshold) {
this.threshold = threshold;
}
public AlertRuleRun thresholdType(ThresholdTypeEnum thresholdType) {
this.thresholdType = thresholdType;
return this;
}
/**
* Get thresholdType
* @return thresholdType
**/
@ApiModelProperty(value = "")
public ThresholdTypeEnum getThresholdType() {
return thresholdType;
}
public void setThresholdType(ThresholdTypeEnum thresholdType) {
this.thresholdType = thresholdType;
}
public AlertRuleRun topFields(Map<String, Long> topFields) {
this.topFields = topFields;
return this;
}
public AlertRuleRun putTopFieldsItem(String key, Long topFieldsItem) {
if (this.topFields == null) {
this.topFields = new HashMap<>();
}
this.topFields.put(key, topFieldsItem);
return this;
}
/**
* Get topFields
* @return topFields
**/
@ApiModelProperty(value = "")
public Map<String, Long> getTopFields() {
return topFields;
}
public void setTopFields(Map<String, Long> topFields) {
this.topFields = topFields;
}
public AlertRuleRun topFieldsCount(Integer topFieldsCount) {
this.topFieldsCount = topFieldsCount;
return this;
}
/**
* Get topFieldsCount
* @return topFieldsCount
**/
@ApiModelProperty(value = "")
public Integer getTopFieldsCount() {
return topFieldsCount;
}
public void setTopFieldsCount(Integer topFieldsCount) {
this.topFieldsCount = topFieldsCount;
}
public AlertRuleRun triageStartTime(LocalDateTime triageStartTime) {
this.triageStartTime = triageStartTime;
return this;
}
/**
* Get triageStartTime
* @return triageStartTime
**/
@ApiModelProperty(value = "")
public LocalDateTime getTriageStartTime() {
return triageStartTime;
}
public void setTriageStartTime(LocalDateTime triageStartTime) {
this.triageStartTime = triageStartTime;
}
public AlertRuleRun urls(List<String> urls) {
this.urls = urls;
return this;
}
public AlertRuleRun addUrlsItem(String urlsItem) {
if (this.urls == null) {
this.urls = new ArrayList<>();
}
this.urls.add(urlsItem);
return this;
}
/**
* Get urls
* @return urls
**/
@ApiModelProperty(value = "")
public List<String> getUrls() {
return urls;
}
public void setUrls(List<String> urls) {
this.urls = urls;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AlertRuleRun alertRuleRun = (AlertRuleRun) o;
return Objects.equals(this.actorIds, alertRuleRun.actorIds) &&
Objects.equals(this.actualValue, alertRuleRun.actualValue) &&
Objects.equals(this.affectedHosts, alertRuleRun.affectedHosts) &&
Objects.equals(this.alertRuleId, alertRuleRun.alertRuleId) &&
Objects.equals(this.alertRuleName, alertRuleRun.alertRuleName) &&
Objects.equals(this.alertType, alertRuleRun.alertType) &&
Objects.equals(this.applicationName, alertRuleRun.applicationName) &&
Objects.equals(this.countryCodes, alertRuleRun.countryCodes) &&
Objects.equals(this.created, alertRuleRun.created) &&
Objects.equals(this.details, alertRuleRun.details) &&
Objects.equals(this.domains, alertRuleRun.domains) &&
Objects.equals(this.emails, alertRuleRun.emails) &&
Objects.equals(this.entryIds, alertRuleRun.entryIds) &&
Objects.equals(this.executionDuration, alertRuleRun.executionDuration) &&
Objects.equals(this.externalIps, alertRuleRun.externalIps) &&
Objects.equals(this.fileHashes, alertRuleRun.fileHashes) &&
Objects.equals(this.fired, alertRuleRun.fired) &&
Objects.equals(this.id, alertRuleRun.id) &&
Objects.equals(this.internalIps, alertRuleRun.internalIps) &&
Objects.equals(this.ioc, alertRuleRun.ioc) &&
Objects.equals(this.iocTypes, alertRuleRun.iocTypes) &&
Objects.equals(this.notified, alertRuleRun.notified) &&
Objects.equals(this.organizationId, alertRuleRun.organizationId) &&
Objects.equals(this.previousAlerts, alertRuleRun.previousAlerts) &&
Objects.equals(this.resolutionTime, alertRuleRun.resolutionTime) &&
Objects.equals(this.resultDisplayAggregationField, alertRuleRun.resultDisplayAggregationField) &&
Objects.equals(this.riskLevel, alertRuleRun.riskLevel) &&
Objects.equals(this.status, alertRuleRun.status) &&
Objects.equals(this.tags, alertRuleRun.tags) &&
Objects.equals(this.threshold, alertRuleRun.threshold) &&
Objects.equals(this.thresholdType, alertRuleRun.thresholdType) &&
Objects.equals(this.topFields, alertRuleRun.topFields) &&
Objects.equals(this.topFieldsCount, alertRuleRun.topFieldsCount) &&
Objects.equals(this.triageStartTime, alertRuleRun.triageStartTime) &&
Objects.equals(this.urls, alertRuleRun.urls);
}
@Override
public int hashCode() {
return Objects.hash(actorIds, actualValue, affectedHosts, alertRuleId, alertRuleName, alertType, applicationName, countryCodes, created, details, domains, emails, entryIds, executionDuration, externalIps, fileHashes, fired, id, internalIps, ioc, iocTypes, notified, organizationId, previousAlerts, resolutionTime, resultDisplayAggregationField, riskLevel, status, tags, threshold, thresholdType, topFields, topFieldsCount, triageStartTime, urls);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AlertRuleRun {\n");
sb.append(" actorIds: ").append(toIndentedString(actorIds)).append("\n");
sb.append(" actualValue: ").append(toIndentedString(actualValue)).append("\n");
sb.append(" affectedHosts: ").append(toIndentedString(affectedHosts)).append("\n");
sb.append(" alertRuleId: ").append(toIndentedString(alertRuleId)).append("\n");
sb.append(" alertRuleName: ").append(toIndentedString(alertRuleName)).append("\n");
sb.append(" alertType: ").append(toIndentedString(alertType)).append("\n");
sb.append(" applicationName: ").append(toIndentedString(applicationName)).append("\n");
sb.append(" countryCodes: ").append(toIndentedString(countryCodes)).append("\n");
sb.append(" created: ").append(toIndentedString(created)).append("\n");
sb.append(" details: ").append(toIndentedString(details)).append("\n");
sb.append(" domains: ").append(toIndentedString(domains)).append("\n");
sb.append(" emails: ").append(toIndentedString(emails)).append("\n");
sb.append(" entryIds: ").append(toIndentedString(entryIds)).append("\n");
sb.append(" executionDuration: ").append(toIndentedString(executionDuration)).append("\n");
sb.append(" externalIps: ").append(toIndentedString(externalIps)).append("\n");
sb.append(" fileHashes: ").append(toIndentedString(fileHashes)).append("\n");
sb.append(" fired: ").append(toIndentedString(fired)).append("\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" internalIps: ").append(toIndentedString(internalIps)).append("\n");
sb.append(" ioc: ").append(toIndentedString(ioc)).append("\n");
sb.append(" iocTypes: ").append(toIndentedString(iocTypes)).append("\n");
sb.append(" notified: ").append(toIndentedString(notified)).append("\n");
sb.append(" organizationId: ").append(toIndentedString(organizationId)).append("\n");
sb.append(" previousAlerts: ").append(toIndentedString(previousAlerts)).append("\n");
sb.append(" resolutionTime: ").append(toIndentedString(resolutionTime)).append("\n");
sb.append(" resultDisplayAggregationField: ").append(toIndentedString(resultDisplayAggregationField)).append("\n");
sb.append(" riskLevel: ").append(toIndentedString(riskLevel)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" threshold: ").append(toIndentedString(threshold)).append("\n");
sb.append(" thresholdType: ").append(toIndentedString(thresholdType)).append("\n");
sb.append(" topFields: ").append(toIndentedString(topFields)).append("\n");
sb.append(" topFieldsCount: ").append(toIndentedString(topFieldsCount)).append("\n");
sb.append(" triageStartTime: ").append(toIndentedString(triageStartTime)).append("\n");
sb.append(" urls: ").append(toIndentedString(urls)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| |
/*
* Copyright 2016 The OpenYOLO Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openyolo.demoprovider.barbican.storage;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.openyolo.demoprovider.barbican.CredentialListActivity;
import org.openyolo.demoprovider.barbican.LockActivity;
import org.openyolo.demoprovider.barbican.Protobufs.AccountHint;
import org.openyolo.demoprovider.barbican.R;
import org.openyolo.protocol.AuthenticationDomain;
import org.openyolo.protocol.Protobufs.Credential;
/**
* A service which retains an instance of {@link CredentialStorage} beyond the lifecycle of the
* activities that interact with it. This reduces the frequency at which the user would have
* to enter their password to unlock the keystore.
*/
public class CredentialStorageService extends Service implements CredentialStorageApi {
private static final String LOG_TAG = "CredentialStorage";
private static final int UNLOCKED_NOTIFICATION_ID = 1;
private final IBinder mLocalBinder = new LocalBinder();
private CredentialStorage mStorage;
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.d(LOG_TAG, "enter onBind");
return mLocalBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "enter onCreate");
try {
mStorage = new CredentialStorage(this);
} catch (IOException ex) {
Log.wtf(LOG_TAG, "Failed to open credential storage", ex);
return;
}
Log.d(LOG_TAG, "after create storage");
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public boolean isCreated() {
return mStorage.isCreated();
}
@Override
public void create(final String password) throws IOException {
mStorage.create(password);
becomeForeground();
}
@Override
public boolean isUnlocked() {
return mStorage.isUnlocked();
}
@Override
public boolean unlock(String password) throws IOException {
if (mStorage.unlock(password)) {
// when unlocked, we become foreground in order to retain the unlock key for longer,
// and also to notify the user of the associated security risk.
becomeForeground();
return true;
}
return false;
}
@Override
public void lock() {
if (!mStorage.isUnlocked()) {
return;
}
mStorage.lock();
stopForeground(true);
}
@Override
public boolean isOnNeverSaveList(List<AuthenticationDomain> authDomains) throws IOException {
return mStorage.isOnNeverSaveList(authDomains);
}
@Override
public void addToNeverSaveList(AuthenticationDomain authDomain) throws IOException {
mStorage.addToNeverSaveList(authDomain);
}
@Override
public void removeFromNeverSaveList(List<AuthenticationDomain> authDomains) throws IOException {
mStorage.removeFromNeverSaveList(authDomains);
}
@Override
public List<String> getNeverSaveList() throws IOException {
return mStorage.retrieveNeverSaveList();
}
@Override
public void clearNeverSaveList() throws IOException {
mStorage.clearNeverSaveList();
}
@Override
public List<AccountHint> getHints() throws IOException {
return mStorage.getHints();
}
@Override
public boolean hasCredentialFor(String authDomain) throws IOException {
return mStorage.hasCredentialFor(authDomain);
}
@Override
public boolean hasCredential(Credential credential) throws IOException {
return mStorage.hasCredential(credential);
}
@Override
public List<Credential> listCredentials(List<AuthenticationDomain> authDomains)
throws IOException {
checkUnlocked();
ArrayList<Credential> matchingCredentials = new ArrayList<>();
for (AuthenticationDomain domain : authDomains) {
matchingCredentials.addAll(mStorage.listCredentials(domain.toString()));
}
return matchingCredentials;
}
@Override
public List<Credential> listAllCredentials() throws IOException {
checkUnlocked();
return mStorage.listAllCredentials();
}
@Override
public void upsertCredential(Credential credential) throws IOException {
checkUnlocked();
mStorage.upsertCredential(credential);
}
@Override
public void deleteCredential(Credential credential) throws IOException {
mStorage.deleteCredential(credential);
}
private void becomeForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.unlocked_notification_icon)
.setContentTitle(getString(R.string.unlocked_notification_title))
.setContentText(getString(R.string.unlocked_notification_text))
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setContentIntent(PendingIntent.getActivity(
this, 0, new Intent(this, CredentialListActivity.class), 0))
.addAction(
R.drawable.lock_notification_icon,
getString(R.string.unlocked_notification_lock_action),
PendingIntent.getActivity(
this, 0, new Intent(this, LockActivity.class), 0
))
.setLocalOnly(true)
.setAutoCancel(false)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build();
startForeground(UNLOCKED_NOTIFICATION_ID, notification);
}
private void checkUnlocked() {
if (!mStorage.isUnlocked()) {
throw new IllegalStateException("Storage is locked");
}
}
class LocalBinder extends Binder {
CredentialStorageApi getApi() {
return CredentialStorageService.this;
}
}
}
| |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.bluetooth.btservice;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothDevice;
import com.android.bluetooth.a2dp.A2dpService;
import com.android.bluetooth.hid.HidService;
import com.android.bluetooth.hfp.HeadsetService;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.os.UserHandle;
import android.util.Log;
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import java.util.ArrayList;
/**
* This state machine handles Bluetooth Adapter State.
* States:
* {@link StableState} : No device is in bonding / unbonding state.
* {@link PendingCommandState} : Some device is in bonding / unbonding state.
* TODO(BT) This class can be removed and this logic moved to the stack.
*/
final class BondStateMachine extends StateMachine {
private static final boolean DBG = false;
private static final String TAG = "BluetoothBondStateMachine";
static final int CREATE_BOND = 1;
static final int CANCEL_BOND = 2;
static final int REMOVE_BOND = 3;
static final int BONDING_STATE_CHANGE = 4;
static final int BOND_STATE_NONE = 0;
static final int BOND_STATE_BONDING = 1;
static final int BOND_STATE_BONDED = 2;
private AdapterService mAdapterService;
private AdapterProperties mAdapterProperties;
private RemoteDevices mRemoteDevices;
private BluetoothAdapter mAdapter;
private PendingCommandState mPendingCommandState = new PendingCommandState();
private StableState mStableState = new StableState();
private BondStateMachine(AdapterService service,
AdapterProperties prop, RemoteDevices remoteDevices) {
super("BondStateMachine:");
addState(mStableState);
addState(mPendingCommandState);
mRemoteDevices = remoteDevices;
mAdapterService = service;
mAdapterProperties = prop;
mAdapter = BluetoothAdapter.getDefaultAdapter();
setInitialState(mStableState);
}
public static BondStateMachine make(AdapterService service,
AdapterProperties prop, RemoteDevices remoteDevices) {
Log.d(TAG, "make");
BondStateMachine bsm = new BondStateMachine(service, prop, remoteDevices);
bsm.start();
return bsm;
}
public void doQuit() {
quitNow();
}
public void cleanup() {
mAdapterService = null;
mRemoteDevices = null;
mAdapterProperties = null;
}
private class StableState extends State {
@Override
public void enter() {
infoLog("StableState(): Entering Off State");
}
@Override
public boolean processMessage(Message msg) {
BluetoothDevice dev = (BluetoothDevice)msg.obj;
switch(msg.what) {
case CREATE_BOND:
createBond(dev, true);
break;
case REMOVE_BOND:
removeBond(dev, true);
break;
case BONDING_STATE_CHANGE:
int newState = msg.arg1;
/* if incoming pairing, transition to pending state */
if (newState == BluetoothDevice.BOND_BONDING)
{
sendIntent(dev, newState, 0);
transitionTo(mPendingCommandState);
}
else
{
Log.e(TAG, "In stable state, received invalid newState: " + newState);
}
break;
case CANCEL_BOND:
default:
Log.e(TAG, "Received unhandled state: " + msg.what);
return false;
}
return true;
}
}
private class PendingCommandState extends State {
private final ArrayList<BluetoothDevice> mDevices =
new ArrayList<BluetoothDevice>();
@Override
public void enter() {
infoLog("Entering PendingCommandState State");
BluetoothDevice dev = (BluetoothDevice)getCurrentMessage().obj;
}
@Override
public boolean processMessage(Message msg) {
BluetoothDevice dev = (BluetoothDevice)msg.obj;
boolean result = false;
if (mDevices.contains(dev) &&
msg.what != CANCEL_BOND && msg.what != BONDING_STATE_CHANGE) {
deferMessage(msg);
return true;
}
switch (msg.what) {
case CREATE_BOND:
result = createBond(dev, false);
break;
case REMOVE_BOND:
result = removeBond(dev, false);
break;
case CANCEL_BOND:
result = cancelBond(dev);
break;
case BONDING_STATE_CHANGE:
int newState = msg.arg1;
int reason = getUnbondReasonFromHALCode(msg.arg2);
sendIntent(dev, newState, reason);
if(newState != BluetoothDevice.BOND_BONDING )
{
/* this is either none/bonded, remove and transition */
result = !mDevices.remove(dev);
if (mDevices.isEmpty()) {
// Whenever mDevices is empty, then we need to
// set result=false. Else, we will end up adding
// the device to the list again. This prevents us
// from pairing with a device that we just unpaired
result = false;
transitionTo(mStableState);
}
if (newState == BluetoothDevice.BOND_NONE)
{
// Set the profile Priorities to undefined
clearProfilePriorty(dev);
}
else if (newState == BluetoothDevice.BOND_BONDED)
{
// Restore the profile priorty settings
setProfilePriorty(dev);
}
}
else if(!mDevices.contains(dev))
result=true;
break;
default:
Log.e(TAG, "Received unhandled event:" + msg.what);
return false;
}
if (result) mDevices.add(dev);
return true;
}
}
private boolean cancelBond(BluetoothDevice dev) {
if (dev.getBondState() == BluetoothDevice.BOND_BONDING) {
byte[] addr = Utils.getBytesFromAddress(dev.getAddress());
if (!mAdapterService.cancelBondNative(addr)) {
Log.e(TAG, "Unexpected error while cancelling bond:");
} else {
return true;
}
}
return false;
}
private boolean removeBond(BluetoothDevice dev, boolean transition) {
if (dev.getBondState() == BluetoothDevice.BOND_BONDED) {
byte[] addr = Utils.getBytesFromAddress(dev.getAddress());
if (!mAdapterService.removeBondNative(addr)) {
Log.e(TAG, "Unexpected error while removing bond:");
} else {
if (transition) transitionTo(mPendingCommandState);
return true;
}
}
return false;
}
private boolean createBond(BluetoothDevice dev, boolean transition) {
if (dev.getBondState() == BluetoothDevice.BOND_NONE) {
infoLog("Bond address is:" + dev);
byte[] addr = Utils.getBytesFromAddress(dev.getAddress());
if (!mAdapterService.createBondNative(addr)) {
sendIntent(dev, BluetoothDevice.BOND_NONE,
BluetoothDevice.UNBOND_REASON_REMOVED);
return false;
} else if (transition) {
transitionTo(mPendingCommandState);
}
return true;
}
return false;
}
private void sendIntent(BluetoothDevice device, int newState, int reason) {
DeviceProperties devProp = mRemoteDevices.getDeviceProperties(device);
int oldState = BluetoothDevice.BOND_NONE;
if (devProp != null) {
oldState = devProp.getBondState();
}
if (oldState == newState) return;
mAdapterProperties.onBondStateChanged(device, newState);
Intent intent = new Intent(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.putExtra(BluetoothDevice.EXTRA_BOND_STATE, newState);
intent.putExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, oldState);
if (newState == BluetoothDevice.BOND_NONE)
intent.putExtra(BluetoothDevice.EXTRA_REASON, reason);
mAdapterService.sendBroadcastAsUser(intent, UserHandle.ALL,
AdapterService.BLUETOOTH_PERM);
infoLog("Bond State Change Intent:" + device + " OldState: " + oldState
+ " NewState: " + newState);
}
void bondStateChangeCallback(int status, byte[] address, int newState) {
BluetoothDevice device = mRemoteDevices.getDevice(address);
if (device == null) {
infoLog("No record of the device:" + device);
// This device will be added as part of the BONDING_STATE_CHANGE intent processing
// in sendIntent above
device = mAdapter.getRemoteDevice(Utils.getAddressStringFromByte(address));
}
infoLog("bondStateChangeCallback: Status: " + status + " Address: " + device
+ " newState: " + newState);
Message msg = obtainMessage(BONDING_STATE_CHANGE);
msg.obj = device;
if (newState == BOND_STATE_BONDED)
msg.arg1 = BluetoothDevice.BOND_BONDED;
else if (newState == BOND_STATE_BONDING)
msg.arg1 = BluetoothDevice.BOND_BONDING;
else
msg.arg1 = BluetoothDevice.BOND_NONE;
msg.arg2 = status;
sendMessage(msg);
}
private void setProfilePriorty (BluetoothDevice device){
HidService hidService = HidService.getHidService();
A2dpService a2dpService = A2dpService.getA2dpService();
HeadsetService headsetService = HeadsetService.getHeadsetService();
if ((hidService != null) &&
(hidService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){
hidService.setPriority(device,BluetoothProfile.PRIORITY_ON);
}
if ((a2dpService != null) &&
(a2dpService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){
a2dpService.setPriority(device,BluetoothProfile.PRIORITY_ON);
}
if ((headsetService != null) &&
(headsetService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){
headsetService.setPriority(device,BluetoothProfile.PRIORITY_ON);
}
}
private void clearProfilePriorty (BluetoothDevice device){
HidService hidService = HidService.getHidService();
A2dpService a2dpService = A2dpService.getA2dpService();
HeadsetService headsetService = HeadsetService.getHeadsetService();
if (hidService != null)
hidService.setPriority(device,BluetoothProfile.PRIORITY_UNDEFINED);
if(a2dpService != null)
a2dpService.setPriority(device,BluetoothProfile.PRIORITY_UNDEFINED);
if(headsetService != null)
headsetService.setPriority(device,BluetoothProfile.PRIORITY_UNDEFINED);
}
private void infoLog(String msg) {
Log.i(TAG, msg);
}
private void errorLog(String msg) {
Log.e(TAG, msg);
}
private int getUnbondReasonFromHALCode (int reason) {
if (reason == AbstractionLayer.BT_STATUS_SUCCESS)
return BluetoothDevice.BOND_SUCCESS;
else if (reason == AbstractionLayer.BT_STATUS_RMT_DEV_DOWN)
return BluetoothDevice.UNBOND_REASON_REMOTE_DEVICE_DOWN;
else if (reason == AbstractionLayer.BT_STATUS_AUTH_FAILURE)
return BluetoothDevice.UNBOND_REASON_AUTH_FAILED;
else if (reason == AbstractionLayer.BT_STATUS_AUTH_REJECTED)
return BluetoothDevice.UNBOND_REASON_AUTH_REJECTED;
else if (reason == AbstractionLayer.BT_STATUS_AUTH_TIMEOUT)
return BluetoothDevice.UNBOND_REASON_AUTH_TIMEOUT;
/* default */
return BluetoothDevice.UNBOND_REASON_REMOVED;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.distributed.near;
import java.util.Collection;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture;
import org.apache.ignite.internal.processors.cache.transactions.IgniteTxEntry;
import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey;
import org.apache.ignite.internal.transactions.IgniteTxRollbackCheckedException;
import org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException;
import org.apache.ignite.internal.util.GridConcurrentHashSet;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.jetbrains.annotations.Nullable;
/**
*
*/
public abstract class GridNearOptimisticTxPrepareFutureAdapter extends GridNearTxPrepareFutureAdapter {
/** */
private static final long serialVersionUID = 7460376140787916619L;
/** */
@GridToStringExclude
protected KeyLockFuture keyLockFut;
/**
* @param cctx Context.
* @param tx Transaction.
*/
protected GridNearOptimisticTxPrepareFutureAdapter(GridCacheSharedContext cctx, GridNearTxLocal tx) {
super(cctx, tx);
assert tx.optimistic() : tx;
if (tx.timeout() > 0) {
// Init keyLockFut to make sure it is created when {@link #onNearTxLocalTimeout} is called.
for (IgniteTxEntry e : tx.writeEntries()) {
if (e.context().isNear() || e.context().isLocal()) {
keyLockFut = new KeyLockFuture();
break;
}
}
if (tx.serializable() && keyLockFut == null) {
for (IgniteTxEntry e : tx.readEntries()) {
if (e.context().isNear() || e.context().isLocal()) {
keyLockFut = new KeyLockFuture();
break;
}
}
}
if (keyLockFut != null)
add((IgniteInternalFuture)keyLockFut);
}
}
/** {@inheritDoc} */
@Override public final void onNearTxLocalTimeout() {
if (keyLockFut != null && !keyLockFut.isDone()) {
ERR_UPD.compareAndSet(this, null, new IgniteTxTimeoutCheckedException("Failed to acquire lock " +
"within provided timeout for transaction [timeout=" + tx.timeout() + ", tx=" + tx + ']'));
keyLockFut.onDone();
}
}
/** {@inheritDoc} */
@Override public final void prepare() {
// Obtain the topology version to use.
long threadId = Thread.currentThread().getId();
AffinityTopologyVersion topVer = cctx.mvcc().lastExplicitLockTopologyVersion(threadId);
// If there is another system transaction in progress, use it's topology version to prevent deadlock.
if (topVer == null && tx.system()) {
topVer = cctx.tm().lockedTopologyVersion(threadId, tx);
if (topVer == null)
topVer = tx.topologyVersionSnapshot();
}
if (topVer != null) {
tx.topologyVersion(topVer);
cctx.mvcc().addFuture(this);
prepare0(false, true);
return;
}
prepareOnTopology(false, null);
}
/**
* Acquires topology read lock.
*
* @return Topology ready future.
*/
protected final GridDhtTopologyFuture topologyReadLock() {
return tx.txState().topologyReadLock(cctx, this);
}
/**
* Releases topology read lock.
*/
protected final void topologyReadUnlock() {
tx.txState().topologyReadUnlock(cctx);
}
/**
* @param remap Remap flag.
* @param c Optional closure to run after map.
*/
protected final void prepareOnTopology(final boolean remap, @Nullable final Runnable c) {
GridDhtTopologyFuture topFut = topologyReadLock();
AffinityTopologyVersion topVer = null;
try {
if (topFut == null) {
assert isDone();
return;
}
if (topFut.isDone()) {
if ((topVer = topFut.topologyVersion()) == null && topFut.error() != null) {
onDone(topFut.error()); // Prevent stack overflow if topFut has error.
return;
}
if (remap)
tx.onRemap(topVer, true);
else
tx.topologyVersion(topVer);
if (!remap)
cctx.mvcc().addFuture(this);
}
}
finally {
topologyReadUnlock();
}
if (topVer != null) {
IgniteCheckedException err = tx.txState().validateTopology(
cctx,
tx.writeMap().isEmpty(),
topFut);
if (err != null) {
onDone(err);
return;
}
if (tx.isRollbackOnly()) {
onDone(new IgniteTxRollbackCheckedException(
"Failed to prepare the transaction, due to the transaction is marked as rolled back " +
"[tx=" + CU.txString(tx) + ']'));
return;
}
prepare0(remap, false);
if (c != null)
c.run();
}
else {
cctx.time().waitAsync(topFut, tx.remainingTime(), (e, timedOut) -> {
if (errorOrTimeoutOnTopologyVersion(e, timedOut))
return;
try {
if (tx.isRollbackOnly()) {
onDone(new IgniteTxRollbackCheckedException(
"Failed to prepare the transaction, due to the transaction is marked as rolled back " +
"[tx=" + CU.txString(tx) + ']'));
return;
}
prepareOnTopology(remap, c);
}
finally {
cctx.txContextReset();
}
});
}
}
/**
* @param remap Remap flag.
* @param topLocked {@code True} if thread already acquired lock preventing topology change.
*/
protected abstract void prepare0(boolean remap, boolean topLocked);
/**
* @param e Exception.
* @param timedOut {@code True} if timed out.
*/
protected boolean errorOrTimeoutOnTopologyVersion(IgniteCheckedException e, boolean timedOut) {
if (e != null || timedOut) {
if (timedOut)
e = tx.timeoutException();
ERR_UPD.compareAndSet(this, null, e);
onDone(e);
return true;
}
return false;
}
/**
* Keys lock future.
*/
protected static class KeyLockFuture extends GridFutureAdapter<Void> {
/** */
@GridToStringInclude
protected Collection<IgniteTxKey> lockKeys = new GridConcurrentHashSet<>();
/** */
protected volatile boolean allKeysAdded;
/**
* @param key Key to track for locking.
*/
protected void addLockKey(IgniteTxKey key) {
assert !allKeysAdded;
lockKeys.add(key);
}
/**
* @param key Locked keys.
*/
protected void onKeyLocked(IgniteTxKey key) {
lockKeys.remove(key);
checkLocks();
}
/**
* Moves future to the ready state.
*/
protected void onAllKeysAdded() {
allKeysAdded = true;
checkLocks();
}
/** */
private void checkLocks() {
boolean locked = lockKeys.isEmpty();
if (locked && allKeysAdded) {
if (log.isDebugEnabled())
log.debug("All locks are acquired for near prepare future: " + this);
onDone((Void)null);
}
else {
if (log.isDebugEnabled())
log.debug("Still waiting for locks [fut=" + this + ", keys=" + lockKeys + ']');
}
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(KeyLockFuture.class, this, super.toString());
}
}
}
| |
package org.simpleflatmapper.poi.test.impl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.joda.time.DateTime;
import org.junit.Test;
import org.simpleflatmapper.poi.impl.RowGetterFactory;
import org.simpleflatmapper.reflect.primitive.BooleanGetter;
import org.simpleflatmapper.reflect.primitive.ByteGetter;
import org.simpleflatmapper.reflect.primitive.CharacterGetter;
import org.simpleflatmapper.reflect.primitive.DoubleGetter;
import org.simpleflatmapper.reflect.primitive.FloatGetter;
import org.simpleflatmapper.reflect.primitive.IntGetter;
import org.simpleflatmapper.reflect.primitive.LongGetter;
import org.simpleflatmapper.reflect.primitive.ShortGetter;
import org.simpleflatmapper.test.beans.DbObject;
import org.simpleflatmapper.csv.CsvColumnDefinition;
import org.simpleflatmapper.csv.CsvColumnKey;
import org.simpleflatmapper.reflect.Getter;
import java.text.SimpleDateFormat;
//IFJAVA8_START
import java.time.LocalDateTime;
import java.time.ZoneId;
//IFJAVA8_END
import java.util.Date;
import static org.junit.Assert.*;
@SuppressWarnings("unchecked")
public class RowGetterFactoryTest {
RowGetterFactory rowGetterFactory = new RowGetterFactory();
CsvColumnKey key = new CsvColumnKey("key", 1);
CsvColumnKey blankCellKey = new CsvColumnKey("key", 2);
CsvColumnKey noCellKey = new CsvColumnKey("key", 3);
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
Cell blankCell = row.createCell(2);
DataFormat dataFormat = wb.createDataFormat();
CellStyle twoDigitCellFormat = wb.createCellStyle();
CellStyle dateCellFormat = wb.createCellStyle();
{
twoDigitCellFormat.setDataFormat(dataFormat.getFormat("#.##"));
dateCellFormat.setDataFormat(dataFormat.getFormat("dd/MM/yyyy"));
}
@Test
public void testGetStringOnStringCell() throws Exception {
final Getter<Row, String> getter = rowGetterFactory.newGetter(String.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue("value");
assertEquals("value", getter.get(row));
}
@Test
public void testGetStringOnDoubleCell() throws Exception {
final Getter<Row, String> getter = rowGetterFactory.newGetter(String.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3.1456);
cell.setCellStyle(twoDigitCellFormat);
assertEquals("3.15", getter.get(row));
}
@Test
public void testGetStringOnDateCell() throws Exception {
final Getter<Row, String> getter = rowGetterFactory.newGetter(String.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(new SimpleDateFormat("yyyyMMdd").parse("20150527"));
cell.setCellStyle(dateCellFormat);
assertEquals("27/05/2015", getter.get(row));
}
@Test
public void testGetStringOnBooleanCell() throws Exception {
final Getter<Row, String> getter = rowGetterFactory.newGetter(String.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(true);
assertEquals("TRUE", getter.get(row));
}
@Test
public void testGetStringOnBlankCell() throws Exception {
final Getter<Row, String> getter = rowGetterFactory.newGetter(String.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertEquals("", getter.get(row));
}
@Test
public void testGetStringOnNullCell() throws Exception {
final Getter<Row, String> getter = rowGetterFactory.newGetter(String.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertEquals(null, getter.get(row));
}
@Test
public void testGetDoubleOnDoubleCell() throws Exception {
final Getter<Row, Double> getter = rowGetterFactory.newGetter(Double.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3.22);
assertEquals(3.22, getter.get(row), 0.0001);
assertEquals(3.22, ((DoubleGetter<Row>)getter).getDouble(row), 0.0001);
}
@Test
public void testGetDoubleOnBlankCell() throws Exception {
final Getter<Row, Double> getter = rowGetterFactory.newGetter(Double.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0.0, ((DoubleGetter<Row>)getter).getDouble(row), 0.0001);
}
@Test
public void testGetDoubleOnNullCell() throws Exception {
final Getter<Row, Double> getter = rowGetterFactory.newGetter(Double.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0.0, ((DoubleGetter<Row>)getter).getDouble(row), 0.0001);
}
@Test
public void testGetFloatOnDoubleCell() throws Exception {
final Getter<Row, Float> getter = rowGetterFactory.newGetter(Float.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3.22);
assertEquals(3.22, getter.get(row), 0.0001);
assertEquals(3.22, ((FloatGetter<Row>)getter).getFloat(row), 0.0001);
}
@Test
public void testGetFloatOnBlankCell() throws Exception {
final Getter<Row, Float> getter = rowGetterFactory.newGetter(Float.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertEquals(0.0, getter.get(row), 0.0001);
assertEquals(0.0, ((FloatGetter<Row>)getter).getFloat(row), 0.0001);
}
@Test
public void testGetFloatOnNullCell() throws Exception {
final Getter<Row, Float> getter = rowGetterFactory.newGetter(Float.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0.0, ((FloatGetter<Row>)getter).getFloat(row), 0.0001);
}
@Test
public void testGetLongOnDoubleCell() throws Exception {
final Getter<Row, Long> getter = rowGetterFactory.newGetter(Long.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3l);
assertEquals(3l, getter.get(row).longValue());
assertEquals(3l, ((LongGetter<Row>)getter).getLong(row));
}
@Test
public void testGetLongOnBlankCell() throws Exception {
final Getter<Row, Long> getter = rowGetterFactory.newGetter(Long.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertEquals(0, getter.get(row).longValue());
assertEquals(0, ((LongGetter<Row>)getter).getLong(row));
}
@Test
public void testGetLongOnNullCell() throws Exception {
final Getter<Row, Long> getter = rowGetterFactory.newGetter(Long.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0, ((LongGetter<Row>)getter).getLong(row));
}
@Test
public void testGetIntegerOnDoubleCell() throws Exception {
final Getter<Row, Integer> getter = rowGetterFactory.newGetter(Integer.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3);
assertEquals(3, getter.get(row).intValue());
assertEquals(3, ((IntGetter<Row>)getter).getInt(row));
}
@Test
public void testGetIntegerOnBlankCell() throws Exception {
final Getter<Row, Integer> getter = rowGetterFactory.newGetter(Integer.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertEquals(0, getter.get(row).intValue());
assertEquals(0, ((IntGetter<Row>) getter).getInt(row));
}
@Test
public void testGetIntegerOnNullCell() throws Exception {
final Getter<Row, Integer> getter = rowGetterFactory.newGetter(Integer.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0, ((IntGetter<Row>)getter).getInt(row));
}
@Test
public void testGetShortOnDoubleCell() throws Exception {
final Getter<Row, Short> getter = rowGetterFactory.newGetter(Short.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3);
assertEquals(3, getter.get(row).shortValue());
assertEquals(3, ((ShortGetter<Row>)getter).getShort(row));
}
@Test
public void testGetShortOnBlankCell() throws Exception {
final Getter<Row, Short> getter = rowGetterFactory.newGetter(Short.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertEquals(0, getter.get(row).shortValue());
assertEquals(0, ((ShortGetter<Row>)getter).getShort(row));
}
@Test
public void testGetShortOnNullCell() throws Exception {
final Getter<Row, Short> getter = rowGetterFactory.newGetter(Short.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0, ((ShortGetter<Row>)getter).getShort(row));
}
@Test
public void testGetCharacterOnDoubleCell() throws Exception {
final Getter<Row, Character> getter = rowGetterFactory.newGetter(Character.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3);
assertEquals(3, getter.get(row).charValue());
assertEquals(3, ((CharacterGetter<Row>)getter).getCharacter(row));
}
@Test
public void testGetCharacterOnBlankCell() throws Exception {
final Getter<Row, Character> getter = rowGetterFactory.newGetter(Character.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertEquals(0, getter.get(row).charValue());
assertEquals(0, ((CharacterGetter<Row>)getter).getCharacter(row));
}
@Test
public void testGetCharacterOnNullCell() throws Exception {
final Getter<Row, Character> getter = rowGetterFactory.newGetter(Character.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0, ((CharacterGetter<Row>)getter).getCharacter(row));
}
@Test
public void testGetByteOnDoubleCell() throws Exception {
final Getter<Row, Byte> getter = rowGetterFactory.newGetter(Byte.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(3);
assertEquals(3, getter.get(row).byteValue());
assertEquals(3, ((ByteGetter<Row>)getter).getByte(row));
}
@Test
public void testGetByteOnBlankCell() throws Exception {
final Getter<Row, Byte> getter = rowGetterFactory.newGetter(Byte.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertEquals(0, getter.get(row).byteValue());
assertEquals(0, ((ByteGetter<Row>)getter).getByte(row));
}
@Test
public void testGetByteOnNullCell() throws Exception {
final Getter<Row, Byte> getter = rowGetterFactory.newGetter(Byte.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertEquals(0, ((ByteGetter<Row>)getter).getByte(row));
}
@Test
public void testGetDateOnDateCell() throws Exception {
final Getter<Row, Date> getter = rowGetterFactory.newGetter(Date.class, key, CsvColumnDefinition.IDENTITY);
Date now = new Date();
cell.setCellValue(now);
assertEquals(now, getter.get(row));
}
@Test
public void testGetDateOnBlankCell() throws Exception {
final Getter<Row, Date> getter = rowGetterFactory.newGetter(Date.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
}
@Test
public void testGetBooleanOnDoubleCell() throws Exception {
final Getter<Row, Boolean> getter = rowGetterFactory.newGetter(Boolean.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(true);
assertTrue(getter.get(row).booleanValue());
assertTrue(((BooleanGetter<Row>) getter).getBoolean(row));
}
@Test
public void testGetBooleanOnBlankCell() throws Exception {
final Getter<Row, Boolean> getter = rowGetterFactory.newGetter(Boolean.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertFalse(getter.get(row).booleanValue());
assertFalse(((BooleanGetter<Row>) getter).getBoolean(row));
}
@Test
public void testGetBooleanOnNullCell() throws Exception {
final Getter<Row, Boolean> getter = rowGetterFactory.newGetter(Boolean.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
assertFalse(((BooleanGetter<Row>) getter).getBoolean(row));
}
@Test
public void testGetDateOnNullCell() throws Exception {
final Getter<Row, Date> getter = rowGetterFactory.newGetter(Date.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
}
@Test
public void testGetEnumOnString() throws Exception {
final Getter<Row, DbObject.Type> getter = rowGetterFactory.newGetter(DbObject.Type.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue("type1");
assertEquals(DbObject.Type.type1, getter.get(row));
}
@Test
public void testGetEnumOnNumber() throws Exception {
final Getter<Row, DbObject.Type> getter = rowGetterFactory.newGetter(DbObject.Type.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(1);
assertEquals(DbObject.Type.type2, getter.get(row));
}
@Test
public void testGetEnumOnBoolean() throws Exception {
final Getter<Row, DbObject.Type> getter = rowGetterFactory.newGetter(DbObject.Type.class, key, CsvColumnDefinition.IDENTITY);
cell.setCellValue(true);
try {
getter.get(row);
fail();
} catch(Exception e) {
}
}
@Test
public void testGetEnumOnBlank() throws Exception {
final Getter<Row, DbObject.Type> getter = rowGetterFactory.newGetter(DbObject.Type.class, blankCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
}
@Test
public void testGetEnumOnNull() throws Exception {
final Getter<Row, DbObject.Type> getter = rowGetterFactory.newGetter(DbObject.Type.class, noCellKey, CsvColumnDefinition.IDENTITY);
assertNull(getter.get(row));
}
}
| |
package org.docksidestage.mysql.dbflute.whitebox;
import java.util.ArrayList;
import java.util.List;
import org.dbflute.bhv.core.BehaviorCommandMeta;
import org.dbflute.cbean.result.ListResultBean;
import org.dbflute.hook.CallbackContext;
import org.dbflute.hook.SqlLogHandler;
import org.dbflute.hook.SqlLogInfo;
import org.dbflute.hook.SqlStringFilter;
import org.docksidestage.mysql.dbflute.cbean.MemberCB;
import org.docksidestage.mysql.dbflute.exbhv.MemberBhv;
import org.docksidestage.mysql.dbflute.exbhv.pmbean.SimpleMemberPmb;
import org.docksidestage.mysql.dbflute.exbhv.pmbean.SpInOutParameterPmb;
import org.docksidestage.mysql.dbflute.exentity.Member;
import org.docksidestage.mysql.dbflute.exentity.customize.SimpleMember;
import org.docksidestage.mysql.unit.UnitContainerTestCase;
/**
* @author jflute
* @since 0.9.9.6 (2012/07/06 Friday)
*/
public class WxSqlStringFilterProcedureTest extends UnitContainerTestCase {
// ===================================================================================
// Attribute
// =========
private MemberBhv memberBhv;
// ===================================================================================
// After Care
// ==========
@Override
public void tearDown() throws Exception {
super.tearDown();
clearBehaviorCommandHook();
}
protected void clearBehaviorCommandHook() {
CallbackContext.clearSqlStringFilterOnThread();
assertFalse(CallbackContext.isExistCallbackContextOnThread());
assertFalse(CallbackContext.isExistBehaviorCommandHookOnThread());
assertFalse(CallbackContext.isExistSqlFireHookOnThread());
assertFalse(CallbackContext.isExistSqlLogHandlerOnThread());
assertFalse(CallbackContext.isExistSqlResultHandlerOnThread());
assertFalse(CallbackContext.isExistSqlStringFilterOnThread());
}
// ===================================================================================
// ConditionBean
// =============
public void test_ConditionBean_selectList() {
// ## Arrange ##
final List<String> markList = new ArrayList<String>();
CallbackContext.setSqlStringFilterOnThread(new SqlStringFilter() {
public String filterSelectCB(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterSelectCB");
return "/*foo*/" + ln() + executedSql;
}
public String filterEntityUpdate(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterEntityUpdate");
return null;
}
public String filterQueryUpdate(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterQueryUpdate");
return null;
}
public String filterOutsideSql(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterOutsideSql");
return null;
}
public String filterProcedure(BehaviorCommandMeta meta, String executedSql) {
return null;
}
});
final List<SqlLogInfo> sqlLogInfoList = newArrayList();
CallbackContext.setSqlLogHandlerOnThread(new SqlLogHandler() {
public void handle(SqlLogInfo info) {
sqlLogInfoList.add(info);
}
});
try {
{
// ## Act ##
MemberCB cb = new MemberCB();
cb.query().setMemberName_LikeSearch("S", op -> op.likePrefix());
ListResultBean<Member> memberList = memberBhv.selectList(cb);
// ## Assert ##
assertFalse(memberList.isEmpty());
assertEquals(1, markList.size());
assertEquals("filterSelectCB", markList.get(0));
assertEquals(1, sqlLogInfoList.size());
assertTrue(sqlLogInfoList.get(0).getDisplaySql().startsWith("/*foo*/"));
}
{
// ## Act ##
MemberCB cb = new MemberCB();
cb.query().setMemberId_Equal(3);
memberBhv.selectEntityWithDeletedCheck(cb);
// ## Assert ##
assertEquals(2, markList.size());
assertEquals("filterSelectCB", markList.get(1));
assertEquals(2, sqlLogInfoList.size());
assertTrue(sqlLogInfoList.get(1).getDisplaySql().startsWith("/*foo*/"));
}
{
// ## Act ##
MemberCB cb = new MemberCB();
cb.paging(4, 2);
ListResultBean<Member> memberList = memberBhv.selectPage(cb);
// ## Assert ##
assertFalse(memberList.isEmpty());
assertEquals(4, markList.size());
assertEquals("filterSelectCB", markList.get(2));
assertEquals(4, sqlLogInfoList.size());
assertTrue(sqlLogInfoList.get(3).getDisplaySql().startsWith("/*foo*/"));
}
} finally {
CallbackContext.clearSqlLogHandlerOnThread();
}
}
// ===================================================================================
// Procedure
// =========
public void test_Procedure_selectList() {
// ## Arrange ##
final List<String> markList = new ArrayList<String>();
CallbackContext.setSqlStringFilterOnThread(new SqlStringFilter() {
public String filterSelectCB(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterSelectCB");
return null;
}
public String filterEntityUpdate(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterEntityUpdate");
return null;
}
public String filterQueryUpdate(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterQueryUpdate");
return null;
}
public String filterOutsideSql(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterOutsideSql");
return null;
}
public String filterProcedure(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterProcedure");
return executedSql + ln() + "/*foo*/";
}
});
final List<SqlLogInfo> sqlLogInfoList = newArrayList();
CallbackContext.setSqlLogHandlerOnThread(new SqlLogHandler() {
public void handle(SqlLogInfo info) {
sqlLogInfoList.add(info);
}
});
try {
{
// ## Act ##
SpInOutParameterPmb pmb = new SpInOutParameterPmb();
pmb.setVInVarchar("foo");
pmb.setVInoutVarchar("bar");
memberBhv.outsideSql().call(pmb);
// ## Assert ##
assertEquals("bar", pmb.getVOutVarchar());
assertEquals("foo", pmb.getVInoutVarchar());
assertEquals("filterProcedure", markList.get(0));
assertEquals(1, sqlLogInfoList.size());
assertTrue(sqlLogInfoList.get(0).getDisplaySql().endsWith("/*foo*/"));
}
} finally {
CallbackContext.clearSqlLogHandlerOnThread();
}
}
// ===================================================================================
// No Filter
// =========
public void test_NoFilter() {
// ## Arrange ##
final List<String> markList = new ArrayList<String>();
CallbackContext.setSqlStringFilterOnThread(new SqlStringFilter() {
public String filterSelectCB(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterSelectCB");
return null;
}
public String filterEntityUpdate(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterEntityUpdate");
return null;
}
public String filterQueryUpdate(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterQueryUpdate");
return null;
}
public String filterOutsideSql(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterOutsideSql");
return null;
}
public String filterProcedure(BehaviorCommandMeta meta, String executedSql) {
markList.add("filterProcedure");
return null;
}
});
// ## Act & Assert ##
{
MemberCB cb = new MemberCB();
cb.query().setMemberName_LikeSearch("S", op -> op.likePrefix());
assertFalse(memberBhv.selectList(cb).isEmpty());
assertEquals(1, markList.size());
assertEquals("filterSelectCB", markList.get(0));
}
{
Member member = new Member();
member.setMemberId(3);
member.setMemberName("filterEntity");
memberBhv.updateNonstrict(member);
assertEquals("filterEntity", memberBhv.selectEntityWithDeletedCheck(cb -> cb.acceptPK(3)).getMemberName());
assertEquals(3, markList.size());
assertEquals("filterEntityUpdate", markList.get(1));
}
{
Member member = new Member();
member.setMemberName("filterQuery");
MemberCB cb = new MemberCB();
cb.query().setMemberId_Equal(3);
cb.disableQueryUpdateCountPreCheck();
memberBhv.queryUpdate(member, cb);
assertEquals("filterQuery", memberBhv.selectByPK(3).get().getMemberName());
assertEquals(5, markList.size());
assertEquals("filterQueryUpdate", markList.get(3));
}
{
SimpleMemberPmb pmb = new SimpleMemberPmb();
pmb.setMemberId(3);
SimpleMember member = memberBhv.outsideSql().selectEntity(pmb).get();
assertEquals("filterQuery", member.getMemberName());
assertEquals(6, markList.size());
assertEquals("filterOutsideSql", markList.get(5));
}
{
SpInOutParameterPmb pmb = new SpInOutParameterPmb();
pmb.setVInVarchar("foo");
pmb.setVInoutVarchar("bar");
memberBhv.outsideSql().call(pmb);
assertEquals("bar", pmb.getVOutVarchar());
assertEquals("foo", pmb.getVInoutVarchar());
assertEquals(7, markList.size());
assertEquals("filterProcedure", markList.get(6));
}
}
}
| |
/*
* Copyright (c) 2008-2016 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.haulmont.cuba.client.testsupport;
import com.haulmont.chile.core.datatypes.DatatypeRegistry;
import com.haulmont.chile.core.datatypes.FormatStringsRegistry;
import com.haulmont.cuba.client.ClientConfig;
import com.haulmont.cuba.core.app.PersistenceManagerService;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.core.sys.AppContext;
import com.haulmont.cuba.core.sys.FormatStringsRegistryImpl;
import mockit.Mocked;
import mockit.Expectations;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Base class for building client-side integration tests.
*
*/
public class CubaClientTestCase {
private Map<String, List<String>> entityPackages = new LinkedHashMap<>();
private String viewConfig;
@Mocked
protected AppContext appContext;
@Mocked
protected AppBeans appBeans;
@Mocked
protected Configuration configuration;
@Mocked
protected PersistenceManagerService persistenceManager;
@Mocked
protected GlobalConfig globalConfig;
@Mocked
protected ClientConfig clientConfig;
protected TestMetadataClient metadata;
protected TestViewRepositoryClient viewRepository;
protected TestUserSessionSource userSessionSource;
protected TestUuidSource uuidSource;
protected TestSecurity security;
protected TestExtendedEntities extendedEntities;
protected FormatStringsRegistry formatStringsRegistry;
protected TestMessages messages;
protected TestMessageTools messageTools;
protected TestBeanValidation beanValidation;
protected TestEntityStates entityStates;
protected ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
protected MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
private Logger log = LoggerFactory.getLogger(CubaClientTestCase.class);
static {
String property = System.getProperty("logback.configurationFile");
if (StringUtils.isBlank(property)) {
System.setProperty("logback.configurationFile", "test-logback.xml");
}
}
/**
* Add entities package to build metadata from. Should be invoked by concrete test classes in their @Before method.
* @param packageName package FQN, e.g. <code>com.haulmont.cuba.core.entity</code>
*/
protected void addEntityPackage(String packageName) {
log.debug("Adding entity package: " + packageName);
String packagePrefix = packageName.replace(".", "/") + "/**/*.class";
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + packagePrefix;
Resource[] resources;
try {
resources = resourcePatternResolver.getResources(packageSearchPath);
} catch (IOException e) {
throw new RuntimeException(e);
}
entityPackages.put(packageName, getClasses(resources));
}
protected List<String> getClasses(Resource[] resources) {
List<String> classNames = new ArrayList<>();
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader;
try {
metadataReader = metadataReaderFactory.getMetadataReader(resource);
} catch (IOException e) {
throw new RuntimeException("Unable to read metadata resource", e);
}
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName())
|| annotationMetadata.isAnnotated(MappedSuperclass.class.getName())
|| annotationMetadata.isAnnotated(Entity.class.getName())) {
ClassMetadata classMetadata = metadataReader.getClassMetadata();
classNames.add(classMetadata.getClassName());
}
}
}
return classNames;
}
/**
* Set path to Views configuration file to build ViewRepository from it. Should be invoked by concrete test classes
* once in their @Before method.
* @param viewConfigPath configuration resource FQN, e.g. <code>/com/haulmont/cuba/gui/data/impl/testmodel1/test-views.xml</code>
*/
protected void setViewConfig(String viewConfigPath) {
viewConfig = viewConfigPath;
}
/**
* Set up {@link Metadata} and other infrastructure objects before running test. Should be invoked by concrete test classes
* once in their @Before method.
*/
protected void setupInfrastructure() {
log.debug("Setting up infrastructure");
new Expectations() {
{
AppContext.getProperty("cuba.confDir"); result = System.getProperty("user.dir"); minTimes = 0;
}
};
viewRepository = new TestViewRepositoryClient(viewConfig);
metadata = new TestMetadataClient(entityPackages, viewRepository, globalConfig);
userSessionSource = new TestUserSessionSource();
uuidSource = new TestUuidSource();
extendedEntities = new TestExtendedEntities(metadata);
security = new TestSecurity(userSessionSource, metadata, extendedEntities);
formatStringsRegistry = new FormatStringsRegistryImpl();
new Expectations() {
{
configuration.getConfig(GlobalConfig.class); result = globalConfig; minTimes = 0;
configuration.getConfig(ClientConfig.class); result = clientConfig; minTimes = 0;
globalConfig.getConfDir(); result = System.getProperty("user.dir"); minTimes = 0;
clientConfig.getRemoteMessagesSearchEnabled(); result = false; minTimes = 0;
}
};
messages = new TestMessages(userSessionSource, configuration, metadata, extendedEntities, formatStringsRegistry);
messageTools = (TestMessageTools) messages.getTools();
beanValidation = new TestBeanValidation();
entityStates = new TestEntityStates();
((TestMetadataTools) metadata.getTools()).setMessages(messages);
((TestMetadataTools) metadata.getTools()).setUserSessionSource(userSessionSource);
messages.setConfiguration(configuration);
new Expectations() {
{
AppBeans.get(Metadata.NAME); result = metadata; minTimes = 0;
AppBeans.get(Metadata.class); result = metadata; minTimes = 0;
AppBeans.get(Metadata.NAME, Metadata.class); result = metadata; minTimes = 0;
AppBeans.get(ViewRepository.NAME); result = viewRepository; minTimes = 0;
AppBeans.get(ViewRepository.class); result = viewRepository; minTimes = 0;
AppBeans.get(ViewRepository.NAME, ViewRepository.class); result = viewRepository; minTimes = 0;
AppBeans.get(MetadataTools.NAME); result = metadata.getTools(); minTimes = 0;
AppBeans.get(MetadataTools.class); result = metadata.getTools(); minTimes = 0;
AppBeans.get(MetadataTools.NAME, MetadataTools.class); result = metadata.getTools(); minTimes = 0;
AppBeans.get(DatatypeRegistry.NAME); result = metadata.getDatatypes(); minTimes = 0;
AppBeans.get(DatatypeRegistry.class); result = metadata.getDatatypes(); minTimes = 0;
AppBeans.get(DatatypeRegistry.NAME, DatatypeRegistry.class); result = metadata.getDatatypes(); minTimes = 0;
AppBeans.get(FormatStringsRegistry.NAME); result = formatStringsRegistry; minTimes = 0;
AppBeans.get(FormatStringsRegistry.class); result = formatStringsRegistry; minTimes = 0;
AppBeans.get(FormatStringsRegistry.NAME, FormatStringsRegistry.class); result = formatStringsRegistry; minTimes = 0;
AppBeans.get(Configuration.NAME); result = configuration; minTimes = 0;
AppBeans.get(Configuration.class); result = configuration; minTimes = 0;
AppBeans.get(Configuration.NAME, Configuration.class); result = configuration; minTimes = 0;
AppBeans.get(PersistenceManagerService.NAME); result = persistenceManager; minTimes = 0;
AppBeans.get(PersistenceManagerService.class); result = persistenceManager; minTimes = 0;
AppBeans.get(PersistenceManagerService.NAME, PersistenceManagerService.class); result = persistenceManager; minTimes = 0;
AppBeans.get(UserSessionSource.NAME); result = userSessionSource; minTimes = 0;
AppBeans.get(UserSessionSource.class); result = userSessionSource; minTimes = 0;
AppBeans.get(UserSessionSource.NAME, UserSessionSource.class); result = userSessionSource; minTimes = 0;
AppBeans.get(UuidSource.NAME); result = uuidSource; minTimes = 0;
AppBeans.get(UuidSource.class); result = uuidSource; minTimes = 0;
AppBeans.get(UuidSource.NAME, UuidSource.class); result = uuidSource; minTimes = 0;
AppBeans.get(Security.NAME); result = security; minTimes = 0;
AppBeans.get(Security.class); result= security; minTimes = 0;
AppBeans.get(Security.NAME, Security.class); result = security; minTimes = 0;
AppBeans.get(ExtendedEntities.NAME); result = extendedEntities; minTimes = 0;
AppBeans.get(ExtendedEntities.class); result = extendedEntities; minTimes = 0;
AppBeans.get(ExtendedEntities.NAME, ExtendedEntities.class); result = extendedEntities; minTimes = 0;
AppBeans.get(Messages.NAME); result = messages; minTimes = 0;
AppBeans.get(Messages.class); result = messages; minTimes = 0;
AppBeans.get(Messages.NAME, Messages.class); result = messages; minTimes = 0;
AppBeans.get(MessageTools.NAME); result = messageTools; minTimes = 0;
AppBeans.get(MessageTools.class); result = messageTools; minTimes = 0;
AppBeans.get(MessageTools.NAME, MessageTools.class); result = messageTools; minTimes = 0;
AppBeans.get(BeanValidation.NAME); result = beanValidation; minTimes = 0;
AppBeans.get(BeanValidation.class); result = beanValidation; minTimes = 0;
AppBeans.get(BeanValidation.NAME, BeanValidation.class); result = beanValidation; minTimes = 0;
AppBeans.get(EntityStates.NAME); result = entityStates; minTimes = 0;
AppBeans.get(EntityStates.class); result = entityStates; minTimes = 0;
AppBeans.get(EntityStates.NAME, BeanValidation.class); result = entityStates; minTimes = 0;
}
};
metadata.initMetadata();
}
}
| |
/*
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.client;
import com.google.bigtable.v2.SampleRowKeysRequest;
import com.google.cloud.bigtable.config.BigtableOptions;
import com.google.cloud.bigtable.config.Logger;
import com.google.cloud.bigtable.data.v2.models.KeyOffset;
import com.google.cloud.bigtable.grpc.BigtableSession;
import com.google.cloud.bigtable.hbase.BigtableOptionsFactory;
import com.google.cloud.bigtable.hbase.adapters.Adapters;
import com.google.cloud.bigtable.hbase.adapters.HBaseRequestAdapter;
import com.google.cloud.bigtable.hbase.adapters.HBaseRequestAdapter.MutationAdapters;
import com.google.cloud.bigtable.hbase.adapters.SampledRowKeysAdapter;
import com.google.cloud.bigtable.hbase2_x.BigtableAsyncAdmin;
import com.google.cloud.bigtable.hbase2_x.BigtableAsyncBufferedMutator;
import com.google.cloud.bigtable.hbase2_x.BigtableAsyncTable;
import com.google.cloud.bigtable.hbase2_x.BigtableAsyncTableRegionLocator;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.security.User;
/**
* Bigtable implementation of {@link AsyncConnection}
*
* @author spollapally
*/
public class BigtableAsyncConnection implements AsyncConnection, CommonConnection, Closeable {
private final Logger LOG = new Logger(getClass());
private final Configuration conf;
private final BigtableSession session;
private final BigtableOptions options;
private volatile boolean closed = false;
private final Set<TableName> disabledTables = Collections.synchronizedSet(new HashSet<>());
private MutationAdapters mutationAdapters;
static {
// This forces a clean class loading of both HConstants and KeyValue along
// with a whole bunch of other classes.
Adapters.class.getName();
}
public BigtableAsyncConnection(Configuration conf) throws IOException {
this(conf, null, null, null);
}
public BigtableAsyncConnection(
Configuration conf, AsyncRegistry ignoredRegistry, String ignoredClusterId, User ignoredUser)
throws IOException {
LOG.debug("Creating BigtableAsyncConnection");
this.conf = conf;
BigtableOptions opts;
try {
opts = BigtableOptionsFactory.fromConfiguration(conf);
} catch (IOException ioe) {
LOG.error("Error loading BigtableOptions from Configuration.", ioe);
throw ioe;
}
this.closed = false;
this.session = new BigtableSession(opts);
this.options = this.session.getOptions();
}
public HBaseRequestAdapter createAdapter(TableName tableName) {
if (mutationAdapters == null) {
synchronized (this) {
if (mutationAdapters == null) {
mutationAdapters = new HBaseRequestAdapter.MutationAdapters(options, conf);
}
}
}
return new HBaseRequestAdapter(options, tableName, mutationAdapters);
}
public BigtableSession getSession() {
return this.session;
}
public BigtableOptions getOptions() {
return this.options;
}
public Set<TableName> getDisabledTables() {
return disabledTables;
}
@Override
public void close() throws IOException {
LOG.debug("closing BigtableAsyncConnection");
if (!this.closed) {
this.session.close();
this.closed = true;
}
}
@Override
public Configuration getConfiguration() {
return this.conf;
}
@Override
public AsyncAdminBuilder getAdminBuilder() {
return new AsyncAdminBuilder() {
@Override
public AsyncAdminBuilder setStartLogErrorsCnt(int arg0) {
return this;
}
@Override
public AsyncAdminBuilder setRpcTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncAdminBuilder setRetryPause(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncAdminBuilder setOperationTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncAdminBuilder setMaxAttempts(int arg0) {
return this;
}
@Override
public AsyncAdmin build() {
try {
return new BigtableAsyncAdmin(BigtableAsyncConnection.this);
} catch (IOException e) {
LOG.error("failed to build BigtableAsyncAdmin", e);
throw new UncheckedIOException("failed to build BigtableAsyncAdmin", e);
}
}
};
}
@Override
public AsyncAdminBuilder getAdminBuilder(ExecutorService arg0) {
return getAdminBuilder();
}
@Override
public AsyncBufferedMutatorBuilder getBufferedMutatorBuilder(final TableName tableName) {
return new AsyncBufferedMutatorBuilder() {
@Override
public AsyncBufferedMutatorBuilder setWriteBufferSize(long arg0) {
return this;
}
@Override
public AsyncBufferedMutatorBuilder setStartLogErrorsCnt(int arg0) {
return this;
}
@Override
public AsyncBufferedMutatorBuilder setRpcTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncBufferedMutatorBuilder setRetryPause(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncBufferedMutatorBuilder setOperationTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncBufferedMutatorBuilder setMaxAttempts(int arg0) {
return this;
}
@Override
public AsyncBufferedMutator build() {
return new BigtableAsyncBufferedMutator(
createAdapter(tableName), getConfiguration(), session);
}
};
}
@Override
public AsyncBufferedMutatorBuilder getBufferedMutatorBuilder(
TableName tableName, ExecutorService es) {
return getBufferedMutatorBuilder(tableName);
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> getTableBuilder(TableName tableName) {
return new AsyncTableBuilder<AdvancedScanResultConsumer>() {
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setWriteRpcTimeout(
long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setStartLogErrorsCnt(int arg0) {
return this;
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setScanTimeout(
long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setRpcTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setRetryPause(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setReadRpcTimeout(
long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setOperationTimeout(
long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<AdvancedScanResultConsumer> setMaxAttempts(int arg0) {
return this;
}
@Override
public AsyncTable build() {
return new BigtableAsyncTable(BigtableAsyncConnection.this, createAdapter(tableName));
}
};
}
@Override
public AsyncTableRegionLocator getRegionLocator(TableName tableName) {
return new BigtableAsyncTableRegionLocator(
tableName, options, this.session.getDataClientWrapper());
}
@Override
public AsyncTableBuilder<ScanResultConsumer> getTableBuilder(
TableName tableName, final ExecutorService ignored) {
return new AsyncTableBuilder<ScanResultConsumer>() {
@Override
public AsyncTable build() {
return new BigtableAsyncTable(BigtableAsyncConnection.this, createAdapter(tableName));
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setMaxAttempts(int arg0) {
return this;
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setOperationTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setReadRpcTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setRetryPause(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setRpcTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setScanTimeout(long arg0, TimeUnit arg1) {
return this;
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setStartLogErrorsCnt(int arg0) {
return this;
}
@Override
public AsyncTableBuilder<ScanResultConsumer> setWriteRpcTimeout(long arg0, TimeUnit arg1) {
return this;
}
};
}
@Override
public List<HRegionInfo> getAllRegionInfos(TableName tableName) throws IOException {
ServerName serverName = ServerName.valueOf(options.getDataHost(), options.getPort(), 0);
SampleRowKeysRequest.Builder request = SampleRowKeysRequest.newBuilder();
request.setTableName(options.getInstanceName().toTableNameStr(tableName.getNameAsString()));
List<KeyOffset> sampleRowKeyResponse =
this.session.getDataClientWrapper().sampleRowKeys(tableName.getNameAsString());
return getSampledRowKeysAdapter(tableName, serverName).adaptResponse(sampleRowKeyResponse)
.stream()
.map(HRegionLocation::getRegionInfo)
.collect(Collectors.toCollection(CopyOnWriteArrayList::new));
}
@Override
public Hbck getHbck(ServerName serverName) {
throw new UnsupportedOperationException("getHbck is not supported.");
}
@Override
public CompletableFuture<Hbck> getHbck() {
throw new UnsupportedOperationException("getHbck is not supported.");
}
private SampledRowKeysAdapter getSampledRowKeysAdapter(
TableName tableNameAdapter, ServerName serverNameAdapter) {
return new SampledRowKeysAdapter(tableNameAdapter, serverNameAdapter) {
@Override
protected HRegionLocation createRegionLocation(byte[] startKey, byte[] endKey) {
RegionInfo regionInfo =
RegionInfoBuilder.newBuilder(tableNameAdapter)
.setStartKey(startKey)
.setEndKey(endKey)
.build();
return new HRegionLocation(regionInfo, serverNameAdapter);
}
};
}
}
| |
package io.fabric8.maven.docker.access.hc;
import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import io.fabric8.maven.docker.access.hc.http.HttpRequestException;
import io.fabric8.maven.docker.access.hc.util.ClientBuilder;
public class ApacheHttpClientDelegate {
private final ClientBuilder clientBuilder;
private final CloseableHttpClient httpClient;
public ApacheHttpClientDelegate(ClientBuilder clientBuilder, boolean pooled) throws IOException {
this.clientBuilder = clientBuilder;
this.httpClient = pooled ? clientBuilder.buildPooledClient() : clientBuilder.buildBasicClient();
}
public CloseableHttpClient createBasicClient() {
try {
return clientBuilder.buildBasicClient();
} catch (IOException exp) {
throw new IllegalStateException("Cannot create single HTTP client: " + exp,exp);
}
}
public CloseableHttpClient getHttpClient() {
return httpClient;
}
public void close() throws IOException {
httpClient.close();
}
public int delete(String url, int... statusCodes) throws IOException {
return delete(url, new StatusCodeResponseHandler(), statusCodes);
}
public static class StatusCodeResponseHandler implements ResponseHandler<Integer> {
@Override
public Integer handleResponse(HttpResponse response) {
return response.getStatusLine().getStatusCode();
}
}
public <T> T delete(String url, ResponseHandler<T> responseHandler, int... statusCodes)
throws IOException {
return httpClient.execute(newDelete(url),
new StatusCodeCheckerResponseHandler<>(responseHandler,
statusCodes));
}
public String get(String url, int... statusCodes) throws IOException {
return httpClient.execute(newGet(url), new StatusCodeCheckerResponseHandler<>(
new BodyResponseHandler(), statusCodes));
}
public <T> T get(String url, ResponseHandler<T> responseHandler, int... statusCodes)
throws IOException {
return httpClient
.execute(newGet(url), new StatusCodeCheckerResponseHandler<>(responseHandler, statusCodes));
}
public static class BodyResponseHandler implements ResponseHandler<String> {
@Override
public String handleResponse(HttpResponse response)
throws IOException {
return getResponseMessage(response);
}
}
private static String getResponseMessage(HttpResponse response) throws IOException {
return (response.getEntity() == null) ? null
: EntityUtils.toString(response.getEntity()).trim();
}
public <T> T post(String url, Object body, Map<String, String> headers,
ResponseHandler<T> responseHandler, int... statusCodes) throws IOException {
HttpUriRequest request = newPost(url, body);
for (Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
return httpClient.execute(request, new StatusCodeCheckerResponseHandler<>(responseHandler, statusCodes));
}
public <T> T post(String url, Object body, ResponseHandler<T> responseHandler,
int... statusCodes) throws IOException {
return httpClient.execute(newPost(url, body),
new StatusCodeCheckerResponseHandler<>(responseHandler,
statusCodes));
}
public int post(String url, int... statusCodes) throws IOException {
return post(url, null, new StatusCodeResponseHandler(), statusCodes);
}
public int put(String url, Object body, int... statusCodes) throws IOException {
return httpClient.execute(newPut(url, body),
new StatusCodeCheckerResponseHandler<>(new StatusCodeResponseHandler(), statusCodes));
}
// =========================================================================================
private HttpUriRequest addDefaultHeaders(HttpUriRequest req, Object body) {
req.addHeader(HttpHeaders.ACCEPT, "*/*");
if (body instanceof File) {
req.addHeader(HttpHeaders.CONTENT_TYPE, URLConnection.guessContentTypeFromName(((File)body).getName()));
}
if (body != null && !req.containsHeader(HttpHeaders.CONTENT_TYPE)) {
req.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}
return req;
}
private HttpUriRequest newDelete(String url) {
return addDefaultHeaders(new HttpDelete(url), null);
}
private HttpUriRequest newGet(String url) {
return addDefaultHeaders(new HttpGet(url), null);
}
private HttpUriRequest newPut(String url, Object body) {
HttpPut put = new HttpPut(url);
setEntityIfGiven(put, body);
return addDefaultHeaders(put, body);
}
private HttpUriRequest newPost(String url, Object body) {
HttpPost post = new HttpPost(url);
setEntityIfGiven(post, body);
return addDefaultHeaders(post, body);
}
private void setEntityIfGiven(HttpEntityEnclosingRequestBase request, Object entity) {
if (entity != null) {
if (entity instanceof File) {
request.setEntity(new FileEntity((File) entity));
} else {
request.setEntity(new StringEntity((String) entity, Charset.defaultCharset()));
}
}
}
private static class StatusCodeCheckerResponseHandler<T> implements ResponseHandler<T> {
private int[] statusCodes;
private ResponseHandler<T> delegate;
StatusCodeCheckerResponseHandler(ResponseHandler<T> delegate, int... statusCodes) {
this.statusCodes = statusCodes;
this.delegate = delegate;
}
@Override
public T handleResponse(HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
for (int code : statusCodes) {
if (statusCode == code) {
return delegate.handleResponse(response);
}
}
String reason = statusLine.getReasonPhrase().trim();
throw new HttpRequestException(String.format("%s (%s: %d)", getResponseMessage(response),
reason, statusCode));
}
}
public static class BodyAndStatusResponseHandler implements ResponseHandler<HttpBodyAndStatus> {
@Override
public HttpBodyAndStatus handleResponse(HttpResponse response)
throws IOException {
return new HttpBodyAndStatus(response.getStatusLine().getStatusCode(),
getResponseMessage(response));
}
}
public static class HttpBodyAndStatus {
private final int statusCode;
private final String body;
public HttpBodyAndStatus(int statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public int getStatusCode() {
return statusCode;
}
public String getBody() {
return body;
}
}
}
| |
/*
* Copyright 2004-2013 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.docksidestage.mysql.dbflute.cbean.cq.bs;
import java.util.Map;
import org.dbflute.cbean.*;
import org.dbflute.cbean.chelper.*;
import org.dbflute.cbean.coption.*;
import org.dbflute.cbean.cvalue.ConditionValue;
import org.dbflute.cbean.sqlclause.SqlClause;
import org.dbflute.exception.IllegalConditionBeanOperationException;
import org.docksidestage.mysql.dbflute.cbean.cq.ciq.*;
import org.docksidestage.mysql.dbflute.cbean.*;
import org.docksidestage.mysql.dbflute.cbean.cq.*;
/**
* The base condition-query of vendor_the_long_and_winding_table_and_column.
* @author DBFlute(AutoGenerator)
*/
public class BsVendorTheLongAndWindingTableAndColumnCQ extends AbstractBsVendorTheLongAndWindingTableAndColumnCQ {
// ===================================================================================
// Attribute
// =========
protected VendorTheLongAndWindingTableAndColumnCIQ _inlineQuery;
// ===================================================================================
// Constructor
// ===========
public BsVendorTheLongAndWindingTableAndColumnCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) {
super(referrerQuery, sqlClause, aliasName, nestLevel);
}
// ===================================================================================
// InlineView/OrClause
// ===================
/**
* Prepare InlineView query. <br>
* {select ... from ... left outer join (select * from vendor_the_long_and_winding_table_and_column) where FOO = [value] ...}
* <pre>
* cb.query().queryMemberStatus().<span style="color: #CC4747">inline()</span>.setFoo...;
* </pre>
* @return The condition-query for InlineView query. (NotNull)
*/
public VendorTheLongAndWindingTableAndColumnCIQ inline() {
if (_inlineQuery == null) { _inlineQuery = xcreateCIQ(); }
_inlineQuery.xsetOnClause(false); return _inlineQuery;
}
protected VendorTheLongAndWindingTableAndColumnCIQ xcreateCIQ() {
VendorTheLongAndWindingTableAndColumnCIQ ciq = xnewCIQ();
ciq.xsetBaseCB(_baseCB);
return ciq;
}
protected VendorTheLongAndWindingTableAndColumnCIQ xnewCIQ() {
return new VendorTheLongAndWindingTableAndColumnCIQ(xgetReferrerQuery(), xgetSqlClause(), xgetAliasName(), xgetNestLevel(), this);
}
/**
* Prepare OnClause query. <br>
* {select ... from ... left outer join vendor_the_long_and_winding_table_and_column on ... and FOO = [value] ...}
* <pre>
* cb.query().queryMemberStatus().<span style="color: #CC4747">on()</span>.setFoo...;
* </pre>
* @return The condition-query for OnClause query. (NotNull)
* @throws IllegalConditionBeanOperationException When this condition-query is base query.
*/
public VendorTheLongAndWindingTableAndColumnCIQ on() {
if (isBaseQuery()) { throw new IllegalConditionBeanOperationException("OnClause for local table is unavailable!"); }
VendorTheLongAndWindingTableAndColumnCIQ inlineQuery = inline(); inlineQuery.xsetOnClause(true); return inlineQuery;
}
// ===================================================================================
// Query
// =====
protected ConditionValue _theLongAndWindingTableAndColumnId;
public ConditionValue xdfgetTheLongAndWindingTableAndColumnId()
{ if (_theLongAndWindingTableAndColumnId == null) { _theLongAndWindingTableAndColumnId = nCV(); }
return _theLongAndWindingTableAndColumnId; }
protected ConditionValue xgetCValueTheLongAndWindingTableAndColumnId() { return xdfgetTheLongAndWindingTableAndColumnId(); }
public Map<String, VendorTheLongAndWindingTableAndColumnRefCQ> xdfgetTheLongAndWindingTableAndColumnId_ExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList() { return xgetSQueMap("theLongAndWindingTableAndColumnId_ExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList"); }
public String keepTheLongAndWindingTableAndColumnId_ExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList(VendorTheLongAndWindingTableAndColumnRefCQ sq) { return xkeepSQue("theLongAndWindingTableAndColumnId_ExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList", sq); }
public Map<String, VendorTheLongAndWindingTableAndColumnRefCQ> xdfgetTheLongAndWindingTableAndColumnId_NotExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList() { return xgetSQueMap("theLongAndWindingTableAndColumnId_NotExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList"); }
public String keepTheLongAndWindingTableAndColumnId_NotExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList(VendorTheLongAndWindingTableAndColumnRefCQ sq) { return xkeepSQue("theLongAndWindingTableAndColumnId_NotExistsReferrer_VendorTheLongAndWindingTableAndColumnRefList", sq); }
public Map<String, VendorTheLongAndWindingTableAndColumnRefCQ> xdfgetTheLongAndWindingTableAndColumnId_SpecifyDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList() { return xgetSQueMap("theLongAndWindingTableAndColumnId_SpecifyDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList"); }
public String keepTheLongAndWindingTableAndColumnId_SpecifyDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList(VendorTheLongAndWindingTableAndColumnRefCQ sq) { return xkeepSQue("theLongAndWindingTableAndColumnId_SpecifyDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList", sq); }
public Map<String, VendorTheLongAndWindingTableAndColumnRefCQ> xdfgetTheLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList() { return xgetSQueMap("theLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList"); }
public String keepTheLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList(VendorTheLongAndWindingTableAndColumnRefCQ sq) { return xkeepSQue("theLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList", sq); }
public Map<String, Object> xdfgetTheLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefListParameter() { return xgetSQuePmMap("theLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList"); }
public String keepTheLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefListParameter(Object pm) { return xkeepSQuePm("theLongAndWindingTableAndColumnId_QueryDerivedReferrer_VendorTheLongAndWindingTableAndColumnRefList", pm); }
/**
* Add order-by as ascend. <br>
* THE_LONG_AND_WINDING_TABLE_AND_COLUMN_ID: {PK, NotNull, BIGINT(19)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_TheLongAndWindingTableAndColumnId_Asc() { regOBA("THE_LONG_AND_WINDING_TABLE_AND_COLUMN_ID"); return this; }
/**
* Add order-by as descend. <br>
* THE_LONG_AND_WINDING_TABLE_AND_COLUMN_ID: {PK, NotNull, BIGINT(19)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_TheLongAndWindingTableAndColumnId_Desc() { regOBD("THE_LONG_AND_WINDING_TABLE_AND_COLUMN_ID"); return this; }
protected ConditionValue _theLongAndWindingTableAndColumnName;
public ConditionValue xdfgetTheLongAndWindingTableAndColumnName()
{ if (_theLongAndWindingTableAndColumnName == null) { _theLongAndWindingTableAndColumnName = nCV(); }
return _theLongAndWindingTableAndColumnName; }
protected ConditionValue xgetCValueTheLongAndWindingTableAndColumnName() { return xdfgetTheLongAndWindingTableAndColumnName(); }
/**
* Add order-by as ascend. <br>
* THE_LONG_AND_WINDING_TABLE_AND_COLUMN_NAME: {UQ, NotNull, VARCHAR(180)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_TheLongAndWindingTableAndColumnName_Asc() { regOBA("THE_LONG_AND_WINDING_TABLE_AND_COLUMN_NAME"); return this; }
/**
* Add order-by as descend. <br>
* THE_LONG_AND_WINDING_TABLE_AND_COLUMN_NAME: {UQ, NotNull, VARCHAR(180)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_TheLongAndWindingTableAndColumnName_Desc() { regOBD("THE_LONG_AND_WINDING_TABLE_AND_COLUMN_NAME"); return this; }
protected ConditionValue _shortName;
public ConditionValue xdfgetShortName()
{ if (_shortName == null) { _shortName = nCV(); }
return _shortName; }
protected ConditionValue xgetCValueShortName() { return xdfgetShortName(); }
/**
* Add order-by as ascend. <br>
* SHORT_NAME: {NotNull, VARCHAR(200)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_ShortName_Asc() { regOBA("SHORT_NAME"); return this; }
/**
* Add order-by as descend. <br>
* SHORT_NAME: {NotNull, VARCHAR(200)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_ShortName_Desc() { regOBD("SHORT_NAME"); return this; }
protected ConditionValue _shortSize;
public ConditionValue xdfgetShortSize()
{ if (_shortSize == null) { _shortSize = nCV(); }
return _shortSize; }
protected ConditionValue xgetCValueShortSize() { return xdfgetShortSize(); }
/**
* Add order-by as ascend. <br>
* SHORT_SIZE: {NotNull, INT(10)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_ShortSize_Asc() { regOBA("SHORT_SIZE"); return this; }
/**
* Add order-by as descend. <br>
* SHORT_SIZE: {NotNull, INT(10)}
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addOrderBy_ShortSize_Desc() { regOBD("SHORT_SIZE"); return this; }
// ===================================================================================
// SpecifiedDerivedOrderBy
// =======================
/**
* Add order-by for specified derived column as ascend.
* <pre>
* cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
* public void query(PurchaseCB subCB) {
* subCB.specify().columnPurchaseDatetime();
* }
* }, <span style="color: #CC4747">aliasName</span>);
* <span style="color: #3F7E5E">// order by [alias-name] asc</span>
* cb.<span style="color: #CC4747">addSpecifiedDerivedOrderBy_Asc</span>(<span style="color: #CC4747">aliasName</span>);
* </pre>
* @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; }
/**
* Add order-by for specified derived column as descend.
* <pre>
* cb.specify().derivedPurchaseList().max(new SubQuery<PurchaseCB>() {
* public void query(PurchaseCB subCB) {
* subCB.specify().columnPurchaseDatetime();
* }
* }, <span style="color: #CC4747">aliasName</span>);
* <span style="color: #3F7E5E">// order by [alias-name] desc</span>
* cb.<span style="color: #CC4747">addSpecifiedDerivedOrderBy_Desc</span>(<span style="color: #CC4747">aliasName</span>);
* </pre>
* @param aliasName The alias name specified at (Specify)DerivedReferrer. (NotNull)
* @return this. (NotNull)
*/
public BsVendorTheLongAndWindingTableAndColumnCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; }
// ===================================================================================
// Union Query
// ===========
public void reflectRelationOnUnionQuery(ConditionQuery bqs, ConditionQuery uqs) {
}
// ===================================================================================
// Foreign Query
// =============
protected Map<String, Object> xfindFixedConditionDynamicParameterMap(String property) {
return null;
}
// ===================================================================================
// ScalarCondition
// ===============
public Map<String, VendorTheLongAndWindingTableAndColumnCQ> xdfgetScalarCondition() { return xgetSQueMap("scalarCondition"); }
public String keepScalarCondition(VendorTheLongAndWindingTableAndColumnCQ sq) { return xkeepSQue("scalarCondition", sq); }
// ===================================================================================
// MyselfDerived
// =============
public Map<String, VendorTheLongAndWindingTableAndColumnCQ> xdfgetSpecifyMyselfDerived() { return xgetSQueMap("specifyMyselfDerived"); }
public String keepSpecifyMyselfDerived(VendorTheLongAndWindingTableAndColumnCQ sq) { return xkeepSQue("specifyMyselfDerived", sq); }
public Map<String, VendorTheLongAndWindingTableAndColumnCQ> xdfgetQueryMyselfDerived() { return xgetSQueMap("queryMyselfDerived"); }
public String keepQueryMyselfDerived(VendorTheLongAndWindingTableAndColumnCQ sq) { return xkeepSQue("queryMyselfDerived", sq); }
public Map<String, Object> xdfgetQueryMyselfDerivedParameter() { return xgetSQuePmMap("queryMyselfDerived"); }
public String keepQueryMyselfDerivedParameter(Object pm) { return xkeepSQuePm("queryMyselfDerived", pm); }
// ===================================================================================
// MyselfExists
// ============
protected Map<String, VendorTheLongAndWindingTableAndColumnCQ> _myselfExistsMap;
public Map<String, VendorTheLongAndWindingTableAndColumnCQ> xdfgetMyselfExists() { return xgetSQueMap("myselfExists"); }
public String keepMyselfExists(VendorTheLongAndWindingTableAndColumnCQ sq) { return xkeepSQue("myselfExists", sq); }
// ===================================================================================
// MyselfInScope
// =============
public Map<String, VendorTheLongAndWindingTableAndColumnCQ> xdfgetMyselfInScope() { return xgetSQueMap("myselfInScope"); }
public String keepMyselfInScope(VendorTheLongAndWindingTableAndColumnCQ sq) { return xkeepSQue("myselfInScope", sq); }
// ===================================================================================
// Very Internal
// =============
// very internal (for suppressing warn about 'Not Use Import')
protected String xCB() { return VendorTheLongAndWindingTableAndColumnCB.class.getName(); }
protected String xCQ() { return VendorTheLongAndWindingTableAndColumnCQ.class.getName(); }
protected String xCHp() { return HpQDRFunction.class.getName(); }
protected String xCOp() { return ConditionOption.class.getName(); }
protected String xMap() { return Map.class.getName(); }
}
| |
/*
* Copyright (c) 2010-2018 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.model.intest;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.evolveum.midpoint.prism.query.OrgFilter;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.evolveum.icf.dummy.resource.DummyResource;
import com.evolveum.midpoint.model.api.ProgressListener;
import com.evolveum.midpoint.model.common.mapping.MappingFactory;
import com.evolveum.midpoint.model.impl.lens.Clockwork;
import com.evolveum.midpoint.model.impl.lens.ClockworkMedic;
import com.evolveum.midpoint.model.intest.util.CheckingProgressListener;
import com.evolveum.midpoint.model.test.ProfilingModelInspectorManager;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.DummyResourceContoller;
import com.evolveum.midpoint.test.IntegrationTestTools;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* @author semancik
*
*/
public class AbstractInitializedModelIntegrationTest extends AbstractConfiguredModelIntegrationTest {
private static final int NUM_FUNCTIONAL_ORGS = 6;
private static final int NUM_PROJECT_ORGS = 3;
protected static final Trace LOGGER = TraceManager.getTrace(AbstractInitializedModelIntegrationTest.class);
private static final int NUMBER_OF_IMPORTED_USERS = 4;
private static final int NUMBER_OF_IMPORTED_ROLES = 16;
@Autowired protected MappingFactory mappingFactory;
@Autowired protected Clockwork clockwork;
@Autowired protected ClockworkMedic clockworkMedic;
protected ProfilingModelInspectorManager profilingModelInspectorManager;
protected CheckingProgressListener checkingProgressListener;
protected UserType userTypeJack;
protected UserType userTypeBarbossa;
protected UserType userTypeGuybrush;
protected UserType userTypeElaine;
protected DummyResourceContoller dummyResourceCtl;
protected DummyResource dummyResourceCyan;
protected DummyResourceContoller dummyResourceCtlCyan;
protected ResourceType resourceDummyCyanType;
protected PrismObject<ResourceType> resourceDummyCyan;
protected DummyResource dummyResourceWhite;
protected DummyResourceContoller dummyResourceCtlWhite;
protected ResourceType resourceDummyWhiteType;
protected PrismObject<ResourceType> resourceDummyWhite;
protected static DummyResource dummyResourceEmerald;
protected static DummyResourceContoller dummyResourceCtlEmerald;
protected ResourceType resourceDummyEmeraldType;
protected PrismObject<ResourceType> resourceDummyEmerald;
protected DummyResource dummyResourceUpcase;
protected DummyResourceContoller dummyResourceCtlUpcase;
protected ResourceType resourceDummyUpcaseType;
protected PrismObject<ResourceType> resourceDummyUpcase;
protected ResourceType resourceDummySchemalessType;
protected PrismObject<ResourceType> resourceDummySchemaless;
public AbstractInitializedModelIntegrationTest() {
super();
}
@Override
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
LOGGER.trace("initSystem");
super.initSystem(initTask, initResult);
assumeConflictResolutionAction(getDefaultConflictResolutionAction());
mappingFactory.setProfiling(true);
profilingModelInspectorManager = new ProfilingModelInspectorManager();
clockworkMedic.setDiagnosticContextManager(profilingModelInspectorManager);
checkingProgressListener = new CheckingProgressListener();
// Resources
dummyResourceCtl = initDummyResource(null, getResourceDummyFile(), RESOURCE_DUMMY_OID,
controller -> {
controller.extendSchemaPirate();
controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(),
DUMMY_ACCOUNT_ATTRIBUTE_SEA_NAME, String.class, false, false);
},
initTask, initResult);
initDummyResourcePirate(RESOURCE_DUMMY_RED_NAME,
RESOURCE_DUMMY_RED_FILE, RESOURCE_DUMMY_RED_OID, initTask, initResult);
initDummyResourcePirate(RESOURCE_DUMMY_BLUE_NAME,
getResourceDummyBlueFile(), RESOURCE_DUMMY_BLUE_OID, initTask, initResult);
initDummyResourcePirate(RESOURCE_DUMMY_YELLOW_NAME,
RESOURCE_DUMMY_YELLOW_FILE, RESOURCE_DUMMY_YELLOW_OID, initTask, initResult);
initDummyResourcePirate(RESOURCE_DUMMY_GREEN_NAME,
RESOURCE_DUMMY_GREEN_FILE, RESOURCE_DUMMY_GREEN_OID, initTask, initResult);
initDummyResourcePirate(RESOURCE_DUMMY_BLACK_NAME,
RESOURCE_DUMMY_BLACK_FILE, RESOURCE_DUMMY_BLACK_OID, initTask, initResult);
initDummyResourcePirate(RESOURCE_DUMMY_RELATIVE_NAME,
RESOURCE_DUMMY_RELATIVE_FILE, RESOURCE_DUMMY_RELATIVE_OID, initTask, initResult);
dummyResourceCtlCyan = DummyResourceContoller.create(RESOURCE_DUMMY_CYAN_NAME, resourceDummyCyan);
dummyResourceCtlCyan.extendSchemaPirate();
dummyResourceCyan = dummyResourceCtlCyan.getDummyResource();
resourceDummyCyan = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_CYAN_FILE, RESOURCE_DUMMY_CYAN_OID, initTask, initResult);
resourceDummyCyanType = resourceDummyCyan.asObjectable();
dummyResourceCtlCyan.setResource(resourceDummyCyan);
dummyResourceCtlWhite = DummyResourceContoller.create(RESOURCE_DUMMY_WHITE_NAME, resourceDummyWhite);
dummyResourceCtlWhite.extendSchemaPirate();
dummyResourceWhite = dummyResourceCtlWhite.getDummyResource();
resourceDummyWhite = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_WHITE_FILENAME, RESOURCE_DUMMY_WHITE_OID, initTask, initResult);
resourceDummyWhiteType = resourceDummyWhite.asObjectable();
dummyResourceCtlWhite.setResource(resourceDummyWhite);
dummyResourceCtlEmerald = DummyResourceContoller.create(RESOURCE_DUMMY_EMERALD_NAME, resourceDummyEmerald);
dummyResourceCtlEmerald.extendSchemaPirate();
dummyResourceCtlEmerald.extendSchemaPosix();
dummyResourceEmerald = dummyResourceCtlEmerald.getDummyResource();
resourceDummyEmerald = importAndGetObjectFromFile(ResourceType.class, getResourceDummyEmeraldFile(), RESOURCE_DUMMY_EMERALD_OID, initTask, initResult);
resourceDummyEmeraldType = resourceDummyEmerald.asObjectable();
dummyResourceCtlEmerald.setResource(resourceDummyEmerald);
initDummyResource(RESOURCE_DUMMY_ORANGE_NAME, RESOURCE_DUMMY_ORANGE_FILE, RESOURCE_DUMMY_ORANGE_OID,
controller -> {
controller.extendSchemaPirate();
controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(),
DUMMY_ACCOUNT_ATTRIBUTE_MATE_NAME, String.class, false, true);
},
initTask, initResult);
dummyResourceCtlUpcase = DummyResourceContoller.create(RESOURCE_DUMMY_UPCASE_NAME, resourceDummyUpcase);
dummyResourceCtlUpcase.extendSchemaPirate();
dummyResourceUpcase = dummyResourceCtlUpcase.getDummyResource();
resourceDummyUpcase = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_UPCASE_FILE, RESOURCE_DUMMY_UPCASE_OID, initTask, initResult);
resourceDummyUpcaseType = resourceDummyUpcase.asObjectable();
dummyResourceCtlUpcase.setResource(resourceDummyUpcase);
dummyResourceCtlUpcase.addGroup(GROUP_JOKER_DUMMY_UPCASE_NAME);
resourceDummySchemaless = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_FILENAME, RESOURCE_DUMMY_SCHEMALESS_OID, initTask, initResult);
resourceDummySchemalessType = resourceDummySchemaless.asObjectable();
postInitDummyResouce();
dummyResourceCtl.addAccount(ACCOUNT_HERMAN_DUMMY_USERNAME, "Herman Toothrot", "Monkey Island");
dummyResourceCtl.addAccount(ACCOUNT_GUYBRUSH_DUMMY_USERNAME, "Guybrush Threepwood", "Melee Island");
dummyResourceCtl.addAccount(ACCOUNT_DAVIEJONES_DUMMY_USERNAME, "Davie Jones", "Davie Jones' Locker");
dummyResourceCtl.addAccount(ACCOUNT_CALYPSO_DUMMY_USERNAME, "Tia Dalma", "Pantano River");
dummyResourceCtl.addAccount(ACCOUNT_ELAINE_DUMMY_USERNAME, "Elaine Marley", "Melee Island");
getDummyResourceController(RESOURCE_DUMMY_RED_NAME).addAccount(ACCOUNT_ELAINE_DUMMY_USERNAME, "Elaine Marley", "Melee Island");
getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).addAccount(ACCOUNT_ELAINE_DUMMY_USERNAME, "Elaine Marley", "Melee Island");
repoAddObjectFromFile(LOOKUP_LANGUAGES_FILE, initResult);
repoAddObjectFromFile(SECURITY_POLICY_FILE, initResult);
// User Templates
repoAddObjectFromFile(USER_TEMPLATE_FILENAME, initResult);
repoAddObjectFromFile(USER_TEMPLATE_COMPLEX_FILE, initResult);
repoAddObjectFromFile(USER_TEMPLATE_SCHEMA_CONSTRAINTS_FILE, initResult);
repoAddObjectFromFile(USER_TEMPLATE_INBOUNDS_FILENAME, initResult);
repoAddObjectFromFile(USER_TEMPLATE_COMPLEX_INCLUDE_FILENAME, initResult);
repoAddObjectFromFile(USER_TEMPLATE_ORG_ASSIGNMENT_FILENAME, initResult);
repoAddObjectFromFile(USER_TEMPLATE_CARTHESIAN_FILENAME, initResult);
// Shadows
repoAddObjectFromFile(ACCOUNT_SHADOW_GUYBRUSH_DUMMY_FILE, initResult);
repoAddObjectFromFile(ACCOUNT_SHADOW_ELAINE_DUMMY_FILE, initResult);
repoAddObjectFromFile(ACCOUNT_SHADOW_ELAINE_DUMMY_RED_FILE, initResult);
repoAddObjectFromFile(ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_FILE, initResult);
repoAddObjectFromFile(GROUP_SHADOW_JOKER_DUMMY_UPCASE_FILE, initResult);
// Users
userTypeJack = repoAddObjectFromFile(USER_JACK_FILE, UserType.class, true, initResult).asObjectable();
userTypeBarbossa = repoAddObjectFromFile(USER_BARBOSSA_FILE, UserType.class, initResult).asObjectable();
userTypeGuybrush = repoAddObjectFromFile(USER_GUYBRUSH_FILE, UserType.class, initResult).asObjectable();
userTypeElaine = repoAddObjectFromFile(USER_ELAINE_FILE, UserType.class, initResult).asObjectable();
// Roles
repoAddObjectFromFile(ROLE_PIRATE_FILE, initResult);
repoAddObjectFromFile(ROLE_PIRATE_GREEN_FILE, initResult);
repoAddObjectFromFile(ROLE_PIRATE_RELATIVE_FILE, initResult);
repoAddObjectFromFile(ROLE_CARIBBEAN_PIRATE_FILE, initResult);
repoAddObjectFromFile(ROLE_BUCCANEER_GREEN_FILE, initResult);
repoAddObjectFromFile(ROLE_NICE_PIRATE_FILENAME, initResult);
repoAddObjectFromFile(ROLE_CAPTAIN_FILENAME, initResult);
repoAddObjectFromFile(ROLE_JUDGE_FILE, initResult);
repoAddObjectFromFile(ROLE_JUDGE_DEPRECATED_FILE, initResult);
repoAddObjectFromFile(ROLE_THIEF_FILE, initResult);
repoAddObjectFromFile(ROLE_EMPTY_FILE, initResult);
repoAddObjectFromFile(ROLE_USELESS_FILE, initResult);
repoAddObjectFromFile(ROLE_SAILOR_FILE, initResult);
repoAddObjectFromFile(ROLE_RED_SAILOR_FILE, initResult);
repoAddObjectFromFile(ROLE_CYAN_SAILOR_FILE, initResult);
repoAddObjectFromFile(ROLE_STRONG_SAILOR_FILE, initResult);
// Orgstruct
if (doAddOrgstruct()) {
repoAddObjectsFromFile(ORG_MONKEY_ISLAND_FILE, OrgType.class, initResult);
}
// Services
repoAddObjectFromFile(SERVICE_SHIP_SEA_MONKEY_FILE, initResult);
//Custom function libraries
repoAddObjectFromFile(CUSTOM_LIBRARY_FILE, initResult);
//Password policy
repoAddObjectFromFile(PASSWORD_POLICY_BENEVOLENT_FILE, initResult);
}
protected ConflictResolutionActionType getDefaultConflictResolutionAction() {
return ConflictResolutionActionType.FAIL;
}
@Override
protected int getNumberOfUsers() {
return super.getNumberOfUsers() + NUMBER_OF_IMPORTED_USERS;
}
@Override
protected int getNumberOfRoles() {
return super.getNumberOfRoles() + NUMBER_OF_IMPORTED_ROLES;
}
protected boolean doAddOrgstruct() {
return true;
}
protected File getResourceDummyFile() {
return RESOURCE_DUMMY_FILE;
}
protected File getResourceDummyBlueFile() {
return RESOURCE_DUMMY_BLUE_FILE;
}
protected File getResourceDummyGreenFile() {
return RESOURCE_DUMMY_GREEN_FILE;
}
protected File getResourceDummyEmeraldFile() {
return RESOURCE_DUMMY_EMERALD_FILE;
}
protected void postInitDummyResouce() {
// Do nothing be default. Concrete tests may override this.
}
protected void assertUserJack(PrismObject<UserType> user) {
assertUserJack(user, USER_JACK_FULL_NAME, USER_JACK_GIVEN_NAME, USER_JACK_FAMILY_NAME);
}
protected void assertUserJack(PrismObject<UserType> user, String fullName) {
assertUserJack(user, fullName, USER_JACK_GIVEN_NAME, USER_JACK_FAMILY_NAME);
}
protected void assertUserJack(PrismObject<UserType> user, String fullName, String givenName, String familyName) {
assertUserJack(user, fullName, givenName, familyName, "Caribbean");
}
protected void assertUserJack(PrismObject<UserType> user, String name, String fullName, String givenName, String familyName, String locality) {
assertUser(user, USER_JACK_OID, name, fullName, givenName, familyName, locality);
UserType userType = user.asObjectable();
PrismAsserts.assertEqualsPolyString("Wrong jack honorificPrefix", "Cpt.", userType.getHonorificPrefix());
PrismAsserts.assertEqualsPolyString("Wrong jack honorificSuffix", "PhD.", userType.getHonorificSuffix());
assertEquals("Wrong jack emailAddress", "jack.sparrow@evolveum.com", userType.getEmailAddress());
assertEquals("Wrong jack telephoneNumber", "555-1234", userType.getTelephoneNumber());
assertEquals("Wrong jack employeeNumber", "emp1234", userType.getEmployeeNumber());
assertEquals("Wrong jack employeeType", USER_JACK_SUBTYPE, userType.getSubtype().get(0));
if (locality == null) {
assertNull("Locality sneaked to user jack", userType.getLocality());
} else {
PrismAsserts.assertEqualsPolyString("Wrong jack locality", locality, userType.getLocality());
}
}
protected void assertUserJack(PrismObject<UserType> user, String fullName, String givenName, String familyName, String locality) {
assertUserJack(user, USER_JACK_USERNAME, fullName, givenName, familyName, locality);
}
protected void assertDummyAccountShadowRepo(PrismObject<ShadowType> accountShadow, String oid, String username) throws SchemaException {
assertAccountShadowRepo(accountShadow, oid, username, dummyResourceCtl.getResource().asObjectable());
}
protected void assertDummyGroupShadowRepo(PrismObject<ShadowType> accountShadow, String oid, String username) throws SchemaException {
assertShadowRepo(accountShadow, oid, username, dummyResourceCtl.getResourceType(), dummyResourceCtl.getGroupObjectClass());
}
protected void assertDummyAccountShadowModel(PrismObject<ShadowType> accountShadow, String oid, String username) throws SchemaException {
assertShadowModel(accountShadow, oid, username, dummyResourceCtl.getResourceType(), dummyResourceCtl.getAccountObjectClass());
}
protected void assertDummyGroupShadowModel(PrismObject<ShadowType> accountShadow, String oid, String username) throws SchemaException {
assertShadowModel(accountShadow, oid, username, dummyResourceCtl.getResourceType(), dummyResourceCtl.getGroupObjectClass());
}
protected void assertDummyAccountShadowModel(PrismObject<ShadowType> accountShadow, String oid, String username, String fullname) throws SchemaException {
assertDummyAccountShadowModel(accountShadow, oid, username);
IntegrationTestTools.assertAttribute(accountShadow, dummyResourceCtl.getAttributeFullnameQName(), fullname);
}
protected void setDefaultUserTemplate(String userTemplateOid)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
setDefaultObjectTemplate(UserType.COMPLEX_TYPE, userTemplateOid);
}
@Override
protected String getTopOrgOid() {
return ORG_GOVERNOR_OFFICE_OID;
}
protected void assertMonkeyIslandOrgSanity() throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
assertMonkeyIslandOrgSanity(0);
}
protected void assertMonkeyIslandOrgSanity(int expectedFictional) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException {
Task task = taskManager.createTaskInstance(AbstractInitializedModelIntegrationTest.class.getName() + ".assertMonkeyIslandOrgSanity");
OperationResult result = task.getResult();
PrismObject<OrgType> orgGovernorOffice = modelService.getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID, null, task, result);
result.computeStatus();
TestUtil.assertSuccess(result);
OrgType orgGovernorOfficeType = orgGovernorOffice.asObjectable();
assertEquals("Wrong governor office name", PrismTestUtil.createPolyStringType("F0001"), orgGovernorOfficeType.getName());
List<PrismObject<OrgType>> governorSubOrgs = searchOrg(ORG_GOVERNOR_OFFICE_OID, OrgFilter.Scope.ONE_LEVEL, task, result);
if (verbose) display("governor suborgs", governorSubOrgs);
assertEquals("Unexpected number of governor suborgs", 3, governorSubOrgs.size());
List<PrismObject<OrgType>> functionalOrgs = searchOrg(ORG_GOVERNOR_OFFICE_OID, OrgFilter.Scope.SUBTREE, task, result);
if (verbose) display("functional orgs (null)", functionalOrgs);
assertEquals("Unexpected number of functional orgs (null)", NUM_FUNCTIONAL_ORGS - 1 + expectedFictional, functionalOrgs.size());
List<PrismObject<OrgType>> prootSubOrgs = searchOrg(ORG_PROJECT_ROOT_OID, OrgFilter.Scope.ONE_LEVEL, task, result);
if (verbose) display("project root suborgs", prootSubOrgs);
assertEquals("Unexpected number of governor suborgs", 2, prootSubOrgs.size());
List<PrismObject<OrgType>> projectOrgs = searchOrg(ORG_PROJECT_ROOT_OID, OrgFilter.Scope.SUBTREE, task, result);
if (verbose) display("project orgs (null)", projectOrgs);
assertEquals("Unexpected number of functional orgs (null)", NUM_PROJECT_ORGS - 1, projectOrgs.size());
PrismObject<OrgType> orgScummBar = modelService.getObject(OrgType.class, ORG_SCUMM_BAR_OID, null, task, result);
List<AssignmentType> scummBarInducements = orgScummBar.asObjectable().getInducement();
assertEquals("Unexpected number of scumm bar inducements: "+scummBarInducements, 1, scummBarInducements.size());
ResultHandler<OrgType> handler = getOrgSanityCheckHandler();
if (handler != null) {
modelService.searchObjectsIterative(OrgType.class, null, handler, null, task, result);
}
}
protected ResultHandler<OrgType> getOrgSanityCheckHandler() {
return null;
}
protected void assertShadowOperationalData(PrismObject<ShadowType> shadow, SynchronizationSituationType expectedSituation, Long timeBeforeSync) {
ShadowType shadowType = shadow.asObjectable();
SynchronizationSituationType actualSituation = shadowType.getSynchronizationSituation();
assertEquals("Wrong situation in shadow "+shadow, expectedSituation, actualSituation);
XMLGregorianCalendar actualTimestampCal = shadowType.getSynchronizationTimestamp();
assert actualTimestampCal != null : "No synchronization timestamp in shadow "+shadow;
if (timeBeforeSync != null) {
long actualTimestamp = XmlTypeConverter.toMillis(actualTimestampCal);
assert actualTimestamp >= timeBeforeSync : "Synchronization timestamp was not updated in shadow " + shadow;
}
// TODO: assert sync description
}
protected Collection<ProgressListener> getCheckingProgressListenerCollection() {
return Collections.singleton((ProgressListener)checkingProgressListener);
}
}
| |
package com.junjunguo.pocketmaps.fragments;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.junjunguo.pocketmaps.R;
import com.junjunguo.pocketmaps.model.MyMap;
import com.junjunguo.pocketmaps.model.listeners.OnClickMapListener;
import java.util.ArrayList;
import java.util.List;
/**
* This file is part of PocketMaps
* <p/>
* Created by GuoJunjun <junjunguo.com> on July 03, 2015.
*/
public class MyMapAdapter extends RecyclerView.Adapter<MyMapAdapter.ViewHolder> {
private List<MyMap> myMaps;
private List<MyMap> myMapsFiltered;
private OnClickMapListener onClickMapListener;
private boolean isDownloadingView;
public static class ViewHolder extends RecyclerView.ViewHolder {
public FloatingActionButton flag;
public TextView name, continent, size, downloadStatus;
public OnClickMapListener onClickMapListener;
private boolean isDownloadingView;
protected ViewHolder(View itemView, OnClickMapListener onClickMapListener, boolean isDownloadingView) {
super(itemView);
this.isDownloadingView = isDownloadingView;
this.onClickMapListener = onClickMapListener;
this.flag = (FloatingActionButton) itemView.findViewById(R.id.my_maps_item_flag);
this.name = (TextView) itemView.findViewById(R.id.my_maps_item_name);
this.continent = (TextView) itemView.findViewById(R.id.my_maps_item_continent);
this.size = (TextView) itemView.findViewById(R.id.my_maps_item_size);
this.downloadStatus = (TextView) itemView.findViewById(R.id.my_maps_item_download_status);
}
public void setItemData(MyMap myMap) {
name.setTextColor(android.graphics.Color.BLACK);
if (isDownloadingView)
{
MyMap.DlStatus status = myMap.getStatus();
if (status == MyMap.DlStatus.Downloading)
{
flag.setImageResource(R.drawable.ic_pause_orange_24dp);
downloadStatus.setText("Downloading ...");
}
else if (status == MyMap.DlStatus.Unzipping)
{
flag.setImageResource(R.drawable.ic_pause_orange_24dp);
downloadStatus.setText("Unzipping ...");
}
else if (status == MyMap.DlStatus.Complete)
{
if (myMap.isUpdateAvailable())
{
flag.setImageResource(R.drawable.ic_cloud_download_white_24dp);
name.setTextColor(android.graphics.Color.RED);
}
else
{
flag.setImageResource(R.drawable.ic_map_white_24dp);
}
downloadStatus.setText("Downloaded");
}
else
{
flag.setImageResource(R.drawable.ic_cloud_download_white_24dp);
downloadStatus.setText("");
}
}
else
{
downloadStatus.setText("");
}
View.OnClickListener l = new View.OnClickListener()
{
public void onClick(View v)
{
log("onclick" + itemView.toString());
onClickMapListener.onClickMap(ViewHolder.this.getAdapterPosition());
}
};
name.setText(myMap.getCountry());
continent.setText(myMap.getContinent());
size.setText(myMap.getSize());
itemView.setOnClickListener(l);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyMapAdapter(List<MyMap> myMaps, OnClickMapListener onClickMapListener, boolean isDownloadingView)
{
this.myMaps = myMaps;
this.myMapsFiltered = myMaps;
this.onClickMapListener = onClickMapListener;
this.isDownloadingView = isDownloadingView;
}
// Create new views (invoked by the layout manager)
@Override
public MyMapAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_maps_item, parent, false);
ViewHolder vh = new ViewHolder(v, onClickMapListener, isDownloadingView);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setItemData(myMapsFiltered.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return myMapsFiltered.size();
}
public void refreshMapView(MyMap myMap)
{
int rvIndex = myMapsFiltered.indexOf(myMap);
if (rvIndex >= 0)
{
notifyItemRemoved(rvIndex);
notifyItemInserted(rvIndex);
}
else
{
log("No map-entry for refreshing found, maybe filter active.");
}
}
/**
* @param position
* @return MyMap item at the position
*/
public MyMap getItem(int position) {
return myMapsFiltered.get(position);
}
/**
* remove item at the given position
*
* @param position index
*/
public MyMap remove(int position) {
MyMap mm = null;
if (position >= 0 && position < getItemCount())
{
mm = myMaps.remove(position);
int posFiltered = myMapsFiltered.indexOf(mm);
if (posFiltered >= 0)
{ // Filter is active!
myMapsFiltered.remove(posFiltered);
position = posFiltered;
}
notifyItemRemoved(position);
}
return mm;
}
/**
* Clear the list (remove all elements)
* Does NOT call notifyItemRangeRemoved()
*/
public void clearList() {
this.myMaps.clear();
this.myMapsFiltered.clear();
}
/**
* add a list of MyMap
*
* @param maps
*/
public void addAll(List<MyMap> maps) {
this.myMaps.addAll(maps);
if (myMaps == myMapsFiltered)
{
notifyItemRangeInserted(myMaps.size() - maps.size(), maps.size());
}
}
/**
* Insert the object to the end of the list
* Executes notifyItemInserted()
* @param myMap
*/
public void insert(MyMap myMap) {
if (!getMapNameList().contains(myMap.getMapName())) {
myMaps.add(myMap);
if (myMaps == myMapsFiltered)
{
notifyItemInserted(getItemCount() - 1);
}
}
}
/**
* @return a string list of map names (continent_country)
*/
public List<String> getMapNameList() {
ArrayList<String> al = new ArrayList<String>();
for (MyMap mm : myMaps) {
al.add(mm.getMapName());
}
return al;
}
static void log(String txt)
{
Log.i(MyMapAdapter.class.getName(), txt);
}
public void doFilter(String filterText)
{
log("FILTER-START!");
filterText = filterText.toLowerCase();
List<MyMap> filteredList = new ArrayList<MyMap>();
if (filterText.isEmpty())
{
filteredList = myMaps;
log("FILTER: Empty");
}
else
{
for (MyMap curMap : myMaps)
{
if (curMap.getCountry().toLowerCase().contains(filterText) || curMap.getContinent().toLowerCase().contains(filterText))
{
filteredList.add(curMap);
}
}
log("FILTER: " + filteredList.size() + "/" + myMaps.size());
}
myMapsFiltered = filteredList;
notifyDataSetChanged();
log("FILTER: Publish: " + myMapsFiltered.size() + "/" + myMaps.size());
}
}
| |
/*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2011/09/19 Added debugging
// ZAP: 2012/04/23 Removed unnecessary cast.
// ZAP: 2012/05/08 Use custom http client on "Connection: Upgrade" in executeMethod().
// Retrieve upgraded socket and save for later use in send() method.
// ZAP: 2012/08/07 Issue 342 Support the HttpSenderListener
// ZAP: 2012/12/27 Do not read request body on Server-Sent Event streams.
// ZAP: 2013/01/03 Resolved Checkstyle issues: removed throws HttpException
// declaration where IOException already appears,
// introduced two helper methods for notifying listeners.
// ZAP: 2013/01/19 Issue 459: Active scanner locking
// ZAP: 2013/01/23 Clean up of exception handling/logging.
// ZAP: 2013/01/30 Issue 478: Allow to choose to send ZAP's managed cookies on
// a single Cookie request header and set it as the default
// ZAP: 2013/07/10 Issue 720: Cannot send non standard http methods
// ZAP: 2013/07/14 Issue 729: Update NTLM authentication code
// ZAP: 2013/07/25 Added support for sending the message from the perspective of a User
// ZAP: 2013/08/31 Reauthentication when sending a message from the perspective of a User
// ZAP: 2013/09/07 Switched to using HttpState for requesting User for cookie management
// ZAP: 2013/09/26 Issue 716: ZAP flags its own HTTP responses
// ZAP: 2013/09/26 Issue 656: Content-length: 0 in GET requests
// ZAP: 2013/09/29 Deprecating configuring HTTP Authentication through Options
// ZAP: 2013/11/16 Issue 837: Update, always, the HTTP request sent/forward by ZAP's proxy
// ZAP: 2013/12/11 Corrected log.info calls to use debug
// ZAP: 2014/03/04 Issue 1043: Custom active scan dialog
// ZAP: 2014/03/23 Issue 412: Enable unsafe SSL/TLS renegotiation option not saved
// ZAP: 2014/03/23 Issue 416: Normalise how multiple related options are managed throughout ZAP
// and enhance the usability of some options
// ZAP: 2014/03/29 Issue 1132: HttpSender ignores the "Send single cookie request header" option
// ZAP: 2014/08/14 Issue 1291: 407 Proxy Authentication Required while active scanning
// ZAP: 2014/10/25 Issue 1062: Added a getter for the HttpClient.
// ZAP: 2014/10/28 Issue 1390: Force https on cfu call
// ZAP: 2014/11/25 Issue 1411: Changed getUser() visibility
// ZAP: 2014/12/11 Added JavaDoc to constructor and removed the instance variable allowState.
// ZAP: 2015/04/09 Allow to specify the maximum number of retries on I/O error.
// ZAP: 2015/04/09 Allow to specify the maximum number of redirects.
// ZAP: 2015/04/09 Allow to specify if circular redirects are allowed.
// ZAP: 2015/06/12 Issue 1459: Add an HTTP sender listener script
// ZAP: 2016/05/24 Issue 2463: Websocket not proxied when outgoing proxy is set
// ZAP: 2016/05/27 Issue 2484: Circular Redirects
// ZAP: 2016/06/08 Set User-Agent header defined in options as default for (internal) CONNECT requests
// ZAP: 2016/06/10 Allow to validate the URI of the redirections before being followed
package org.parosproxy.paros.network;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodDirector;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.InvalidRedirectLocationException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.ProxyHost;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.log4j.Logger;
import org.zaproxy.zap.ZapGetMethod;
import org.zaproxy.zap.ZapHttpConnectionManager;
import org.zaproxy.zap.network.HttpSenderListener;
import org.zaproxy.zap.network.ZapNTLMScheme;
import org.zaproxy.zap.users.User;
public class HttpSender {
public static final int PROXY_INITIATOR = 1;
public static final int ACTIVE_SCANNER_INITIATOR = 2;
public static final int SPIDER_INITIATOR = 3;
public static final int FUZZER_INITIATOR = 4;
public static final int AUTHENTICATION_INITIATOR = 5;
public static final int MANUAL_REQUEST_INITIATOR = 6;
public static final int CHECK_FOR_UPDATES_INITIATOR = 7;
public static final int BEAN_SHELL_INITIATOR = 8;
public static final int ACCESS_CONTROL_SCANNER_INITIATOR = 9;
private static Logger log = Logger.getLogger(HttpSender.class);
private static ProtocolSocketFactory sslFactory = null;
private static Protocol protocol = null;
private static List<HttpSenderListener> listeners = new ArrayList<>();
private static Comparator<HttpSenderListener> listenersComparator = null;;
private User user = null;
static {
try {
protocol = Protocol.getProtocol("https");
sslFactory = protocol.getSocketFactory();
} catch (Exception e) {
}
// avoid init again if already initialized
if (sslFactory == null || !(sslFactory instanceof SSLConnector)) {
Protocol.registerProtocol("https", new Protocol("https",
(ProtocolSocketFactory) new SSLConnector(true), 443));
}
AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, ZapNTLMScheme.class);
}
private static HttpMethodHelper helper = new HttpMethodHelper();
private static String userAgent = "";
private static final ThreadLocal<Boolean> IN_LISTENER = new ThreadLocal<Boolean>();
private HttpClient client = null;
private HttpClient clientViaProxy = null;
private ConnectionParam param = null;
private MultiThreadedHttpConnectionManager httpConnManager = null;
private MultiThreadedHttpConnectionManager httpConnManagerProxy = null;
private boolean followRedirect = false;
private int initiator = -1;
/*
* public HttpSender(ConnectionParam connectionParam, boolean allowState) { this
* (connectionParam, allowState, -1); }
*/
/**
* Constructs an {@code HttpSender}.
* <p>
* If {@code useGlobalState} is {@code true} the HttpSender will use the HTTP state given by
* {@code ConnectionParam#getHttpState()} iff {@code ConnectionParam#isHttpStateEnabled()} returns {@code true} otherwise it
* doesn't have any state (i.e. cookies are disabled). If {@code useGlobalState} is {@code false} it uses a non shared HTTP
* state. The actual state used is overridden, per message, when {@code HttpMessage#getRequestingUser()} returns non
* {@code null}.
* <p>
* The {@code initiator} is used to indicate the component that is sending the messages when the {@code HttpSenderListener}s
* are notified of messages sent and received.
*
* @param connectionParam the parameters used to setup the connections to target hosts
* @param useGlobalState {@code true} if the messages sent/received should use the global HTTP state, {@code false} if
* should use a non shared HTTP state
* @param initiator the ID of the initiator of the HTTP messages sent
* @see ConnectionParam#getHttpState()
* @see HttpSenderListener
* @see HttpMessage#getRequestingUser()
*/
public HttpSender(ConnectionParam connectionParam, boolean useGlobalState, int initiator) {
this.param = connectionParam;
this.initiator = initiator;
client = createHttpClient();
clientViaProxy = createHttpClientViaProxy();
setAllowCircularRedirects(true);
// Set how cookie headers are sent no matter of the "allowState", in case a state is forced by
// other extensions (e.g. Authentication)
final boolean singleCookieRequestHeader = param.isSingleCookieRequestHeader();
client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER,
singleCookieRequestHeader);
clientViaProxy.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER,
singleCookieRequestHeader);
String defaultUserAgent = param.getDefaultUserAgent();
client.getParams().setParameter(HttpMethodDirector.PARAM_DEFAULT_USER_AGENT_CONNECT_REQUESTS, defaultUserAgent);
clientViaProxy.getParams().setParameter(HttpMethodDirector.PARAM_DEFAULT_USER_AGENT_CONNECT_REQUESTS, defaultUserAgent);
if (useGlobalState) {
checkState();
}
}
public static SSLConnector getSSLConnector() {
return (SSLConnector) protocol.getSocketFactory();
}
private void checkState() {
if (param.isHttpStateEnabled()) {
client.setState(param.getHttpState());
clientViaProxy.setState(param.getHttpState());
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
clientViaProxy.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
} else {
client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
clientViaProxy.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
}
}
private HttpClient createHttpClient() {
httpConnManager = new MultiThreadedHttpConnectionManager();
setCommonManagerParams(httpConnManager);
return new HttpClient(httpConnManager);
}
private HttpClient createHttpClientViaProxy() {
if (!param.isUseProxyChain()) {
return createHttpClient();
}
httpConnManagerProxy = new MultiThreadedHttpConnectionManager();
setCommonManagerParams(httpConnManagerProxy);
HttpClient clientProxy = new HttpClient(httpConnManagerProxy);
clientProxy.getHostConfiguration().setProxy(param.getProxyChainName(), param.getProxyChainPort());
if (param.isUseProxyChainAuth()) {
clientProxy.getState().setProxyCredentials(getAuthScope(param), getNTCredentials(param));
}
return clientProxy;
}
private NTCredentials getNTCredentials(ConnectionParam param) {
// NTCredentials credentials = new NTCredentials(
// param.getProxyChainUserName(), param.getProxyChainPassword(),
// param.getProxyChainName(), param.getProxyChainName());
return new NTCredentials(param.getProxyChainUserName(),
param.getProxyChainPassword(), "", param.getProxyChainRealm().equals("") ? ""
: param.getProxyChainRealm());
}
private AuthScope getAuthScope(ConnectionParam param) {
// Below is the original code, but user reported that above code works.
// UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
// param.getProxyChainUserName(), param.getProxyChainPassword());
return new AuthScope(param.getProxyChainName(), param.getProxyChainPort(), param
.getProxyChainRealm().equals("") ? AuthScope.ANY_REALM : param.getProxyChainRealm());
}
public int executeMethod(HttpMethod method, HttpState state) throws IOException {
int responseCode = -1;
String hostName;
hostName = method.getURI().getHost();
method.setDoAuthentication(true);
HostConfiguration hc = null;
HttpClient requestClient;
if (isConnectionUpgrade(method)) {
requestClient = new HttpClient(new ZapHttpConnectionManager());
if (param.isUseProxy(hostName)) {
requestClient.getHostConfiguration().setProxy(param.getProxyChainName(), param.getProxyChainPort());
if (param.isUseProxyChainAuth()) {
requestClient.getState().setProxyCredentials(getAuthScope(param), getNTCredentials(param));
}
}
} else if (param.isUseProxy(hostName)) {
requestClient = clientViaProxy;
} else {
requestClient = client;
}
if (this.initiator == CHECK_FOR_UPDATES_INITIATOR) {
// Use the 'strict' SSLConnector, ie one that performs all the usual cert checks
// The 'standard' one 'trusts' everything
// This is to ensure that all 'check-for update' calls are made to the expected https urls
// without this is would be possible to intercept and change the response which could result
// in the user downloading and installing a malicious add-on
hc = new HostConfiguration() {
@Override
public synchronized void setHost(URI uri) {
try {
setHost(new HttpHost(uri.getHost(), uri.getPort(), getProtocol()));
} catch (URIException e) {
throw new IllegalArgumentException(e.toString());
}
};
};
hc.setHost(hostName, method.getURI().getPort(), new Protocol(
"https", (ProtocolSocketFactory) new SSLConnector(false), 443));
if (param.isUseProxy(hostName)) {
hc.setProxyHost(new ProxyHost(param.getProxyChainName(), param.getProxyChainPort()));
if (param.isUseProxyChainAuth()) {
requestClient.getState().setProxyCredentials(getAuthScope(param), getNTCredentials(param));
}
}
}
// ZAP: Check if a custom state is being used
if (state != null) {
// Make sure cookies are enabled
method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
}
responseCode = requestClient.executeMethod(hc, method, state);
return responseCode;
}
/**
* Tells whether or not the given {@code method} has a {@code Connection} request header with {@code Upgrade} value.
*
* @param method the method that will be checked
* @return {@code true} if the {@code method} has a connection upgrade, {@code false} otherwise
*/
private static boolean isConnectionUpgrade(HttpMethod method) {
Header connectionHeader = method.getRequestHeader("connection");
if (connectionHeader == null) {
return false;
}
return connectionHeader.getValue().toLowerCase().contains("upgrade");
}
public void shutdown() {
if (httpConnManager != null) {
httpConnManager.shutdown();
}
if (httpConnManagerProxy != null) {
httpConnManagerProxy.shutdown();
}
}
public void sendAndReceive(HttpMessage msg) throws IOException {
sendAndReceive(msg, followRedirect);
}
/**
* Do not use this unless sure what is doing. This method works but proxy may skip the pipe
* without properly handle the filter.
*
* Made this method private as it doesnt appear to be used anywhere...
*
* @param msg
* @param pipe
* @param buf
* @throws HttpException
* @throws IOException
*/
/*
* private void sendAndReceive(HttpMessage msg, HttpOutputStream pipe, byte[] buf) throws
* HttpException, IOException { sendAndReceive(msg, followRedirect, pipe, buf);
*
* }
*/
/**
* Send and receive a HttpMessage.
*
* @param msg
* @param isFollowRedirect
* @throws HttpException
* @throws IOException
* @see #sendAndReceive(HttpMessage, RedirectionValidator)
*/
public void sendAndReceive(HttpMessage msg, boolean isFollowRedirect) throws IOException {
log.debug("sendAndReceive " + msg.getRequestHeader().getMethod() + " "
+ msg.getRequestHeader().getURI() + " start");
msg.setTimeSentMillis(System.currentTimeMillis());
try {
notifyRequestListeners(msg);
if (!isFollowRedirect
|| !(msg.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST) || msg
.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.PUT))) {
// ZAP: Reauthentication when sending a message from the perspective of a User
sendAuthenticated(msg, isFollowRedirect);
return;
}
// ZAP: Reauthentication when sending a message from the perspective of a User
sendAuthenticated(msg, false);
HttpMessage temp = msg.cloneAll();
// POST/PUT method cannot be redirected by library. Need to follow by code
// loop 1 time only because httpclient can handle redirect itself after first GET.
for (int i = 0; i < 1
&& (HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode()) && temp
.getResponseHeader().getStatusCode() != HttpStatusCode.NOT_MODIFIED); i++) {
String location = temp.getResponseHeader().getHeader(HttpHeader.LOCATION);
URI baseUri = temp.getRequestHeader().getURI();
URI newLocation = new URI(baseUri, location, false);
temp.getRequestHeader().setURI(newLocation);
temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
temp.getRequestHeader().setHeader(HttpHeader.CONTENT_LENGTH, null);
// ZAP: Reauthentication when sending a message from the perspective of a User
sendAuthenticated(temp, true);
}
msg.setResponseHeader(temp.getResponseHeader());
msg.setResponseBody(temp.getResponseBody());
} finally {
msg.setTimeElapsedMillis((int) (System.currentTimeMillis() - msg.getTimeSentMillis()));
log.debug("sendAndReceive " + msg.getRequestHeader().getMethod() + " "
+ msg.getRequestHeader().getURI() + " took " + msg.getTimeElapsedMillis());
notifyResponseListeners(msg);
}
}
private void notifyRequestListeners(HttpMessage msg) {
if (IN_LISTENER.get() != null) {
// This is a request from one of the listeners - prevent infinite recursion
return;
}
try {
IN_LISTENER.set(true);
for (HttpSenderListener listener : listeners) {
try {
listener.onHttpRequestSend(msg, initiator, this);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} finally {
IN_LISTENER.set(null);
}
}
private void notifyResponseListeners(HttpMessage msg) {
if (IN_LISTENER.get() != null) {
// This is a request from one of the listeners - prevent infinite recursion
return;
}
try {
IN_LISTENER.set(true);
for (HttpSenderListener listener : listeners) {
try {
listener.onHttpResponseReceive(msg, initiator, this);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
} finally {
IN_LISTENER.set(null);
}
}
public User getUser (HttpMessage msg) {
if (this.user != null) {
// If its set for the sender it overrides the message
return user;
}
return msg.getRequestingUser();
}
// ZAP: Make sure a message that needs to be authenticated is authenticated
private void sendAuthenticated(HttpMessage msg, boolean isFollowRedirect) throws IOException {
// Modify the request message if a 'Requesting User' has been set
User forceUser = this.getUser(msg);
if (initiator != AUTHENTICATION_INITIATOR && forceUser != null)
forceUser.processMessageToMatchUser(msg);
log.debug("Sending message to: " + msg.getRequestHeader().getURI().toString());
// Send the message
send(msg, isFollowRedirect);
// If there's a 'Requesting User', make sure the response corresponds to an authenticated
// session and, if not, attempt a reauthentication and try again
if (initiator != AUTHENTICATION_INITIATOR && forceUser != null
&& !msg.getRequestHeader().isImage()
&& !forceUser.isAuthenticated(msg)) {
log.debug("First try to send authenticated message failed for " + msg.getRequestHeader().getURI()
+ ". Authenticating and trying again...");
forceUser.queueAuthentication(msg);
forceUser.processMessageToMatchUser(msg);
send(msg, isFollowRedirect);
} else
log.debug("SUCCESSFUL");
}
private void send(HttpMessage msg, boolean isFollowRedirect) throws IOException {
HttpMethod method = null;
HttpResponseHeader resHeader = null;
try {
method = runMethod(msg, isFollowRedirect);
// successfully executed;
resHeader = HttpMethodHelper.getHttpResponseHeader(method);
resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null); // replaceAll("Transfer-Encoding: chunked\r\n",
// "");
msg.setResponseHeader(resHeader);
msg.getResponseBody().setCharset(resHeader.getCharset());
msg.getResponseBody().setLength(0);
// ZAP: Do not read response body for Server-Sent Events stream
// ZAP: Moreover do not set content length to zero
if (!msg.isEventStream()) {
msg.getResponseBody().append(method.getResponseBody());
}
msg.setResponseFromTargetHost(true);
// ZAP: set method to retrieve upgraded channel later
if (method instanceof ZapGetMethod) {
msg.setUserObject(method);
}
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
private HttpMethod runMethod(HttpMessage msg, boolean isFollowRedirect) throws IOException {
HttpMethod method = null;
// no more retry
modifyUserAgent(msg);
method = helper.createRequestMethod(msg.getRequestHeader(), msg.getRequestBody());
if (!(method instanceof EntityEnclosingMethod)) {
// cant do this for EntityEnclosingMethod methods - it will fail
method.setFollowRedirects(isFollowRedirect);
}
// ZAP: Use custom HttpState if needed
User forceUser = this.getUser(msg);
if (forceUser != null) {
this.executeMethod(method, forceUser.getCorrespondingHttpState());
} else {
this.executeMethod(method, null);
}
HttpMethodHelper.updateHttpRequestHeaderSent(msg.getRequestHeader(), method);
return method;
}
public void setFollowRedirect(boolean followRedirect) {
this.followRedirect = followRedirect;
}
private void modifyUserAgent(HttpMessage msg) {
try {
// no modification to user agent if empty
if (userAgent.equals("") || msg.getRequestHeader().isEmpty()) {
return;
}
// append new user agent to existing user agent
String currentUserAgent = msg.getRequestHeader().getHeader(HttpHeader.USER_AGENT);
if (currentUserAgent == null) {
currentUserAgent = "";
}
if (currentUserAgent.indexOf(userAgent) >= 0) {
// user agent already in place, exit
return;
}
String delimiter = "";
if (!currentUserAgent.equals("") && !currentUserAgent.endsWith(" ")) {
delimiter = " ";
}
currentUserAgent = currentUserAgent + delimiter + userAgent;
msg.getRequestHeader().setHeader(HttpHeader.USER_AGENT, currentUserAgent);
} catch (Exception e) {
}
}
/**
* @return Returns the userAgent.
*/
public static String getUserAgent() {
return userAgent;
}
/**
* @param userAgent The userAgent to set.
*/
public static void setUserAgent(String userAgent) {
HttpSender.userAgent = userAgent;
}
private void setCommonManagerParams(MultiThreadedHttpConnectionManager mgr) {
// ZAP: set timeout
mgr.getParams().setSoTimeout(this.param.getTimeoutInSecs() * 1000);
mgr.getParams().setStaleCheckingEnabled(true);
// Set to arbitrary large values to prevent locking
mgr.getParams().setDefaultMaxConnectionsPerHost(10000);
mgr.getParams().setMaxTotalConnections(200000);
// to use for HttpClient 3.0.1
// mgr.getParams().setDefaultMaxConnectionsPerHost((Constant.MAX_HOST_CONNECTION > 5) ? 15 :
// 3*Constant.MAX_HOST_CONNECTION);
// mgr.getParams().setMaxTotalConnections(mgr.getParams().getDefaultMaxConnectionsPerHost()*10);
// mgr.getParams().setConnectionTimeout(60000); // use default
}
/*
* Send and receive a HttpMessage.
*
* @param msg
*
* @param isFollowRedirect
*
* @throws HttpException
*
* @throws IOException
*/
/*
* private void sendAndReceive(HttpMessage msg, boolean isFollowRedirect, HttpOutputStream pipe,
* byte[] buf) throws HttpException, IOException { log.debug("sendAndReceive " +
* msg.getRequestHeader().getMethod() + " " + msg.getRequestHeader().getURI() + " start");
* msg.setTimeSentMillis(System.currentTimeMillis());
*
* try { if (!isFollowRedirect || !
* (msg.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.POST) ||
* msg.getRequestHeader().getMethod().equalsIgnoreCase(HttpRequestHeader.PUT)) ) { send(msg,
* isFollowRedirect, pipe, buf); return; } else { send(msg, false, pipe, buf); }
*
* HttpMessage temp = msg.cloneAll(); // POST/PUT method cannot be redirected by library. Need
* to follow by code
*
* // loop 1 time only because httpclient can handle redirect itself after first GET. for (int
* i=0; i<1 && (HttpStatusCode.isRedirection(temp.getResponseHeader().getStatusCode()) &&
* temp.getResponseHeader().getStatusCode() != HttpStatusCode.NOT_MODIFIED); i++) { String
* location = temp.getResponseHeader().getHeader(HttpHeader.LOCATION); URI baseUri =
* temp.getRequestHeader().getURI(); URI newLocation = new URI(baseUri, location, false);
* temp.getRequestHeader().setURI(newLocation);
*
* temp.getRequestHeader().setMethod(HttpRequestHeader.GET);
* temp.getRequestHeader().setContentLength(0); send(temp, true, pipe, buf); }
*
* msg.setResponseHeader(temp.getResponseHeader()); msg.setResponseBody(temp.getResponseBody());
*
* } finally { msg.setTimeElapsedMillis((int)
* (System.currentTimeMillis()-msg.getTimeSentMillis())); log.debug("sendAndReceive " +
* msg.getRequestHeader().getMethod() + " " + msg.getRequestHeader().getURI() + " took " +
* msg.getTimeElapsedMillis()); } }
*/
/*
* Do not use this unless sure what is doing. This method works but proxy may skip the pipe
* without properly handle the filter.
*
* @param msg
*
* @param isFollowRedirect
*
* @param pipe
*
* @param buf
*
* @throws HttpException
*
* @throws IOException
*/
/*
* private void send(HttpMessage msg, boolean isFollowRedirect, HttpOutputStream pipe, byte[]
* buf) throws HttpException, IOException { HttpMethod method = null; HttpResponseHeader
* resHeader = null;
*
* try { method = runMethod(msg, isFollowRedirect); // successfully executed; resHeader =
* HttpMethodHelper.getHttpResponseHeader(method);
* resHeader.setHeader(HttpHeader.TRANSFER_ENCODING, null); //
* replaceAll("Transfer-Encoding: chunked\r\n", ""); msg.setResponseHeader(resHeader);
* msg.getResponseBody().setCharset(resHeader.getCharset()); msg.getResponseBody().setLength(0);
*
* // process response for each listner
*
* pipe.write(msg.getResponseHeader()); pipe.flush();
*
* if (msg.getResponseHeader().getContentLength() >= 0 &&
* msg.getResponseHeader().getContentLength() < 20480) { // save time expanding buffer in
* HttpBody if (msg.getResponseHeader().getContentLength() > 0) {
* msg.getResponseBody().setBody(method.getResponseBody()); pipe.write(msg.getResponseBody());
* pipe.flush();
*
* } } else { //byte[] buf = new byte[4096]; InputStream in = method.getResponseBodyAsStream();
*
* int len = 0; while (in != null && (len = in.read(buf)) > 0) { pipe.write(buf, 0, len);
* pipe.flush();
*
* msg.getResponseBody().append(buf, len); } } } finally { if (method != null) {
* method.releaseConnection(); } } }
*/
public static void addListener(HttpSenderListener listener) {
listeners.add(listener);
Collections.sort(listeners, getListenersComparator());
}
private static Comparator<HttpSenderListener> getListenersComparator() {
if (listenersComparator == null) {
createListenersComparator();
}
return listenersComparator;
}
private static synchronized void createListenersComparator() {
if (listenersComparator == null) {
listenersComparator = new Comparator<HttpSenderListener>() {
@Override
public int compare(HttpSenderListener o1, HttpSenderListener o2) {
int order1 = o1.getListenerOrder();
int order2 = o2.getListenerOrder();
if (order1 < order2) {
return -1;
} else if (order1 > order2) {
return 1;
}
return 0;
}
};
}
}
/**
* Set the user to scan as. If null then the current session will be used.
* @param user
*/
public void setUser(User user) {
this.user = user;
}
// ZAP: Added a getter for the client.
public HttpClient getClient() {
return this.client;
}
/**
* Sets whether or not the authentication headers ("Authorization" and "Proxy-Authorization") already present in the request
* should be removed if received an authentication challenge (status codes 401 and 407).
* <p>
* If {@code true} new authentication headers will be generated and the old ones removed otherwise the authentication
* headers already present in the request will be used to authenticate.
* <p>
* Default is {@code false}, i.e. use the headers already present in the request header.
* <p>
* Processes that reuse messages previously sent should consider setting this to {@code true}, otherwise new authentication
* challenges might fail.
*
* @param removeHeaders {@code true} if the the authentication headers already present should be removed when challenged,
* {@code false} otherwise
*/
public void setRemoveUserDefinedAuthHeaders(boolean removeHeaders) {
client.getParams().setBooleanParameter(HttpMethodDirector.PARAM_REMOVE_USER_DEFINED_AUTH_HEADERS, removeHeaders);
clientViaProxy.getParams().setBooleanParameter(HttpMethodDirector.PARAM_REMOVE_USER_DEFINED_AUTH_HEADERS, removeHeaders);
}
/**
* Sets the maximum number of retries of an unsuccessful request caused by I/O errors.
* <p>
* The default number of retries is 3.
*
* @param retries the number of retries
* @throws IllegalArgumentException if {@code retries} is negative.
* @since 2.4.0
*/
public void setMaxRetriesOnIOError(int retries) {
if (retries < 0) {
throw new IllegalArgumentException("Parameter retries must be greater or equal to zero.");
}
HttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, false);
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
clientViaProxy.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
}
/**
* Sets the maximum number of redirects that will be followed before failing with an exception.
* <p>
* The default maximum number of redirects is 100.
*
* @param maxRedirects the maximum number of redirects
* @throws IllegalArgumentException if {@code maxRedirects} is negative.
* @since 2.4.0
*/
public void setMaxRedirects(int maxRedirects) {
if (maxRedirects < 0) {
throw new IllegalArgumentException("Parameter maxRedirects must be greater or equal to zero.");
}
client.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, maxRedirects);
clientViaProxy.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, maxRedirects);
}
/**
* Sets whether or not circular redirects are allowed.
* <p>
* Circular redirects happen when a request redirects to itself, or when a same request was already accessed in a chain of
* redirects.
* <p>
* Since 2.5.0, the default is to allow circular redirects.
*
* @param allow {@code true} if circular redirects should be allowed, {@code false} otherwise
* @since 2.4.0
*/
public void setAllowCircularRedirects(boolean allow) {
client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, allow);
clientViaProxy.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, allow);
}
/**
* Sends the request of given HTTP {@code message}, following redirections per rules defined by the given {@code validator}.
* After the call to this method the given {@code message} will have the contents of the last response received (possibly
* the response of a redirection).
* <p>
* The validator is notified of each message sent and received (first message and redirections followed, if any).
*
* @param message the message that will be sent
* @param validator the validator responsible for validation of redirections
* @throws IllegalArgumentException if any of the parameters is {@code null}
* @throws IOException if an error occurred while sending the message or following the redirections
* @since TODO add version
* @see #sendAndReceive(HttpMessage, boolean)
*/
public void sendAndReceive(HttpMessage message, RedirectionValidator validator) throws IOException {
if (message == null) {
throw new IllegalArgumentException("Parameter message must not be null.");
}
if (validator == null) {
throw new IllegalArgumentException("Parameter validator must not be null.");
}
sendAndReceive(message, false);
validator.notifyMessageReceived(message);
followRedirections(message, validator);
}
/**
* Follows redirections using the response of the given {@code message}. The given {@code validator} will be called for each
* redirection received. After the call to this method the given {@code message} will have the contents of the last response
* received (possibly the response of a redirection).
* <p>
* The validator is notified of each message sent and received (first message and redirections followed, if any).
*
* @param message the message that will be sent, must not be {@code null}
* @param validator the validator responsible for validation of redirections, must not be {@code null}
* @throws IOException if an error occurred while sending the message or following the redirections
* @see #isRedirectionNeeded(int)
*/
private void followRedirections(HttpMessage message, RedirectionValidator validator) throws IOException {
HttpMessage redirectMessage = message;
int maxRedirections = client.getParams().getIntParameter(HttpClientParams.MAX_REDIRECTS, 100);
for (int i = 0; i < maxRedirections && isRedirectionNeeded(redirectMessage.getResponseHeader().getStatusCode()); i++) {
URI newLocation = extractRedirectLocation(redirectMessage);
if (newLocation == null || !validator.isValid(newLocation)) {
return;
}
redirectMessage = redirectMessage.cloneAll();
redirectMessage.getRequestHeader().setURI(newLocation);
if (isRequestRewriteNeeded(redirectMessage.getResponseHeader().getStatusCode())) {
redirectMessage.getRequestHeader().setMethod(HttpRequestHeader.GET);
redirectMessage.getRequestHeader().setHeader(HttpHeader.CONTENT_TYPE, null);
redirectMessage.getRequestHeader().setHeader(HttpHeader.CONTENT_LENGTH, null);
redirectMessage.setRequestBody("");
}
sendAndReceive(redirectMessage, false);
validator.notifyMessageReceived(redirectMessage);
// Update the response of the (original) message
message.setResponseHeader(redirectMessage.getResponseHeader());
message.setResponseBody(redirectMessage.getResponseBody());
}
}
/**
* Tells whether or not a redirection is needed based on the given status code.
* <p>
* A redirection is needed if the status code is 301, 302, 303, 307 or 308.
*
* @param statusCode the status code that will be checked
* @return {@code true} if a redirection is needed, {@code false} otherwise
* @see #isRequestRewriteNeeded(int)
*/
private static boolean isRedirectionNeeded(int statusCode) {
switch (statusCode) {
case 301:
case 302:
case 303:
case 307:
case 308:
return true;
default:
return false;
}
}
/**
* Tells whether or not the (original) request of the redirection with the given status code, should be rewritten.
* <p>
* For status codes 301, 302 and 303 the request should be changed from POST to GET when following redirections (mimicking
* the behaviour of browsers, which per <a href="https://tools.ietf.org/html/rfc7231#section-6.4">RFC 7231, Section 6.4</a>
* is now OK).
*
* @param statusCode the status code that will be checked
* @return {@code true} if the request should be rewritten, {@code false} otherwise
* @see #isRedirectionNeeded(int)
*/
private static boolean isRequestRewriteNeeded(int statusCode) {
return statusCode == 301 || statusCode == 302 || statusCode == 303;
}
/**
* Extracts a {@code URI} from the {@code Location} header of the given HTTP {@code message}.
* <p>
* If there's no {@code Location} header this method returns {@code null}.
*
* @param message the HTTP message that will processed
* @return the {@code URI} created from the value of the {@code Location} header, might be {@code null}
* @throws InvalidRedirectLocationException if the value of {@code Location} header is not a valid {@code URI}
*/
private static URI extractRedirectLocation(HttpMessage message) throws InvalidRedirectLocationException {
String location = message.getResponseHeader().getHeader(HttpHeader.LOCATION);
if (location == null) {
if (log.isDebugEnabled()) {
log.debug("No Location header found: " + message.getResponseHeader());
}
return null;
}
try {
return new URI(message.getRequestHeader().getURI(), location, true);
} catch (URIException ex) {
throw new InvalidRedirectLocationException("Invalid redirect location: " + location, location, ex);
}
}
/**
* A validator of redirections.
* <p>
* As convenience the validator will also be notified of the HTTP messages sent and received (first message and followed
* redirections, if any).
*
* @since TODO add version
*/
public interface RedirectionValidator {
/**
* Tells whether or not the given {@code redirection} is valid, to be followed.
*
* @param redirection the redirection being checked, never {@code null}
* @return {@code true} if the redirection is valid, {@code false} otherwise
*/
boolean isValid(URI redirection);
/**
* Notifies that a new message was sent and received (called for the first message and followed redirections, if any).
*
* @param message the HTTP message that was received, never {@code null}
*/
void notifyMessageReceived(HttpMessage message);
}
}
| |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tests.gl_320.glsl;
import com.jogamp.opengl.GL;
import static com.jogamp.opengl.GL2ES3.*;
import com.jogamp.opengl.GL3;
import com.jogamp.opengl.util.GLBuffers;
import com.jogamp.opengl.util.glsl.ShaderCode;
import com.jogamp.opengl.util.glsl.ShaderProgram;
import framework.BufferUtils;
import glm.glm;
import glm.mat._4.Mat4;
import framework.Profile;
import framework.Semantic;
import framework.Test;
import glm.vec._2.Vec2;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
import jgli.Texture2d;
/**
*
* @author GBarbieri
*/
public class Gl_320_glsl_discard extends Test {
public static void main(String[] args) {
Gl_320_glsl_discard gl_320_glsl_discard = new Gl_320_glsl_discard();
}
public Gl_320_glsl_discard() {
super("gl-320-glsl-discard", Profile.CORE, 3, 2);
}
private final String SHADERS_SOURCE = "glsl-discard";
private final String SHADERS_ROOT = "src/data/gl_320/glsl";
private final String TEXTURE_DIFFUSE = "kueken7_rgba8_srgb.dds";
// With DDS textures, v texture coordinate are reversed, from top to bottom
private int vertexCount = 6;
private int vertexSize = vertexCount * glf.Vertex_v2fv2f.SIZE;
private float[] vertexData = {
-1.0f, -1.0f,/**/ 0.0f, 1.0f,
+1.0f, -1.0f,/**/ 1.0f, 1.0f,
+1.0f, +1.0f,/**/ 1.0f, 0.0f,
+1.0f, +1.0f,/**/ 1.0f, 0.0f,
-1.0f, +1.0f,/**/ 0.0f, 0.0f,
-1.0f, -1.0f,/**/ 0.0f, 1.0f};
private IntBuffer vertexArrayName = GLBuffers.newDirectIntBuffer(1), bufferName = GLBuffers.newDirectIntBuffer(1),
texture2dName = GLBuffers.newDirectIntBuffer(1);
private int programName, uniformMvp, uniformDiffuse;
@Override
protected boolean begin(GL gl) {
GL3 gl3 = (GL3) gl;
boolean validated = true;
if (validated) {
validated = initProgram(gl3);
}
if (validated) {
validated = initBuffer(gl3);
}
if (validated) {
validated = initVertexArray(gl3);
}
if (validated) {
validated = initTexture(gl3);
}
return validated && checkError(gl3, "begin");
}
private boolean initProgram(GL3 gl3) {
boolean validated = true;
if (validated) {
ShaderCode vertShaderCode = ShaderCode.create(gl3, GL_VERTEX_SHADER, this.getClass(), SHADERS_ROOT, null,
SHADERS_SOURCE, "vert", null, true);
ShaderCode fragShaderCode = ShaderCode.create(gl3, GL_FRAGMENT_SHADER, this.getClass(), SHADERS_ROOT, null,
SHADERS_SOURCE, "frag", null, true);
ShaderProgram shaderProgram = new ShaderProgram();
shaderProgram.add(vertShaderCode);
shaderProgram.add(fragShaderCode);
shaderProgram.init(gl3);
programName = shaderProgram.program();
gl3.glBindAttribLocation(programName, Semantic.Attr.POSITION, "position");
gl3.glBindAttribLocation(programName, Semantic.Attr.TEXCOORD, "texCoord");
gl3.glBindFragDataLocation(programName, Semantic.Frag.COLOR, "color");
shaderProgram.link(gl3, System.out);
}
if (validated) {
uniformMvp = gl3.glGetUniformLocation(programName, "mvp");
uniformDiffuse = gl3.glGetUniformLocation(programName, "diffuse");
}
return validated & checkError(gl3, "initProgram");
}
protected boolean initBuffer(GL3 gl3) {
FloatBuffer vertexBuffer = GLBuffers.newDirectFloatBuffer(vertexData);
gl3.glGenBuffers(1, bufferName);
gl3.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(0));
gl3.glBufferData(GL_ARRAY_BUFFER, vertexSize, vertexBuffer, GL_STATIC_DRAW);
gl3.glBindBuffer(GL_ARRAY_BUFFER, 0);
BufferUtils.destroyDirectBuffer(vertexBuffer);
return checkError(gl3, "initBuffer");
}
protected boolean initTexture(GL3 gl3) {
try {
jgli.Texture2d texture = new Texture2d(jgli.Load.load(TEXTURE_ROOT + "/" + TEXTURE_DIFFUSE));
gl3.glGenTextures(1, texture2dName);
gl3.glActiveTexture(GL_TEXTURE0);
gl3.glBindTexture(GL_TEXTURE_2D, texture2dName.get(0));
gl3.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
gl3.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, texture.levels() - 1);
gl3.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
gl3.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gl3.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl3.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
jgli.Gl.Format format = jgli.Gl.translate(texture.format());
for (int level = 0; level < texture.levels();
++level) {
gl3.glTexImage2D(GL_TEXTURE_2D, level,
format.internal.value,
texture.dimensions(level)[0], texture.dimensions(level)[1],
0,
format.external.value, format.type.value,
texture.data(level));
}
} catch (IOException ex) {
Logger.getLogger(Gl_320_glsl_discard.class.getName()).log(Level.SEVERE, null, ex);
}
return checkError(gl3, "initTexture");
}
protected boolean initVertexArray(GL3 gl3) {
gl3.glGenVertexArrays(1, vertexArrayName);
gl3.glBindVertexArray(vertexArrayName.get(0));
{
gl3.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(0));
gl3.glVertexAttribPointer(Semantic.Attr.POSITION, 2, GL_FLOAT, false, glf.Vertex_v2fv2f.SIZE, 0);
gl3.glVertexAttribPointer(Semantic.Attr.TEXCOORD, 2, GL_FLOAT, false, glf.Vertex_v2fv2f.SIZE, Vec2.SIZE);
gl3.glBindBuffer(GL_ARRAY_BUFFER, 0);
gl3.glEnableVertexAttribArray(Semantic.Attr.POSITION);
gl3.glEnableVertexAttribArray(Semantic.Attr.TEXCOORD);
}
gl3.glBindVertexArray(0);
return checkError(gl3, "initVertexArray");
}
@Override
protected boolean render(GL gl) {
GL3 gl3 = (GL3) gl;
Mat4 projection = glm.perspective_((float) Math.PI * 0.25f, 4.0f / 3.0f, 0.1f, 100.0f);
Mat4 model = new Mat4(1.0f);
Mat4 mvp = projection.mul(viewMat4()).mul(model);
gl3.glViewport(0, 0, windowSize.x, windowSize.y);
gl3.glClearColor(1.0f, 0.5f, 0.0f, 1.0f);
gl3.glClear(GL_COLOR_BUFFER_BIT);
gl3.glUseProgram(programName);
gl3.glUniform1i(uniformDiffuse, 0);
gl3.glUniformMatrix4fv(uniformMvp, 1, false, mvp.toFa_(), 0);
gl3.glActiveTexture(GL_TEXTURE0);
gl3.glBindTexture(GL_TEXTURE_2D, texture2dName.get(0));
gl3.glBindVertexArray(vertexArrayName.get(0));
gl3.glDrawArraysInstanced(GL_TRIANGLES, 0, vertexCount, 1);
return true;
}
@Override
protected boolean end(GL gl) {
GL3 gl3 = (GL3) gl;
gl3.glDeleteBuffers(1, bufferName);
gl3.glDeleteProgram(programName);
gl3.glDeleteTextures(1, texture2dName);
gl3.glDeleteVertexArrays(1, vertexArrayName);
BufferUtils.destroyDirectBuffer(bufferName);
BufferUtils.destroyDirectBuffer(texture2dName);
BufferUtils.destroyDirectBuffer(vertexArrayName);
return checkError(gl3, "end");
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.application.options;
import com.intellij.openapi.application.PathMacros;
import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.hash.LinkedHashMap;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.serialization.JpsGlobalLoader;
import org.jetbrains.jps.model.serialization.PathMacroUtil;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@State(
name = "PathMacrosImpl",
storages = @Storage(value = "path.macros.xml", roamingType = RoamingType.PER_OS)
)
public class PathMacrosImpl extends PathMacros implements PersistentStateComponent<Element> {
private static final Logger LOG = Logger.getInstance(PathMacrosImpl.class);
private final Map<String, String> myLegacyMacros = new THashMap<>();
private final Map<String, String> myMacros = new LinkedHashMap<>();
private int myModificationStamp = 0;
private final ReentrantReadWriteLock myLock = new ReentrantReadWriteLock();
private final List<String> myIgnoredMacros = ContainerUtil.createLockFreeCopyOnWriteList();
private static final String MACRO_ELEMENT = JpsGlobalLoader.PathVariablesSerializer.MACRO_TAG;
private static final String NAME_ATTR = JpsGlobalLoader.PathVariablesSerializer.NAME_ATTRIBUTE;
private static final String VALUE_ATTR = JpsGlobalLoader.PathVariablesSerializer.VALUE_ATTRIBUTE;
@NonNls
public static final String IGNORED_MACRO_ELEMENT = "ignoredMacro";
private static final Set<String> SYSTEM_MACROS = new THashSet<>();
@NonNls public static final String EXT_FILE_NAME = "path.macros";
static {
SYSTEM_MACROS.add(PathMacroUtil.APPLICATION_HOME_DIR);
SYSTEM_MACROS.add(PathMacroUtil.APPLICATION_PLUGINS_DIR);
SYSTEM_MACROS.add(PathMacroUtil.PROJECT_DIR_MACRO_NAME);
SYSTEM_MACROS.add(PathMacroUtil.MODULE_WORKING_DIR_NAME);
SYSTEM_MACROS.add(PathMacroUtil.MODULE_DIR_MACRO_NAME);
SYSTEM_MACROS.add(PathMacroUtil.USER_HOME_NAME);
}
public PathMacrosImpl() {
}
public static PathMacrosImpl getInstanceEx() {
return (PathMacrosImpl)getInstance();
}
@Override
public Set<String> getUserMacroNames() {
myLock.readLock().lock();
try {
return new THashSet<>(myMacros.keySet()); // keyset should not escape the lock
}
finally {
myLock.readLock().unlock();
}
}
@NotNull
public Set<String> getToolMacroNames() {
return Collections.emptySet();
}
@Override
public Set<String> getSystemMacroNames() {
return SYSTEM_MACROS;
}
@Override
public Collection<String> getIgnoredMacroNames() {
return myIgnoredMacros;
}
@Override
public void setIgnoredMacroNames(@NotNull final Collection<String> names) {
myIgnoredMacros.clear();
myIgnoredMacros.addAll(names);
}
@Override
public void addIgnoredMacro(@NotNull String name) {
if (!myIgnoredMacros.contains(name)) myIgnoredMacros.add(name);
}
public int getModificationStamp() {
myLock.readLock().lock();
try {
return myModificationStamp;
}
finally {
myLock.readLock().unlock();
}
}
@Override
public boolean isIgnoredMacroName(@NotNull String macro) {
return myIgnoredMacros.contains(macro);
}
@Override
public Set<String> getAllMacroNames() {
return ContainerUtil.union(getUserMacroNames(), getSystemMacroNames());
}
@Override
public String getValue(String name) {
try {
myLock.readLock().lock();
return myMacros.get(name);
}
finally {
myLock.readLock().unlock();
}
}
@Override
public void removeAllMacros() {
try {
myLock.writeLock().lock();
myMacros.clear();
}
finally {
myModificationStamp++;
myLock.writeLock().unlock();
}
}
@Override
public Collection<String> getLegacyMacroNames() {
try {
myLock.readLock().lock();
// keyset should not escape the lock
return new THashSet<>(myLegacyMacros.keySet());
}
finally {
myLock.readLock().unlock();
}
}
@Override
public void setMacro(@NotNull String name, @NotNull String value) {
if (StringUtil.isEmptyOrSpaces(value)) {
return;
}
try {
myLock.writeLock().lock();
myMacros.put(name, value);
}
finally {
myModificationStamp++;
myLock.writeLock().unlock();
}
}
@Override
public void addLegacyMacro(@NotNull String name, @NotNull String value) {
try {
myLock.writeLock().lock();
myLegacyMacros.put(name, value);
myMacros.remove(name);
}
finally {
myModificationStamp++;
myLock.writeLock().unlock();
}
}
@Override
public void removeMacro(String name) {
try {
myLock.writeLock().lock();
final String value = myMacros.remove(name);
LOG.assertTrue(value != null);
}
finally {
myModificationStamp++;
myLock.writeLock().unlock();
}
}
@Nullable
@Override
public Element getState() {
try {
Element element = new Element("state");
myLock.writeLock().lock();
for (Map.Entry<String, String> entry : myMacros.entrySet()) {
String value = entry.getValue();
if (!StringUtil.isEmptyOrSpaces(value)) {
final Element macro = new Element(MACRO_ELEMENT);
macro.setAttribute(NAME_ATTR, entry.getKey());
macro.setAttribute(VALUE_ATTR, value);
element.addContent(macro);
}
}
for (final String macro : myIgnoredMacros) {
final Element macroElement = new Element(IGNORED_MACRO_ELEMENT);
macroElement.setAttribute(NAME_ATTR, macro);
element.addContent(macroElement);
}
return element;
}
finally {
myLock.writeLock().unlock();
}
}
@Override
public void loadState(@NotNull Element element) {
try {
myLock.writeLock().lock();
for (Element macro : element.getChildren(MACRO_ELEMENT)) {
final String name = macro.getAttributeValue(NAME_ATTR);
String value = macro.getAttributeValue(VALUE_ATTR);
if (name == null || value == null) {
continue;
}
if (SYSTEM_MACROS.contains(name)) {
continue;
}
if (value.length() > 1 && value.charAt(value.length() - 1) == '/') {
value = value.substring(0, value.length() - 1);
}
myMacros.put(name, value);
}
for (Element macroElement : element.getChildren(IGNORED_MACRO_ELEMENT)) {
String ignoredName = macroElement.getAttributeValue(NAME_ATTR);
if (!StringUtil.isEmpty(ignoredName) && !myIgnoredMacros.contains(ignoredName)) {
myIgnoredMacros.add(ignoredName);
}
}
}
finally {
myModificationStamp++;
myLock.writeLock().unlock();
}
}
public void addMacroReplacements(ReplacePathToMacroMap result) {
for (String name : getUserMacroNames()) {
String value = getValue(name);
if (!StringUtil.isEmptyOrSpaces(value)) {
result.addMacroReplacement(value, name);
}
}
}
public void addMacroExpands(ExpandMacroToPathMap result) {
for (String name : getUserMacroNames()) {
String value = getValue(name);
if (!StringUtil.isEmptyOrSpaces(value)) {
result.addMacroExpand(name, value);
}
}
myLock.readLock().lock();
try {
for (Map.Entry<String, String> entry : myLegacyMacros.entrySet()) {
result.addMacroExpand(entry.getKey(), entry.getValue());
}
}
finally {
myLock.readLock().unlock();
}
}
}
| |
package amberdb.sql.dcm;
import java.util.Date;
public class DcmWork {
String workpid;
String sortworkpid;
String subunittype_id;
String immutable;
String workno;
String subunitno;
String collection;
String form;
String biblevel;
String digitalstatus;
String title;
String creator;
String creatorstatement;
String background;
String edition;
String notes;
String summary;
String contents;
String publisher;
Date startdate;
Date enddate;
String extent;
String parentpid;
String indexes;
String accessrestrictions;
String rights;
String language;
Date datetimecreated;
String recordcreator;
Date datetimeupdated;
String recordupdater;
long version;
String childrange;
String firstpart;
Date digitalstatusdate;
String addressee;
String startchild;
String endchild;
String recordsource;
String localsystemno;
public String getWorkpid() {
return workpid;
}
public void setWorkpid(String workpid) {
this.workpid = workpid;
}
public String getSortworkpid() {
return sortworkpid;
}
public void setSortworkpid(String sortworkpid) {
this.sortworkpid = sortworkpid;
}
public String getSubunittype_id() {
return subunittype_id;
}
public void setSubunittype_id(String subunittype_id) {
this.subunittype_id = subunittype_id;
}
public String getImmutable() {
return immutable;
}
public void setImmutable(String immutable) {
this.immutable = immutable;
}
public String getWorkno() {
return workno;
}
public void setWorkno(String workno) {
this.workno = workno;
}
public String getSubunitno() {
return subunitno;
}
public void setSubunitno(String subunitno) {
this.subunitno = subunitno;
}
public String getCollection() {
return collection;
}
public void setCollection(String collection) {
this.collection = collection;
}
public String getForm() {
return form;
}
public void setForm(String form) {
this.form = form;
}
public String getBiblevel() {
return biblevel;
}
public void setBiblevel(String biblevel) {
this.biblevel = biblevel;
}
public String getDigitalstatus() {
return digitalstatus;
}
public void setDigitalstatus(String digitalstatus) {
this.digitalstatus = digitalstatus;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getCreatorstatement() {
return creatorstatement;
}
public void setCreatorstatement(String creatorstatement) {
this.creatorstatement = creatorstatement;
}
public String getBackground() {
return background;
}
public void setBackground(String background) {
this.background = background;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
public String getExtent() {
return extent;
}
public void setExtent(String extent) {
this.extent = extent;
}
public String getParentpid() {
return parentpid;
}
public void setParentpid(String parentpid) {
this.parentpid = parentpid;
}
public String getIndexes() {
return indexes;
}
public void setIndexes(String indexes) {
this.indexes = indexes;
}
public String getAccessrestrictions() {
return accessrestrictions;
}
public void setAccessrestrictions(String accessrestrictions) {
this.accessrestrictions = accessrestrictions;
}
public String getRights() {
return rights;
}
public void setRights(String rights) {
this.rights = rights;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Date getDatetimecreated() {
return datetimecreated;
}
public void setDatetimecreated(Date datetimecreated) {
this.datetimecreated = datetimecreated;
}
public String getRecordcreator() {
return recordcreator;
}
public void setRecordcreator(String recordcreator) {
this.recordcreator = recordcreator;
}
public Date getDatetimeupdated() {
return datetimeupdated;
}
public void setDatetimeupdated(Date datetimeupdated) {
this.datetimeupdated = datetimeupdated;
}
public String getRecordupdater() {
return recordupdater;
}
public void setRecordupdater(String recordupdater) {
this.recordupdater = recordupdater;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getChildrange() {
return childrange;
}
public void setChildrange(String childrange) {
this.childrange = childrange;
}
public String getFirstpart() {
return firstpart;
}
public void setFirstpart(String firstpart) {
this.firstpart = firstpart;
}
public Date getDigitalstatusdate() {
return digitalstatusdate;
}
public void setDigitalstatusdate(Date digitalstatusdate) {
this.digitalstatusdate = digitalstatusdate;
}
public String getAddressee() {
return addressee;
}
public void setAddressee(String addressee) {
this.addressee = addressee;
}
public String getStartchild() {
return startchild;
}
public void setStartchild(String startchild) {
this.startchild = startchild;
}
public String getEndchild() {
return endchild;
}
public void setEndchild(String endchild) {
this.endchild = endchild;
}
public String getRecordsource() {
return recordsource;
}
public void setRecordsource(String recordsource) {
this.recordsource = recordsource;
}
public String getLocalsystemno() {
return localsystemno;
}
public void setLocalsystemno(String localsystemno) {
this.localsystemno = localsystemno;
}
@Override
public String toString() {
return "DcmWork [workpid=" + workpid + ", sortworkpid=" + sortworkpid + ", subunittype_id="
+ subunittype_id + ", immutable=" + immutable + ", workno=" + workno
+ ", subunitno=" + subunitno + ", collection=" + collection + ", form=" + form
+ ", biblevel=" + biblevel + ", digitalstatus=" + digitalstatus + ", title="
+ title + ", creator=" + creator + ", creatorstatement=" + creatorstatement
+ ", background=" + background + ", edition=" + edition + ", notes=" + notes
+ ", summary=" + summary + ", contents=" + contents + ", publisher=" + publisher
+ ", startdate=" + startdate + ", enddate=" + enddate + ", extent=" + extent
+ ", parentpid=" + parentpid + ", indexes=" + indexes + ", accessrestrictions="
+ accessrestrictions + ", rights=" + rights + ", language=" + language
+ ", datetimecreated=" + datetimecreated + ", recordcreator=" + recordcreator
+ ", datetimeupdated=" + datetimeupdated + ", recordupdater=" + recordupdater
+ ", version=" + version + ", childrange=" + childrange + ", firstpart="
+ firstpart + ", digitalstatusdate=" + digitalstatusdate + ", addressee="
+ addressee + ", startchild=" + startchild + ", endchild=" + endchild
+ ", recordsource=" + recordsource + ", localsystemno=" + localsystemno + "]";
}
}
| |
/*
Copyright 2011-2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.zylib.gui.zygraph.realizers.KeyBehaviours;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.ZyLabelContent;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.ZyLineContent;
import com.google.security.zynamics.zylib.gui.zygraph.realizers.KeyBehaviours.UndoHistroy.CUndoManager;
import java.awt.event.KeyEvent;
public class CCursorKeyBehavior extends CAbstractKeyBehavior {
public CCursorKeyBehavior(final CUndoManager undoManager) {
super(undoManager);
}
private int getXdelta() {
int delta = 0;
if (getEvent().getKeyCode() == KeyEvent.VK_LEFT) {
delta = -1;
} else if (getEvent().getKeyCode() == KeyEvent.VK_RIGHT) {
delta = +1;
}
return delta;
}
private int getYdelta() {
int delta = 0;
if (getEvent().getKeyCode() == KeyEvent.VK_UP) {
delta = -1;
} else if (getEvent().getKeyCode() == KeyEvent.VK_DOWN) {
delta = +1;
}
return delta;
}
protected void handleNotShiftAndCtrl(final int xdelta, final int ydelta) {
final ZyLabelContent labelContent = getLabelContent();
int caretStartPos_X = getCaretStartPosX();
int mousePressed_X = getCaretMousePressedX();
final int mousePressed_Y = getCaretMousePressedY();
int caretEndPos_X = getCaretEndPosX();
int mouseReleased_X = getCaretMouseReleasedX();
final int mouseReleased_Y = getCaretMouseReleasedY();
if (xdelta != 0) {
final ZyLineContent lineContent = labelContent.getLineContent(mouseReleased_Y);
final String s = lineContent.getText() + " ";
if (xdelta > 0) {
final boolean firstIsSpace = s.charAt(caretEndPos_X) == ' ';
int endindex = 0;
for (int i = caretEndPos_X; i < s.length(); ++i) {
endindex = i;
if (firstIsSpace) {
if (s.charAt(i) != ' ') {
break;
}
} else {
if (s.charAt(i) == ' ') {
break;
}
}
}
if ((lineContent.getText().endsWith("\n") || lineContent.getText().endsWith("\r"))
&& (lineContent.getText().length() == endindex)) {
endindex -= 1;
}
caretStartPos_X = endindex;
mousePressed_X = endindex;
mouseReleased_X = endindex;
caretEndPos_X = endindex;
} else if (xdelta < 0) {
if (caretEndPos_X == 0) {
return;
}
final boolean firstIsSpace = s.charAt(caretEndPos_X - 1) == ' ';
int startindex = caretEndPos_X - 1;
for (int i = caretEndPos_X - 1; i >= 0; --i) {
if (firstIsSpace) {
if (s.charAt(i) != ' ') {
break;
}
} else {
if (s.charAt(i) == ' ') {
break;
}
}
startindex = i;
}
caretStartPos_X = startindex;
mousePressed_X = startindex;
mouseReleased_X = startindex;
caretEndPos_X = startindex;
}
mouseReleased_X = correctMouseReleasedX(mouseReleased_X, mouseReleased_Y, mousePressed_Y);
setCaret(caretStartPos_X, mousePressed_X, mousePressed_Y, caretEndPos_X, mouseReleased_X,
mouseReleased_Y);
} else if (ydelta != 0) {
handleNotShiftAndNotCtrl(0, ydelta);
}
}
protected void handleNotShiftAndNotCtrl(final int xdelta, final int ydelta) {
final ZyLabelContent labelContent = getLabelContent();
int caretStartPos_X = getCaretStartPosX();
int mousePressed_X = getCaretMousePressedX();
int mousePressed_Y = getCaretMousePressedY();
int caretEndPos_X = getCaretEndPosX();
int mouseReleased_X = getCaretMouseReleasedX();
int mouseReleased_Y = getCaretMouseReleasedY();
if (isSelection() && (xdelta != 0) && (ydelta == 0)) {
if ((mousePressed_Y <= mouseReleased_Y) && (mousePressed_X <= mouseReleased_X)) {
if (xdelta < 0) {
mouseReleased_X = mousePressed_X;
caretEndPos_X = caretStartPos_X;
mouseReleased_Y = mousePressed_Y;
} else {
mousePressed_X = mouseReleased_X;
caretStartPos_X = mouseReleased_X;
mousePressed_Y = mouseReleased_Y;
}
} else {
if (xdelta > 0) {
mouseReleased_X = mousePressed_X;
caretEndPos_X = caretStartPos_X;
mouseReleased_Y = mousePressed_Y;
} else {
mousePressed_X = mouseReleased_X;
caretStartPos_X = mouseReleased_X;
mousePressed_Y = mouseReleased_Y;
}
}
} else {
mousePressed_X = mouseReleased_X;
mousePressed_Y = mouseReleased_Y;
mousePressed_Y += ydelta;
if (mousePressed_Y < 0) {
mousePressed_Y = 0;
}
if (mousePressed_Y > (labelContent.getLineCount() - 1)) {
mousePressed_Y = labelContent.getLineCount() - 1;
}
mouseReleased_Y = mousePressed_Y;
mousePressed_X += xdelta;
if (mousePressed_X < 0) {
mousePressed_X = 0;
}
if (mousePressed_X > (labelContent.getLineContent(mouseReleased_Y).getTextLayout()
.getCharacterCount() - 1)) {
mousePressed_X =
labelContent.getLineContent(mouseReleased_Y).getTextLayout().getCharacterCount();
}
caretEndPos_X = mousePressed_X;
mouseReleased_X = mousePressed_X;
caretStartPos_X = caretEndPos_X;
}
mouseReleased_X = correctMouseReleasedX(mouseReleased_X, mouseReleased_Y, mousePressed_Y);
setCaret(caretStartPos_X, mousePressed_X, mousePressed_Y, caretEndPos_X, mouseReleased_X,
mouseReleased_Y);
}
protected void handleShiftAndCtrl(final int xdelta, final int ydelta) {
if (ydelta != 0) {
handleShiftAndNotCtrl(0, ydelta);
} else if (xdelta != 0) {
final ZyLabelContent labelContent = getLabelContent();
final ZyLineContent lineContent = labelContent.getLineContent(getCaretMouseReleasedY());
int caretStartPos_X = getCaretStartPosX();
final int mousePressed_X = getCaretMousePressedX();
final int mousePressed_Y = getCaretMousePressedY();
int caretEndPos_X = getCaretEndPosX();
int mouseReleased_X = getCaretMouseReleasedX();
final int mouseReleased_Y = getCaretMouseReleasedY();
final String s = lineContent.getText() + " ";
if (xdelta > 0) {
final boolean firstIsSpace = s.charAt(caretEndPos_X) == ' ';
int endindex = 0;
for (int i = caretEndPos_X; i < s.length(); ++i) {
endindex = i;
if (firstIsSpace) {
if (s.charAt(i) != ' ') {
break;
}
} else {
if (s.charAt(i) == ' ') {
break;
}
}
}
if ((lineContent.getText().endsWith("\n") || lineContent.getText().endsWith("\r"))
&& (lineContent.getText().length() == endindex)) {
endindex -= 1;
}
caretStartPos_X = mousePressed_X;
mouseReleased_X = endindex;
caretEndPos_X = endindex;
final boolean noReturn = getCaretEndPosX() == lineContent.getText().length();
final boolean withReturn =
lineContent.getText().endsWith("\n")
&& (getCaretEndPosX() == (lineContent.getText().length() - 1));
final boolean withCReturn =
lineContent.getText().endsWith("\r")
&& (getCaretEndPosX() == (lineContent.getText().length() - 1));
if (noReturn || withReturn || withCReturn) {
mouseReleased_X = getMaxLineLength(getCaretMousePressedY(), getCaretMouseReleasedY());
}
} else if (xdelta < 0) {
if (caretEndPos_X == 0) {
return;
}
final boolean firstIsSpace = s.charAt(caretEndPos_X - 1) == ' ';
int startindex = caretEndPos_X - 1;
for (int i = caretEndPos_X - 1; i >= 0; --i) {
if (firstIsSpace) {
if (s.charAt(i) != ' ') {
break;
}
} else {
if (s.charAt(i) == ' ') {
break;
}
}
startindex = i;
}
caretStartPos_X = mousePressed_X;
mouseReleased_X = startindex;
caretEndPos_X = startindex;
}
mouseReleased_X = correctMouseReleasedX(mouseReleased_X, mouseReleased_Y, mousePressed_Y);
setCaret(caretStartPos_X, mousePressed_X, mousePressed_Y, caretEndPos_X, mouseReleased_X,
mouseReleased_Y);
}
}
protected void handleShiftAndNotCtrl(final int xDelta, final int yDelta) {
final ZyLabelContent labelContent = getLabelContent();
int caretStartPos_X = getCaretStartPosX();
final int mousePressed_X = getCaretMousePressedX();
final int mousePressed_Y = getCaretMousePressedY();
int caretEndPos_X = getCaretEndPosX();
int mouseReleased_X = getCaretMouseReleasedX();
int mouseReleased_Y = getCaretMouseReleasedY();
final int linecount = labelContent.getLineCount();
if ((xDelta != 0) || (yDelta != 0)) {
mouseReleased_Y += yDelta;
if (mouseReleased_Y < 0) {
mouseReleased_Y = 0;
}
if (mouseReleased_Y > (linecount - 1)) {
mouseReleased_Y = linecount - 1;
}
mouseReleased_X += xDelta;
if (mouseReleased_X < 0) {
mouseReleased_X = 0;
}
int lp = mousePressed_Y;
int lr = mouseReleased_Y;
if (lp > lr) {
lp = mouseReleased_Y;
lr = mousePressed_Y;
}
int maxlength = 0;
for (int y = lp; y <= lr; ++y) {
maxlength = Math.max(maxlength, labelContent.getLineContent(y).getText().length());
}
if (mouseReleased_X > maxlength) {
mouseReleased_X = maxlength;
}
if (mouseReleased_X <= labelContent.getLineContent(mouseReleased_Y).getTextLayout()
.getCharacterCount()) {
caretEndPos_X = mouseReleased_X;
} else {
caretEndPos_X =
labelContent.getLineContent(mouseReleased_Y).getTextLayout().getCharacterCount();
}
caretStartPos_X = mousePressed_X;
}
mouseReleased_X = correctMouseReleasedX(mouseReleased_X, mouseReleased_Y, mousePressed_Y);
setCaret(caretStartPos_X, mousePressed_X, mousePressed_Y, caretEndPos_X, mouseReleased_X,
mouseReleased_Y);
}
@Override
protected void initUndoHistory() {
}
@Override
protected void updateCaret() {
final int xDelta = getXdelta();
final int yDelta = getYdelta();
if (!isShiftPressed() && !isCtrlPressed()) {
handleNotShiftAndNotCtrl(xDelta, yDelta);
} else if (isShiftPressed() && !isCtrlPressed()) {
handleShiftAndNotCtrl(xDelta, yDelta);
} else if (!isShiftPressed() && isCtrlPressed()) {
handleNotShiftAndCtrl(xDelta, yDelta);
} else if (isShiftPressed() && isCtrlPressed()) {
handleShiftAndCtrl(xDelta, yDelta);
}
}
@Override
protected void updateClipboard() {
}
@Override
protected void updateLabelContent() {
return;
}
@Override
protected void updateSelection() {
}
@Override
protected void updateUndoHistory() {
}
}
| |
package jeffaschenk.commons.parameters;
import java.util.ArrayList;
import java.util.List;
/**
* Search Criteria Object provides an Abstraction for upstream layers
* to allow the necessary Search Criteria to be specified
* for a given search.
*
* @author Jeff Schenk
*/
public class SearchCriteria implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* Ordered List of Search Restrictions
*/
private List<SearchRestriction> searchRestrictions = new ArrayList<SearchRestriction>();
/**
* Ordered List of Result Ordering
*/
private List<SearchOrder> ordering = new ArrayList<SearchOrder>();
/**
* Obtain a List of all Search Restrictions contained in this Criteria.
*
* @return List<SearchRestriction> Established Search Restrictions.
*/
public List<SearchRestriction> getSearchRestrictions() {
return searchRestrictions;
}
/**
* Obtain a List of all Search Order contained in this Criteria.
*
* @return List<SearchOrder> Established Search Order.
*/
public List<SearchOrder> getOrdering() {
return ordering;
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void eq(String name, Object value) {
this.eq(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void eq(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.EQ, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void ne(String name, Object value) {
this.ne(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void ne(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.NE, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void like(String name, Object value) {
this.like(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void like(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.LIKE, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void ilike(String name, Object value) {
this.ilike(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void ilike(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.ILIKE, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void gt(String name, Object value) {
this.gt(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void gt(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.GT, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void lt(String name, Object value) {
this.lt(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void lt(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.LT, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void le(String name, Object value) {
this.le(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void le(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.LE, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
*/
public void ge(String name, Object value) {
this.ge(name, value, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void ge(String name, Object value, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, value, SearchRestriction.Operation.GE, ignoreCase));
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param anotherValue the upper value for use within a between operation.
*/
public void between(String name, Object value, Object anotherValue) {
this.between(name, value, anotherValue, false);
}
/**
* Helper Method to provide Simple Search Expression
*
* @param name Attribute/Property/Field/Column Name
* @param value Value to be applied to Search Criteria
* @param anotherValue the upper value for use within a between operation.
* @param ignoreCase indicates if Textual String Case should be ignored or not, default is not to ignore case.
*/
public void between(String name, Object value, Object anotherValue, boolean ignoreCase) {
searchRestrictions.add(SearchRestriction.SearchRestriction(name, new Object[]{value, anotherValue}, SearchRestriction.Operation.BETWEEN, ignoreCase));
}
}
| |
/*
* Copyright (c) 2010 WiQuery team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.odlabs.wiquery.tester;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.Component;
import org.apache.wicket.Component.IVisitor;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.Page;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.behavior.IBehavior;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.FormComponentPanel;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.util.tester.ITestPageSource;
import org.apache.wicket.util.tester.ITestPanelSource;
import org.apache.wicket.util.tester.WicketTester;
import org.odlabs.wiquery.core.commons.WiQueryCoreHeaderContributor;
import org.odlabs.wiquery.tester.matchers.ComponentMatcher;
import org.odlabs.wiquery.tester.matchers.ComponentTypeMatcher;
public class WiQueryTester extends WicketTester {
public <X extends Component> X first(final MarkupContainer root,
ComponentMatcher matcher) {
CollectingVisitor<X> visitor = new CollectingVisitor<X>(matcher, true);
root.visitChildren(visitor);
return visitor.matchedComponents.isEmpty() ? null
: visitor.matchedComponents.get(0);
}
public <X extends Component> List<X> all(final MarkupContainer root,
ComponentMatcher matcher) {
CollectingVisitor<X> visitor = new CollectingVisitor<X>(matcher);
root.visitChildren(visitor);
return visitor.matchedComponents;
}
public <X extends Component> X first(final MarkupContainer root,
Class<X> componentType) {
CollectingVisitor<X> visitor = new CollectingVisitor<X>(
new ComponentTypeMatcher(componentType), true);
root.visitChildren(visitor);
return visitor.matchedComponents.get(0);
}
public <X extends Component> List<X> all(MarkupContainer root,
Class<X> componentType) {
ComponentMatcher matcher = new ComponentTypeMatcher(componentType);
CollectingVisitor<X> visitor = new CollectingVisitor<X>(matcher);
root.visitChildren(componentType, visitor);
return visitor.matchedComponents;
}
/**
* Sets the value on the input control.
*/
public void setValue(FormComponent<?> input, String value) {
getServletRequest().setParameter(input.getInputName(), value);
}
/**
* Renders a <code>Panel</code> defined in <code>TestPanelSource</code>
* inside a {@link Form}. The usage is similar to
* {@link #startPage(ITestPageSource)}. Please note that testing
* <code>Panel</code> must use the supplied
* <code>panelId<code> as a <code>Component</code> id.
*
* <pre>
* tester.startFormPanel(new TestPanelSource() {
* public Panel getTestPanel(String panelId) {
* MyData mockMyData = new MyData();
* return new MyPanel(panelId, mockMyData);
* }
* });
* </pre>
*
* @param factory
* a <code>Panel</code> factory that creates test
* <code>Panel</code> instances
* @return a rendered <code>Panel</code>
*/
public Panel startFormPanel(final ITestPanelSource factory) {
FormTestPage page = (FormTestPage) startPage(new ITestPageSource() {
private static final long serialVersionUID = 1L;
public Page getTestPage() {
return new FormTestPage(factory);
}
});
return (Panel) page.get(page.getPanelComponentPath());
}
/**
* Renders a <code>FormComponentPanel</code> defined in
* <code>TestFormComponentPanelSource</code> inside a {@link Form}. The
* usage is similar to {@link #startPage(ITestPageSource)}. Please note that
* testing <code>Panel</code> must use the supplied
* <code>panelId<code> as a <code>Component</code> id.
*
* <pre>
* tester.startFormPanel(new TestPanelSource() {
* public FormComponentPanel getTestPanel(String panelId) {
* MyData mockMyData = new MyData();
* return new MyPanel(panelId, mockMyData);
* }
* });
* </pre>
*
* @param factory
* a <code>Panel</code> factory that creates test
* <code>Panel</code> instances
* @return a rendered <code>Panel</code>
*/
public FormComponentPanel<?> startFormPanel(
final TestFormComponentPanelSource factory) {
FormTestPage page = (FormTestPage) startPage(new ITestPageSource() {
private static final long serialVersionUID = 1L;
public Page getTestPage() {
return new FormTestPage(factory);
}
});
return (FormComponentPanel<?>) page.get(page.getPanelComponentPath());
}
public RepeatingView getRepeatingView(String path) {
Page renderedPage = getLastRenderedPage();
assertComponent(path, RepeatingView.class);
RepeatingView rv = (RepeatingView) renderedPage.get(path);
return rv;
}
public ListView<?> getListView(String path) {
Page renderedPage = getLastRenderedPage();
assertComponent(path, ListView.class);
ListView<?> rv = (ListView<?>) renderedPage.get(path);
return rv;
}
public List<IHeaderContributor> getHeaderContributors() {
Page renderedPage = getLastRenderedPage();
final List<IHeaderContributor> contributors = new ArrayList<IHeaderContributor>();
renderedPage.visitChildren(new IVisitor<Component>() {
public Object component(Component component) {
for (IBehavior behavior : component.getBehaviors())
if (behavior instanceof HeaderContributor
|| behavior instanceof WiQueryCoreHeaderContributor)
contributors.add((IHeaderContributor) behavior);
return Component.IVisitor.CONTINUE_TRAVERSAL;
}
});
return contributors;
}
public WiQueryCoreHeaderContributor getWiQueryCoreHeaderContributor() {
List<IHeaderContributor> contributors = getHeaderContributors();
for(IHeaderContributor contributor : contributors)
{
if(contributor instanceof WiQueryCoreHeaderContributor)
return (WiQueryCoreHeaderContributor) contributor;
else if(contributor instanceof HeaderContributor)
{
for(IHeaderContributor innercontributor : ((HeaderContributor)contributor).getHeaderContributors())
{
if(innercontributor instanceof WiQueryCoreHeaderContributor)
return (WiQueryCoreHeaderContributor) innercontributor;
}
}
}
return null;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation;
import com.azure.cosmos.implementation.apachecommons.lang.StringUtils;
import com.azure.cosmos.models.ConflictResolutionPolicy;
import com.azure.cosmos.models.IndexingPolicy;
import com.azure.cosmos.models.ModelBridgeInternal;
import com.azure.cosmos.models.PartitionKeyDefinition;
import com.azure.cosmos.models.UniqueKeyPolicy;
import com.fasterxml.jackson.databind.node.ObjectNode;
import static com.azure.cosmos.BridgeInternal.setProperty;
/**
* Represents a document collection in the Azure Cosmos DB database service. A collection is a named logical container
* for documents.
* <p>
* A database may contain zero or more named collections and each collection consists of zero or more JSON documents.
* Being schema-free, the documents in a collection do not need to share the same structure or fields. Since collections
* are application resources, they can be authorized using either the master key or resource keys.
*/
public final class DocumentCollection extends Resource {
private IndexingPolicy indexingPolicy;
private UniqueKeyPolicy uniqueKeyPolicy;
private PartitionKeyDefinition partitionKeyDefinition;
/**
* Constructor.
*
* @param objectNode the {@link ObjectNode} that represent the
* {@link JsonSerializable}
*/
public DocumentCollection(ObjectNode objectNode) {
super(objectNode);
}
/**
* Initialize a document collection object.
*/
public DocumentCollection() {
super();
}
/**
* Sets the id and returns the document collection
* @param id the name of the resource.
* @return
*/
public DocumentCollection setId(String id){
super.setId(id);
return this;
}
/**
* Initialize a document collection object from json string.
*
* @param jsonString the json string that represents the document collection.
*/
public DocumentCollection(String jsonString) {
super(jsonString);
}
/**
* Gets the indexing policy.
*
* @return the indexing policy.
*/
public IndexingPolicy getIndexingPolicy() {
if (this.indexingPolicy == null) {
if (super.has(Constants.Properties.INDEXING_POLICY)) {
this.indexingPolicy = super.getObject(Constants.Properties.INDEXING_POLICY, IndexingPolicy.class);
} else {
this.indexingPolicy = new IndexingPolicy();
}
}
return this.indexingPolicy;
}
/**
* Sets the indexing policy.
*
* @param indexingPolicy the indexing policy.
*/
public void setIndexingPolicy(IndexingPolicy indexingPolicy) {
if (indexingPolicy == null) {
throw new IllegalArgumentException("IndexingPolicy cannot be null.");
}
this.indexingPolicy = indexingPolicy;
}
/**
* Gets the collection's partition key definition.
*
* @return the partition key definition.
*/
public PartitionKeyDefinition getPartitionKey() {
if (this.partitionKeyDefinition == null) {
if (super.has(Constants.Properties.PARTITION_KEY)) {
this.partitionKeyDefinition = super.getObject(Constants.Properties.PARTITION_KEY, PartitionKeyDefinition.class);
} else {
this.partitionKeyDefinition = new PartitionKeyDefinition();
}
}
return this.partitionKeyDefinition;
}
/**
* Sets the collection's partition key definition.
*
* @param partitionKey the partition key definition.
*/
public void setPartitionKey(PartitionKeyDefinition partitionKey) {
if (partitionKey == null) {
throw new IllegalArgumentException("partitionKeyDefinition cannot be null.");
}
this.partitionKeyDefinition = partitionKey;
}
/**
* Gets the collection's default time-to-live value.
*
* @return the default time-to-live value in seconds.
*/
public Integer getDefaultTimeToLive() {
if (super.has(Constants.Properties.DEFAULT_TTL)) {
return super.getInt(Constants.Properties.DEFAULT_TTL);
}
return null;
}
/**
* Sets the collection's default time-to-live value.
* <p>
* The default time-to-live value on a collection is an optional property. If set, the documents within the collection
* expires after the specified number of seconds since their last write time. The value of this property should be one of the following:
* <p>
* null - indicates evaluation of time-to-live is disabled and documents within the collection will never expire, regardless whether
* individual documents have their time-to-live set.
* <p>
* nonzero positive integer - indicates the default time-to-live value for all documents within the collection. This value can be overridden
* by individual documents' time-to-live value.
* <p>
* -1 - indicates by default all documents within the collection never expire. This value can be overridden by individual documents'
* time-to-live value.
*
* @param timeToLive the default time-to-live value in seconds.
*/
public void setDefaultTimeToLive(Integer timeToLive) {
// a "null" value is represented as a missing element on the wire.
// setting timeToLive to null should remove the property from the property bag.
if (timeToLive != null) {
setProperty(this, Constants.Properties.DEFAULT_TTL, timeToLive);
} else if (super.has(Constants.Properties.DEFAULT_TTL)) {
remove(Constants.Properties.DEFAULT_TTL);
}
}
/**
* Sets the analytical storage time to live in seconds for items in a container from the Azure Cosmos DB service.
*
* It is an optional property. A valid value must be either a nonzero positive integer, '-1', or 0.
* By default, AnalyticalStorageTimeToLive is set to 0 meaning the analytical store is turned off for the container;
* -1 means documents in analytical store never expire.
* The unit of measurement is seconds. The maximum allowed value is 2147483647.
*
* @param timeToLive the analytical storage time to live in seconds.
* @return the CosmosContainerProperties.
*/
public void setAnalyticalStoreTimeToLiveInSeconds(Integer timeToLive) {
// a "null" value is represented as a missing element on the wire.
// setting timeToLive to null should remove the property from the property bag.
if (timeToLive != null) {
super.set(Constants.Properties.ANALYTICAL_STORAGE_TTL, timeToLive);
} else if (super.has(Constants.Properties.ANALYTICAL_STORAGE_TTL)) {
super.remove(Constants.Properties.ANALYTICAL_STORAGE_TTL);
}
}
/**
* Gets the analytical storage time to live in seconds for items in a container from the Azure Cosmos DB service.
*
* It is an optional property. A valid value must be either a nonzero positive integer, '-1', or 0.
* By default, AnalyticalStorageTimeToLive is set to 0 meaning the analytical store is turned off for the container;
* -1 means documents in analytical store never expire.
* The unit of measurement is seconds. The maximum allowed value is 2147483647.
*
* @return analytical ttl
*/
public Integer getAnalyticalStoreTimeToLiveInSeconds() {
if (super.has(Constants.Properties.ANALYTICAL_STORAGE_TTL)) {
return super.getInt(Constants.Properties.ANALYTICAL_STORAGE_TTL);
}
return null;
}
/**
* Sets the Uni that guarantees uniqueness of documents in collection in the Azure Cosmos DB service.
* @return UniqueKeyPolicy
*/
public UniqueKeyPolicy getUniqueKeyPolicy() {
// Thread safe lazy initialization for case when collection is cached (and is basically readonly).
if (this.uniqueKeyPolicy == null) {
this.uniqueKeyPolicy = super.getObject(Constants.Properties.UNIQUE_KEY_POLICY, UniqueKeyPolicy.class);
if (this.uniqueKeyPolicy == null) {
this.uniqueKeyPolicy = new UniqueKeyPolicy();
}
}
return this.uniqueKeyPolicy;
}
public void setUniqueKeyPolicy(UniqueKeyPolicy uniqueKeyPolicy) {
if (uniqueKeyPolicy == null) {
throw new IllegalArgumentException("uniqueKeyPolicy cannot be null.");
}
this.uniqueKeyPolicy = uniqueKeyPolicy;
setProperty(this, Constants.Properties.UNIQUE_KEY_POLICY, uniqueKeyPolicy);
}
/**
* Gets the conflictResolutionPolicy that is used for resolving conflicting writes
* on documents in different regions, in a collection in the Azure Cosmos DB service.
*
* @return ConflictResolutionPolicy
*/
public ConflictResolutionPolicy getConflictResolutionPolicy() {
return super.getObject(Constants.Properties.CONFLICT_RESOLUTION_POLICY, ConflictResolutionPolicy.class);
}
/**
* Sets the conflictResolutionPolicy that is used for resolving conflicting writes
* on documents in different regions, in a collection in the Azure Cosmos DB service.
*
* @param value ConflictResolutionPolicy to be used.
*/
public void setConflictResolutionPolicy(ConflictResolutionPolicy value) {
if (value == null) {
throw new IllegalArgumentException("CONFLICT_RESOLUTION_POLICY cannot be null.");
}
setProperty(this, Constants.Properties.CONFLICT_RESOLUTION_POLICY, value);
}
/**
* Gets the self-link for documents in a collection.
*
* @return the document link.
*/
public String getDocumentsLink() {
return String.format("%s/%s",
StringUtils.stripEnd(super.getSelfLink(), "/"),
super.getString(Constants.Properties.DOCUMENTS_LINK));
}
/**
* Gets the self-link for stored procedures in a collection.
*
* @return the stored procedures link.
*/
public String getStoredProceduresLink() {
return String.format("%s/%s",
StringUtils.stripEnd(super.getSelfLink(), "/"),
super.getString(Constants.Properties.STORED_PROCEDURES_LINK));
}
/**
* Gets the self-link for triggers in a collection.
*
* @return the trigger link.
*/
public String getTriggersLink() {
return StringUtils.removeEnd(this.getSelfLink(), "/") +
"/" + super.getString(Constants.Properties.TRIGGERS_LINK);
}
/**
* Gets the self-link for user defined functions in a collection.
*
* @return the user defined functions link.
*/
public String getUserDefinedFunctionsLink() {
return StringUtils.removeEnd(this.getSelfLink(), "/") +
"/" + super.getString(Constants.Properties.USER_DEFINED_FUNCTIONS_LINK);
}
/**
* Gets the self-link for conflicts in a collection.
*
* @return the conflicts link.
*/
public String getConflictsLink() {
return StringUtils.removeEnd(this.getSelfLink(), "/") +
"/" + super.getString(Constants.Properties.CONFLICTS_LINK);
}
public void populatePropertyBag() {
super.populatePropertyBag();
if (this.indexingPolicy == null) {
this.getIndexingPolicy();
}
if (this.uniqueKeyPolicy == null) {
this.getUniqueKeyPolicy();
}
if (this.partitionKeyDefinition != null) {
ModelBridgeInternal.populatePropertyBag(this.partitionKeyDefinition);
setProperty(this, Constants.Properties.PARTITION_KEY, this.partitionKeyDefinition);
}
ModelBridgeInternal.populatePropertyBag(this.indexingPolicy);
ModelBridgeInternal.populatePropertyBag(this.uniqueKeyPolicy);
setProperty(this, Constants.Properties.INDEXING_POLICY, this.indexingPolicy);
setProperty(this, Constants.Properties.UNIQUE_KEY_POLICY, this.uniqueKeyPolicy);
}
@Override
public boolean equals(Object obj) {
if (obj == null || !DocumentCollection.class.isAssignableFrom(obj.getClass())) {
return false;
}
DocumentCollection typedObj = (DocumentCollection) obj;
return typedObj.getResourceId().equals(this.getResourceId());
}
@Override
public int hashCode() {
return this.getResourceId().hashCode();
}
@Override
public String toJson() {
this.populatePropertyBag();
return super.toJson();
}
}
| |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.bgfx;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Custom allocator. When custom allocator is not specified, library uses default CRT allocator. The library assumes custom allocator is thread safe.
*
* <h3>Member documentation</h3>
*
* <ul>
* <li>{@code vtbl} – the allocator virtual table</li>
* </ul>
*
* <h3>Layout</h3>
*
* <pre><code>struct bgfx_allocator_interface_t {
const bgfx_allocator_vtbl_t * vtbl;
}</code></pre>
*/
public class BGFXAllocatorInterface extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
VTBL;
static {
Layout layout = __struct(
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
VTBL = layout.offsetof(0);
}
BGFXAllocatorInterface(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link BGFXAllocatorInterface} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public BGFXAllocatorInterface(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** Returns a {@link BGFXAllocatorVtbl} view of the struct pointed to by the {@code vtbl} field. */
public BGFXAllocatorVtbl vtbl() { return nvtbl(address()); }
/** Sets the address of the specified {@link BGFXAllocatorVtbl} to the {@code vtbl} field. */
public BGFXAllocatorInterface vtbl(BGFXAllocatorVtbl value) { nvtbl(address(), value); return this; }
/** Unsafe version of {@link #set(BGFXAllocatorInterface) set}. */
public BGFXAllocatorInterface nset(long struct) {
memCopy(struct, address(), SIZEOF);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public BGFXAllocatorInterface set(BGFXAllocatorInterface src) {
return nset(src.address());
}
// -----------------------------------
/** Returns a new {@link BGFXAllocatorInterface} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static BGFXAllocatorInterface malloc() {
return create(nmemAlloc(SIZEOF));
}
/** Returns a new {@link BGFXAllocatorInterface} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static BGFXAllocatorInterface calloc() {
return create(nmemCalloc(1, SIZEOF));
}
/** Returns a new {@link BGFXAllocatorInterface} instance allocated with {@link BufferUtils}. */
public static BGFXAllocatorInterface create() {
return new BGFXAllocatorInterface(BufferUtils.createByteBuffer(SIZEOF));
}
/** Returns a new {@link BGFXAllocatorInterface} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static BGFXAllocatorInterface create(long address) {
return address == NULL ? null : new BGFXAllocatorInterface(address, null);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer malloc(int capacity) {
return create(nmemAlloc(capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static Buffer calloc(int capacity) {
return create(nmemCalloc(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static Buffer create(int capacity) {
return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
}
/**
* Create a {@link BGFXAllocatorInterface.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static Buffer create(long address, int capacity) {
return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
}
// -----------------------------------
/** Returns a new {@link BGFXAllocatorInterface} instance allocated on the thread-local {@link MemoryStack}. */
public static BGFXAllocatorInterface mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@link BGFXAllocatorInterface} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static BGFXAllocatorInterface callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@link BGFXAllocatorInterface} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static BGFXAllocatorInterface mallocStack(MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@link BGFXAllocatorInterface} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static BGFXAllocatorInterface callocStack(MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity) {
return mallocStack(capacity, stackGet());
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity) {
return callocStack(capacity, stackGet());
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer mallocStack(int capacity, MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link BGFXAllocatorInterface.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static Buffer callocStack(int capacity, MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #vtbl}. */
public static BGFXAllocatorVtbl nvtbl(long struct) { return BGFXAllocatorVtbl.create(memGetAddress(struct + BGFXAllocatorInterface.VTBL)); }
/** Unsafe version of {@link #vtbl(BGFXAllocatorVtbl) vtbl}. */
public static void nvtbl(long struct, BGFXAllocatorVtbl value) { memPutAddress(struct + BGFXAllocatorInterface.VTBL, value.address()); }
/**
* Validates pointer members that should not be {@code NULL}.
*
* @param struct the struct to validate
*/
public static void validate(long struct) {
long vtbl = memGetAddress(struct + BGFXAllocatorInterface.VTBL);
checkPointer(vtbl);
BGFXAllocatorVtbl.validate(vtbl);
}
/**
* Calls {@link #validate(long)} for each struct contained in the specified struct array.
*
* @param array the struct array to validate
* @param count the number of structs in {@code array}
*/
public static void validate(long array, int count) {
for ( int i = 0; i < count; i++ )
validate(array + i * SIZEOF);
}
// -----------------------------------
/** An array of {@link BGFXAllocatorInterface} structs. */
public static class Buffer extends StructBuffer<BGFXAllocatorInterface, Buffer> implements NativeResource {
/**
* Creates a new {@link BGFXAllocatorInterface.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link BGFXAllocatorInterface#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected BGFXAllocatorInterface newInstance(long address) {
return new BGFXAllocatorInterface(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
/** Returns a {@link BGFXAllocatorVtbl} view of the struct pointed to by the {@code vtbl} field. */
public BGFXAllocatorVtbl vtbl() { return BGFXAllocatorInterface.nvtbl(address()); }
/** Sets the address of the specified {@link BGFXAllocatorVtbl} to the {@code vtbl} field. */
public BGFXAllocatorInterface.Buffer vtbl(BGFXAllocatorVtbl value) { BGFXAllocatorInterface.nvtbl(address(), value); return this; }
}
}
| |
package jsky.app.ot.gemini.obslog;
import edu.gemini.spModel.dataset.*;
import edu.gemini.spModel.event.ObsExecEvent;
import edu.gemini.spModel.obslog.ObsLog;
import edu.gemini.spModel.obsrecord.ObsVisit;
import edu.gemini.spModel.obsrecord.UniqueConfig;
import edu.gemini.spModel.type.DisplayableSpType;
import jsky.app.ot.OTOptions;
import jsky.app.ot.util.OtColor;
import jsky.app.ot.util.Resources;
import jsky.util.gui.DropDownListBoxWidget;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.awt.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.*;
import java.util.List;
/**
* GUI component for the ObsLog editor component.
* @author rnorris
*/
public class ObslogGUI extends JPanel {
private final DataAnalysisComponent tabDataAnalysis = new DataAnalysisComponent("Data Analysis");
private final VisitsComponent tabVisits = new VisitsComponent("Visits");
private final CommentsComponent tabComments = new CommentsComponent("Comments");
static final DateFormat OBSLOG_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z") {{
setTimeZone(TimeZone.getTimeZone("UTC"));
}};
private static final Icon BLANK = Resources.getIcon("eclipse/blank.gif");
private static final Icon GREEN_DOT = Resources.getIcon("bullet/bullet_green.png");
private static final Icon GREY_DOT = Resources.getIcon("bullet/bullet_grey.png");
private static final Icon ORANGE_DOT = Resources.getIcon("bullet/bullet_orange.png");
private static final Icon PALE_GREEN_DOT = Resources.getIcon("bullet/bullet_pale_green.gif");
private static final Icon RED_DOT = Resources.getIcon("bullet/bullet_red.png");
private static final Icon WHITE_DOT = Resources.getIcon("bullet/bullet_white.gif");
private static final Map<DataflowStatus, Icon> STATUS_ICON = new HashMap<>();
static {
STATUS_ICON.put(DataflowStatus.Archived$.MODULE$, PALE_GREEN_DOT);
STATUS_ICON.put(DataflowStatus.NeedsQa$.MODULE$, WHITE_DOT);
STATUS_ICON.put(DataflowStatus.SyncPending$.MODULE$, GREY_DOT);
STATUS_ICON.put(DataflowStatus.CheckRequested$.MODULE$, ORANGE_DOT);
STATUS_ICON.put(DataflowStatus.UpdateFailure$.MODULE$, RED_DOT);
STATUS_ICON.put(DataflowStatus.UpdateInProgress$.MODULE$, GREY_DOT);
STATUS_ICON.put(DataflowStatus.SummitOnly$.MODULE$, GREY_DOT);
STATUS_ICON.put(DataflowStatus.Diverged$.MODULE$, GREY_DOT);
STATUS_ICON.put(DataflowStatus.InSync$.MODULE$, GREEN_DOT);
}
private static final String ZONE_STRING = ZoneId.systemDefault().getDisplayName(TextStyle.SHORT, Locale.getDefault());
private static final TableCellRenderer STATUS_RENDERER = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
final JLabel lab = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
final DataflowStatus dfs = (DataflowStatus) value;
lab.setText(dfs.description());
final Icon icon = STATUS_ICON.get(dfs);
lab.setIcon(icon != null ? icon : BLANK);
return lab;
}
};
public ObslogGUI() {
setLayout(new BorderLayout());
add(new JTabbedPane() {{
add(tabComments);
add(tabDataAnalysis);
add(tabVisits);
}}, BorderLayout.CENTER);
}
/**
* Sets the data object, replacing or updating the content as appropriate.
*/
void setup(ObsLog obsLog) {
// And tell the tabs that the world has changed.
tabDataAnalysis.setObsLog(obsLog);
tabVisits.setObsLog(obsLog);
tabComments.setObsLog(obsLog);
}
class AbstractDatasetRecordTable extends JTable implements ObslogTableModels {
protected AbstractDatasetRecordTable() {
setAutoResizeMode(AUTO_RESIZE_OFF);
}
protected AbstractDatasetRecordTable(TableModel model) {
super(model);
setAutoResizeMode(AUTO_RESIZE_OFF);
}
public TableCellRenderer getCellRenderer(int row, int col) {
final TableCellRenderer renderer = super.getCellRenderer(row, col);
if (renderer instanceof JLabel && dataModel instanceof AbstractDatasetRecordTableModel) {
if (((AbstractDatasetRecordTableModel) dataModel).isUnavailable(row)) {
((Component) renderer).setForeground(Color.LIGHT_GRAY);
} else {
((Component) renderer).setForeground(null);
}
}
return renderer;
}
/**
* This is very, very bad.
* (Shane, and Java Swing I suppose, are to blame for this one.)
*/
void sizeColumnsToFitData() {
final TableColumnModel colModel = getColumnModel();
final TableModel model = getModel();
final int rows = model.getRowCount();
final TableCellRenderer headerRenderer;
try {
headerRenderer = getDefaultRenderer(String.class);
} catch (NullPointerException ex) {
// Sorry, the table doesn't seem to be ready to be re-sized.
return;
}
for (int col = 0; col < model.getColumnCount(); ++col) {
// Start with the width of the column header
Component component = headerRenderer.getTableCellRendererComponent(this, model.getColumnName(col), false, false, -1, col);
int size = component.getPreferredSize().width;
// Check the width of each item in the column to get the maximum width
for (int row = 0; row < rows; ++row) {
final TableCellRenderer renderer = getCellRenderer(row, col);
component = prepareRenderer(renderer, row, col);
final int tmp = component.getPreferredSize().width;
if (tmp > size) size = tmp;
}
size += 10; // add a bit of padding
// Resize the column
final TableColumn tc = colModel.getColumn(col);
tc.setPreferredWidth(size);
tc.setMinWidth(size);
tc.setMaxWidth(size);
}
}
}
/**
* Functional interface for extracting a value of an arbitrary type A from
* a DatasetRecord.
*/
interface DatasetRecordExtractor<A> {
A getValue(DatasetRecord r);
}
/**
* Information extracted from an ActiveRequest object for formatting and
* display.
*/
static final class RequestDetail {
final QaRequestStatus status;
final Instant when;
final int retry;
public RequestDetail(QaRequestStatus status, Instant when, int retry) {
this.status = status;
this.when = when;
this.retry = retry;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final RequestDetail that = (RequestDetail) o;
return Objects.equals(retry, that.retry) &&
Objects.equals(status, that.status) &&
Objects.equals(when, that.when);
}
@Override
public int hashCode() {
return Objects.hash(status, when, retry);
}
public String formatWhen() {
final ZoneId z = ZoneId.systemDefault();
final OffsetDateTime whenOff = OffsetDateTime.ofInstant(when, z);
final OffsetDateTime nowOff = OffsetDateTime.ofInstant(Instant.now(), z);
final LocalDate whenDate = whenOff.toLocalDate();
final LocalDate nowDate = nowOff.toLocalDate();
final DateTimeFormatter dateFmt = DateTimeFormatter.ISO_LOCAL_DATE;
final String timeString = DateTimeFormatter.ISO_LOCAL_TIME.format(whenOff.toLocalTime());
return (whenDate.equals(nowDate)) ? timeString :
dateFmt.format(whenDate) + " " + timeString;
}
public static RequestDetail fromActiveRequest(SummitState.ActiveRequest ar) {
return new RequestDetail(ar.status(), ar.when(), ar.retryCount());
}
public static Optional<RequestDetail> fromSummitState(SummitState ss) {
return (ss instanceof SummitState.ActiveRequest) ?
Optional.of(fromActiveRequest((SummitState.ActiveRequest) ss)) :
Optional.empty();
}
public static Optional<RequestDetail> fromDatasetRecord(DatasetRecord dr) {
return fromSummitState(dr.exec().summit());
}
}
/**
* Component that shows a table of {@link edu.gemini.spModel.dataset.DatasetExecRecord}s with
* editable fields for QA State. Editing is disabled unless the OT is running in on site mode.
*
* @author rnorris
*/
class DataAnalysisComponent extends JPanel implements ObslogTableModels {
private final DataAnalysisTable table = new DataAnalysisTable();
private final JPanel editArea = new Editor();
private Optional<Boolean> isStaffMode = Optional.empty();
public DataAnalysisComponent(String name) {
super(new BorderLayout());
setName(name);
}
private void reconfigure() {
final boolean isStaff = OTOptions.isStaffGlobally();
// if (isStaffMode.forall(_ =/= isStaff)) {
if (!isStaffMode.isPresent() || isStaffMode.get() != isStaff) {
isStaffMode = Optional.of(isStaff);
removeAll();
add(new JScrollPane(table) {{
if (isStaff) setBorder(BorderFactory.createEmptyBorder());
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}}, BorderLayout.CENTER);
if (isStaff) {
final JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(new Header("Select multiple rows for bulk updating."), BorderLayout.NORTH);
editPanel.add(editArea, BorderLayout.CENTER);
add(editPanel, BorderLayout.SOUTH);
}
}
}
void setObsLog(final ObsLog obsLog) {
reconfigure();
table.setModel(new DatasetAnalysisTableModel(obsLog));
table.setEnabled(true);
editArea.setEnabled(true);
}
// OT-424: bulk editing support
class Editor extends JPanel implements ListSelectionListener {
final JComboBox<DatasetQaState> qa;
final JTextPane textPane = new JTextPane() {{
setBackground(OtColor.BG_GREY);
setContentType("text/html");
setEditable(false);
putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
}};
final JScrollPane scrollPane = new JScrollPane(textPane) {{
setBorder(BorderFactory.createEmptyBorder());
setPreferredSize(new Dimension(1, 50));
}};
boolean adjusting; // sigh
public Editor() {
super(new GridBagLayout());
setBorder(BorderFactory.createEmptyBorder(10,5,5,5));
// QA State
add(new JLabel("QA State:"), new GridBagConstraints() {{
gridx = 0;
gridy = 0;
insets = new Insets(0, 2, 0, 5);
}});
add(qa = new DropDownListBoxWidget<DatasetQaState>() {{
setChoices(DatasetQaState.values());
setRenderer(new SpTypeCellRenderer());
setSelectedItem(null);
addActionListener(ae -> {
if (!adjusting) {
setCommonValue(DatasetAnalysisTableModel.COL_QA_STATE, getSelectedItem());
}
});
}}, new GridBagConstraints() {{
gridx = 1;
gridy = 0;
anchor = WEST;
weightx = 1.0;
}});
table.editArea = this;
table.getSelectionModel().addListSelectionListener(this);
}
public void setEnabled(boolean enable) {
super.setEnabled(enable);
qa.setEnabled(enable);
if (!enable) {
adjusting = true;
qa.setSelectedItem(null);
textPane.setText(null);
adjusting = false;
}
}
public void valueChanged(ListSelectionEvent lse) {
if (lse.getValueIsAdjusting() || table.adjusting) return;
final ListSelectionModel lsm = (ListSelectionModel) lse.getSource();
if (!lsm.isSelectionEmpty()) {
setEnabled(true);
adjusting = true;
qa.setSelectedItem(getCommonValue(dr -> dr.qa().qaState).orElse(null));
final Optional<RequestDetail> detail = getCommonValue(RequestDetail::fromDatasetRecord).orElse(Optional.empty());
remove(scrollPane);
detail.ifPresent(d -> {
add(scrollPane, new GridBagConstraints() {{
gridx = 0;
gridy = 1;
gridwidth = 2;
fill = BOTH;
weightx = 1.0;
weighty = 1.0;
insets = new Insets(10, 0, 0, 0);
}});
textPane.setText(String.format("<html><body><b>%s (%s)</b> %s</body></html>", d.formatWhen(), ZONE_STRING, d.status.description()));
textPane.setCaretPosition(0);
});
revalidate();
adjusting = false;
} else {
setEnabled(false);
}
}
private <A> Optional<A> getCommonValue(DatasetRecordExtractor<A> ex) {
final ListSelectionModel lsm = table.getSelectionModel();
A a = null;
if (!lsm.isSelectionEmpty()) {
final DatasetAnalysisTableModel model = (DatasetAnalysisTableModel) table.getModel();
for (int row = lsm.getMinSelectionIndex(); row <= lsm.getMaxSelectionIndex(); row++) {
if (lsm.isSelectedIndex(row)) {
final A a0 = ex.getValue(model.getRecordAt(row));
if (a == null) {
a = a0;
} else if (!a.equals(a0)) {
a = null;
break;
}
}
}
}
return Optional.ofNullable(a);
}
private void setCommonValue(int col, Object value) {
final ListSelectionModel lsm = table.getSelectionModel();
if (!lsm.isSelectionEmpty()) {
final TableModel model = table.getModel();
for (int row = lsm.getMinSelectionIndex(); row <= lsm.getMaxSelectionIndex(); row++) {
if (lsm.isSelectedIndex(row)) {
model.setValueAt(value, row, col);
}
}
}
}
}
final class SpTypeCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList<?> arg0, Object o, int arg2, boolean arg3, boolean arg4) {
if (o != null) {
if (o instanceof DisplayableSpType) {
o = ((DisplayableSpType) o).displayValue();
}
}
return super.getListCellRendererComponent(arg0, o, arg2, arg3, arg4);
}
}
final class DataAnalysisTable extends AbstractDatasetRecordTable {
JPanel editArea;
boolean adjusting = false;
public DataAnalysisTable() {
setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
@Override
public void setModel(TableModel newModel) {
// OT-640: Preserve selection
if (newModel instanceof DatasetAnalysisTableModel && getModel() instanceof DatasetAnalysisTableModel) {
final DatasetAnalysisTableModel prev = (DatasetAnalysisTableModel) getModel();
final DatasetAnalysisTableModel next = (DatasetAnalysisTableModel) newModel;
// Collect the set of labels. This may be inefficient but it's safe.
final Collection<DatasetLabel> selection = new TreeSet<>();
final ListSelectionModel lsm = getSelectionModel();
for (int i = lsm.getMinSelectionIndex(); i <= lsm.getMaxSelectionIndex(); i++) {
if (lsm.isSelectedIndex(i))
selection.add(prev.records.get(i).label());
}
// Swap the model
adjusting = true;
super.setModel(next);
adjusting = false;
// And restore the selection
for (int i = 0; i < next.records.size(); i++) {
if (selection.contains(next.records.get(i).label()))
lsm.addSelectionInterval(i, i);
}
editArea.setEnabled(!lsm.isSelectionEmpty());
// And reset the rendering stuff since the model has changed
attachDescriptionRenderer(DatasetAnalysisTableModel.COL_QA_STATE);
} else {
super.setModel(newModel);
}
if (newModel instanceof DatasetAnalysisTableModel) {
final TableColumn col = getColumnModel().getColumn(DatasetAnalysisTableModel.COL_STATUS);
col.setCellRenderer(STATUS_RENDERER);
}
sizeColumnsToFitData();
}
private void attachDescriptionRenderer(int i) {
final TableColumn col = getColumnModel().getColumn(i);
col.setCellRenderer(new DefaultTableCellRenderer() {
protected void setValue(Object o) {
if (o != null && o instanceof DisplayableSpType)
o = ((DisplayableSpType) o).displayValue();
super.setValue(o);
}
});
}
}
private final class Header extends JLabel {
public Header(String text) {
super(text);
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Dimension d = getSize();
g.setColor(Color.LIGHT_GRAY);
g.drawLine(0, (int) d.getHeight() - 1, (int) d.getWidth() - 1, (int) d.getHeight() - 1);
}
}
}
/**
* Component that shows a table of {@link edu.gemini.spModel.dataset.DatasetExecRecord}s with an
* editable detail view for comments. Editing is disabled unless the OT is running in -onsite mode.
*
* @author rnorris
*/
final class CommentsComponent extends JPanel implements ObslogTableModels, ListSelectionListener {
private final JTable table;
private final JTextArea area = new JTextArea();
private final DocumentListener docListener = new DocumentListener() {
public void changedUpdate(DocumentEvent de) {
updateText();
}
public void removeUpdate(DocumentEvent de) {
updateText();
}
public void insertUpdate(DocumentEvent de) {
updateText();
}
private void updateText() {
final int row = table.getSelectedRow();
if (row > -1)
table.getModel().setValueAt(area.getText(), row, CommentTableModel.COL_COMMENT);
}
};
public CommentsComponent(String name) {
super(new BorderLayout());
setName(name);
table = new CommentsTable();
table.getSelectionModel().addListSelectionListener(this);
area.setEditable(OTOptions.isStaffGlobally());
area.getDocument().addDocumentListener(docListener);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(new Header("Select a row to " + (OTOptions.isStaffGlobally() ? "view or edit its comment." : "view its comment in full.")), BorderLayout.NORTH);
panel.add(new JScrollPane(area) {{
setBorder(BorderFactory.createEmptyBorder());
}}, BorderLayout.CENTER);
add(new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(table) {{
setBorder(BorderFactory.createEmptyBorder());
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}}, panel) {{
setResizeWeight(0.75);
}});
}
void setObsLog(final ObsLog obsLog) {
area.setEditable(OTOptions.isStaffGlobally()); // the answer can change as keys are added/removed
table.setModel(new CommentTableModel(obsLog));
table.setEnabled(true);
}
// Called when the user clicks on a row in the table
public void valueChanged(ListSelectionEvent lse) {
if (lse.getValueIsAdjusting()) return;
final ListSelectionModel lsm = (ListSelectionModel) lse.getSource();
if (lsm.isSelectionEmpty()) {
area.setText("");
area.setEnabled(false);
} else {
final int row = lsm.getMinSelectionIndex();
final String comment = (String) table.getModel().getValueAt(row, CommentTableModel.COL_COMMENT);
if (comment != null) {
area.getDocument().removeDocumentListener(docListener);
try {
area.setText(comment);
area.setSelectionStart(comment.length());
area.setSelectionEnd(comment.length());
} finally {
area.getDocument().addDocumentListener(docListener);
}
}
area.setEnabled(true);
area.requestFocusInWindow();
}
}
private class CommentsTable extends AbstractDatasetRecordTable {
public CommentsTable() {
super();
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
getSelectionModel().addListSelectionListener(this);
}
/**
* Overridden to preserve the selected item, if possible.
*/
@Override
public void setModel(TableModel model) {
final int row = getSelectedRow();
if (row == -1) {
super.setModel(model);
} else {
final Object label = getModel().getValueAt(row, CommentTableModel.COL_LABEL);
super.setModel(model);
for (int i = 0; i < getModel().getRowCount(); i++) {
final Object other = getModel().getValueAt(i, CommentTableModel.COL_LABEL);
if (label.equals(other)) {
getSelectionModel().setSelectionInterval(i, i);
break;
}
}
}
if (model instanceof CommentTableModel) {
attachCommentRenderer(CommentTableModel.COL_COMMENT);
sizeColumnsToFitData();
}
}
private void attachCommentRenderer(int i) {
final TableColumn col = getColumnModel().getColumn(i);
col.setCellRenderer(new DefaultTableCellRenderer() {
protected void setValue(Object o) {
// Truncate the comment if it is really long. There is
// a scroll bar but it could be a ridiculously long
// comment. Arbitrary cutoff set to 200.
if ((o != null) && o instanceof String) {
final String s = (String) o;
o = (s.length() <= 203) ? s : s.substring(0, 200) + "...";
}
super.setValue(o);
}
});
}
}
private class Header extends JLabel {
public Header(String text) {
super(text);
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Dimension d = getSize();
g.setColor(Color.LIGHT_GRAY);
g.drawLine(0, (int) d.getHeight() - 1, (int) d.getWidth() - 1, (int) d.getHeight() - 1);
}
}
}
/**
* A component that shows the visits in an ObsLogDataObject as a hierarchical tree.
* This control is read-only.
*
* @author rnorris
*/
final class VisitsComponent extends JScrollPane implements ObslogTableModels {
private final DateFormat OBSLOG_DATE_FORMAT = ObslogGUI.OBSLOG_DATE_FORMAT;
private final Box clientArea;
public VisitsComponent(String name) {
super(new Box(BoxLayout.Y_AXIS));
clientArea = (Box) getViewport().getView();
clientArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 10));
setName(name);
}
void setObsLog(final ObsLog obsLog) {
clientArea.removeAll();
addVisits(clientArea, obsLog);
revalidate();
}
private void addVisits(Container parent, ObsLog obsLog) {
final ObsVisit[] visits = obsLog.getVisits();
for (final ObsVisit visit : visits) {
final String title;
final DatasetLabel[] labels = visit.getAllDatasetLabels();
switch (labels.length) {
case 0:
title = "Visit " + OBSLOG_DATE_FORMAT.format(new Date(visit.getStartTime()));
break;
case 1:
title = "Visit " + OBSLOG_DATE_FORMAT.format(new Date(visit.getStartTime())) + " (Dataset " + labels[0].getIndex() + ")";
break;
default:
title = "Visit " + OBSLOG_DATE_FORMAT.format(new Date(visit.getStartTime())) + " (Datasets " + labels[0].getIndex() + "-" + labels[labels.length - 1].getIndex() + ")";
}
final CollapsableContainer cc = new CollapsableContainer(parent, title, true);
addDataSets(cc, labels, obsLog);
addUniqueConfigs(cc, visit.getUniqueConfigs());
addEvents(cc, visit.getEvents());
parent.add(cc);
}
}
private void addDataSets(Container parent, DatasetLabel[] labels, ObsLog obsLog) {
if (labels.length > 0) {
final CollapsableContainer cc = new CollapsableContainer(this, "Datasets", true);
final List<DatasetRecord> records = new ArrayList<>(labels.length);
for (DatasetLabel label : labels) {
records.add(obsLog.getDatasetRecord(label));
}
cc.add(tableWithHeader(new DatasetRecordTable(new DatasetAnalysisTableModel(obsLog, records))));
parent.add(cc);
}
}
private void addUniqueConfigs(Container parent, UniqueConfig[] uniqueConfigs) {
for (int i = 0; i < uniqueConfigs.length; i++) {
final UniqueConfig config = uniqueConfigs[i];
final String title;
final DatasetLabel[] labels = config.getDatasetLabels();
switch (labels.length) {
case 0:
title = "Config " + (i + 1);
break;
case 1:
title = "Config " + (i + 1) + " (Dataset " + labels[0].getIndex() + ")";
break;
default:
title = "Config " + (i + 1) + " (Datasets " + labels[0].getIndex() + "-" + labels[labels.length - 1].getIndex() + ")";
}
final CollapsableContainer cc = new CollapsableContainer(this, title, false);
cc.add(tableWithHeader(new JTable(new ConfigTableModel(config.getConfig()))));
parent.add(cc);
}
}
private void addEvents(Container parent, ObsExecEvent[] events) {
if (events.length > 0) {
final String title;
switch (events.length) {
case 1:
title = "Event (" + OBSLOG_DATE_FORMAT.format(new Date(events[0].getTimestamp())) + ")";
break;
default:
title = "Events (" + OBSLOG_DATE_FORMAT.format(new Date(events[0].getTimestamp())) + " to " + OBSLOG_DATE_FORMAT.format(new Date(events[events.length - 1].getTimestamp())) + ")";
break;
}
final CollapsableContainer cc = new CollapsableContainer(this, title, false);
cc.add(tableWithHeader(new JTable(new EventTableModel(events))));
parent.add(cc);
}
}
private Component tableWithHeader(JTable t) {
final JPanel p = new JPanel(new BorderLayout());
p.add(t.getTableHeader(), BorderLayout.NORTH);
p.add(t, BorderLayout.CENTER);
return p;
}
private class DatasetRecordTable extends AbstractDatasetRecordTable {
public DatasetRecordTable(TableModel model) {
super(model);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
@Override
public void setModel(TableModel model) {
super.setModel(model);
if (model instanceof DatasetAnalysisTableModel) {
attachDescriptionRenderer(DatasetAnalysisTableModel.COL_QA_STATE);
}
}
private void attachDescriptionRenderer(int i) {
final TableColumn col = getColumnModel().getColumn(i);
col.setCellRenderer(new DefaultTableCellRenderer() {
protected void setValue(Object o) {
if (o != null && o instanceof DisplayableSpType)
o = ((DisplayableSpType) o).displayValue();
super.setValue(o);
}
});
}
}
}
}
| |
/*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.restless.client.http;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.MappingJsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.andrewoma.restless.client.ClientExceptionHandler;
import com.github.andrewoma.restless.core.ByteStream;
import com.github.andrewoma.restless.core.ClosableByteStream;
import com.github.andrewoma.restless.core.Context;
import com.github.andrewoma.restless.core.Headers;
import com.github.andrewoma.restless.core.Streamed;
import com.github.andrewoma.restless.core.proxy.MethodHandler;
import com.github.andrewoma.restless.core.proxy.MethodInvocation;
import com.github.andrewoma.restless.core.util.CaseConverter;
import com.github.andrewoma.restless.core.util.Jdks;
import com.github.andrewoma.restless.core.util.Validators;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
public class HttpClientMethodHandler<T extends Context> implements MethodHandler<T> {
private final CloseableHttpClient httpClient;
private final URI baseUri;
private final JsonFactory jsonFactory;
private final ObjectMapper objectMapper;
private final ClientExceptionHandler clientExceptionHandler;
public HttpClientMethodHandler(CloseableHttpClient httpClient, URI baseUri, ObjectMapper objectMapper, ClientExceptionHandler clientExceptionHandler) {
this.httpClient = httpClient;
this.baseUri = baseUri;
this.clientExceptionHandler = clientExceptionHandler;
this.jsonFactory = new MappingJsonFactory(objectMapper);
this.objectMapper = objectMapper;
}
@Override
public Object invoke(MethodInvocation<T> methodInvocation) throws Throwable {
HttpPost request = createRequest(methodInvocation);
CloseableHttpResponse response = httpClient.execute(request);
try {
Map<String, String> headers = getResponseHeaders(response);
if (response.getStatusLine().getStatusCode() / 100 == 2) {
return handleResponse(methodInvocation.getMethod().getReturnType(), response);
} else {
throw handleException(headers, response.getEntity().getContent());
}
} finally {
if (!isByteStream(methodInvocation.getMethod().getReturnType())) {
closeResponse(response);
}
}
}
private void closeResponse(CloseableHttpResponse response) throws IOException {
try {
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
}
private boolean isByteStream(Class<?> returnType) {
return returnType.isAssignableFrom(ByteStream.class);
}
private Throwable handleException(Map<String, String> headers, InputStream inputStream) throws IOException {
return clientExceptionHandler.handleException(headers, objectMapper, inputStream);
}
private Object handleResponse(Class<?> returnType, final CloseableHttpResponse response) throws IOException {
if (returnType.equals(Void.TYPE)) {
return null;
} else if (isByteStream(returnType)) {
return createStreamingResponse(response);
} else {
return objectMapper.readValue(response.getEntity().getContent(), returnType);
}
}
private Object createStreamingResponse(final CloseableHttpResponse response) {
if (Jdks.supportsAutoCloseable()) {
return new ClosableByteStream() {
@Override
public InputStream input() throws Exception {
return response.getEntity().getContent();
}
@Override
public void close() throws Exception {
closeResponse(response);
}
};
} else {
return new ByteStream() {
@Override
public InputStream input() throws Exception {
return response.getEntity().getContent();
}
@Override
public void close() throws Exception {
closeResponse(response);
}
};
}
}
private HttpPost createRequest(final MethodInvocation<T> methodInvocation) throws IOException, URISyntaxException {
URI uri = createRequestUri(methodInvocation);
final HttpPost request = new HttpPost(uri);
setRequestHeaders(request, methodInvocation.getContext().getRequestHeaders());
request.setEntity(createEntity(methodInvocation));
return request;
}
private StreamingEntity createEntity(final MethodInvocation<T> methodInvocation) {
if (methodInvocation.getMethod().getParameterTypes().length == 1 &&
methodInvocation.getMethod().getParameterTypes()[0].equals(ByteStream.class)) {
return new StreamingEntity() {
@Override
public void writeTo(OutputStream outstream) throws IOException {
ByteStream parameter = (ByteStream) methodInvocation.getParameters()[0];
try {
parameter.output(outstream);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
StreamingEntity entity = new StreamingEntity() {
@Override
public void writeTo(OutputStream output) throws IOException {
JsonGenerator generator = jsonFactory.createGenerator(output, JsonEncoding.UTF8);
try {
generator.writeStartObject();
int numParams = methodInvocation.getParameters().length;
for (int i = 0; i < numParams; i++) {
String name = methodInvocation.getParameterNames()[i];
Object parameter = methodInvocation.getParameters()[i];
Class<?> type = methodInvocation.getMethod().getParameterTypes()[i];
if (type.equals(Streamed.class)) {
generator.writeArrayFieldStart(name);
for (Object value : (Streamed) parameter) {
generator.writeObject(value);
}
generator.writeEndArray();
} else {
Validators.require(!type.equals(ByteStream.class), "'ByteStream' parameters must be the first and only argument");
generator.writeObjectField(name, parameter);
}
}
generator.writeEndObject();
} finally {
generator.close();
}
}
};
entity.setContentType(ContentType.APPLICATION_JSON.toString());
return entity;
}
private URI createRequestUri(MethodInvocation<T> methodInvocation) throws URISyntaxException {
URIBuilder builder = new URIBuilder(baseUri);
builder.setPath(builder.getPath() + (builder.getPath().endsWith("/") ? "" : "/")
+ methodInvocation.getContext().getServiceName()
+ "/" + CaseConverter.camelCaseToLowerDash(methodInvocation.getMethod().getName()));
return builder.build();
}
private void setRequestHeaders(HttpPost request, Map<String, String> requestHeaders) {
for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
}
private Map<String, String> getResponseHeaders(HttpResponse response) {
// TODO ... create a lazy view
Header[] headers = response.getAllHeaders();
Map<String, String> result = new HashMap<String, String>();
for (Header header : headers) {
result.put(header.getName(), header.getValue());
}
result.put(Headers.STATUS.getValue(), String.valueOf(response.getStatusLine().getStatusCode()));
return result;
}
}
| |
/*
* ! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2018 by Hitachi Vantara : http://www.pentaho.com
*
* ******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* *****************************************************************************
*/
package org.pentaho.di.trans.ael.adapters;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Spy;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.pentaho.di.core.KettleClientEnvironment;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleMissingPluginsException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.engine.api.model.Hop;
import org.pentaho.di.engine.api.model.Operation;
import org.pentaho.di.engine.api.model.Transformation;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.csvinput.CsvInputMeta;
import org.pentaho.di.trans.steps.dummytrans.DummyTransMeta;
import org.pentaho.di.trans.steps.tableinput.TableInputMeta;
import org.pentaho.di.workarounds.ResolvableResource;
import org.pentaho.metastore.api.exceptions.MetaStoreException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith ( MockitoJUnitRunner.class )
public class TransMetaConverterTest {
@Spy StepMetaInterface stepMetaInterface = new DummyTransMeta();
final String XML = "<xml></xml>";
@Before
public void before() throws KettleException {
when( stepMetaInterface.getXML() ).thenReturn( XML );
}
@BeforeClass
public static void init() throws Exception {
if ( !KettleClientEnvironment.isInitialized() ) {
KettleClientEnvironment.init();
}
PluginRegistry.addPluginType( StepPluginType.getInstance() );
PluginRegistry.init();
if ( !Props.isInitialized() ) {
Props.init( 0 );
}
}
@Test
public void simpleConvert() {
TransMeta meta = new TransMeta();
meta.setFilename( "fileName" );
meta.addStep( new StepMeta( "stepName", stepMetaInterface ) );
Transformation trans = TransMetaConverter.convert( meta );
assertThat( trans.getId(), is( meta.getFilename() ) );
assertThat( trans.getOperations().size(), is( 1 ) );
assertThat( trans.getOperations().get( 0 ).getId(), is( "stepName" ) );
}
@Test
public void transWithHops() {
TransMeta meta = new TransMeta();
meta.setFilename( "fileName" );
StepMeta from = new StepMeta( "step1", stepMetaInterface );
meta.addStep( from );
StepMeta to = new StepMeta( "step2", stepMetaInterface );
meta.addStep( to );
meta.addTransHop( new TransHopMeta( from, to ) );
Transformation trans = TransMetaConverter.convert( meta );
assertThat( trans.getId(), is( meta.getFilename() ) );
assertThat( trans.getOperations().size(), is( 2 ) );
assertThat( trans.getHops().size(), is( 1 ) );
assertThat( trans.getHops().get( 0 ).getFrom().getId(), is( from.getName() ) );
assertThat( trans.getHops().get( 0 ).getTo().getId(), is( to.getName() ) );
assertThat(
trans.getHops().stream().map( Hop::getType ).collect( Collectors.toList() ),
everyItem( is( Hop.TYPE_NORMAL ) )
);
}
@Test
public void transIdFromRepo() throws Exception {
TransMeta meta = new TransMeta();
meta.setName( "transName" );
Transformation trans = TransMetaConverter.convert( meta );
assertThat( trans.getId(), is( "/transName" ) );
}
@Test
public void transConfigItems() throws Exception {
TransMeta meta = new TransMeta();
meta.setName( "foo" );
Transformation trans = TransMetaConverter.convert( meta );
assertThat( trans.getConfig().get( TransMetaConverter.TRANS_META_NAME_CONF_KEY ),
is( "foo" ) );
assertThat( (String) trans.getConfig().get( TransMetaConverter.TRANS_META_CONF_KEY ),
startsWith( "<transformation>" ) );
}
@Test
public void transConfigItemsNoNameSpecified() throws Exception {
TransMeta meta = new TransMeta();
Transformation trans = TransMetaConverter.convert( meta );
assertThat( trans.getConfig().get( TransMetaConverter.TRANS_META_NAME_CONF_KEY ),
is( TransMetaConverter.TRANS_DEFAULT_NAME ) );
assertThat( (String) trans.getConfig().get( TransMetaConverter.TRANS_META_CONF_KEY ),
startsWith( "<transformation>" ) );
}
@Test
public void testDisabledHops() {
TransMeta trans = new TransMeta();
StepMeta start = new StepMeta( "Start", stepMetaInterface );
trans.addStep( start );
StepMeta withEnabledHop = new StepMeta( "WithEnabledHop", stepMetaInterface );
trans.addStep( withEnabledHop );
StepMeta withDisabledHop = new StepMeta( "WithDisabledHop", stepMetaInterface );
trans.addStep( withDisabledHop );
StepMeta shouldStay = new StepMeta( "ShouldStay", stepMetaInterface );
trans.addStep( shouldStay );
StepMeta shouldNotStay = new StepMeta( "ShouldNotStay", stepMetaInterface );
trans.addStep( shouldNotStay );
StepMeta withEnabledAndDisabledHops = new StepMeta( "WithEnabledAndDisabledHops", stepMetaInterface );
trans.addStep( withEnabledAndDisabledHops );
StepMeta afterEnabledDisabled = new StepMeta( "AfterEnabledDisabled", stepMetaInterface );
trans.addStep( afterEnabledDisabled );
trans.addTransHop( new TransHopMeta( start, withEnabledHop ) );
trans.addTransHop( new TransHopMeta( start, withDisabledHop, false ) );
trans.addTransHop( new TransHopMeta( withEnabledHop, shouldStay ) );
trans.addTransHop( new TransHopMeta( withDisabledHop, shouldStay ) );
trans.addTransHop( new TransHopMeta( withDisabledHop, shouldNotStay ) );
trans.addTransHop( new TransHopMeta( start, withEnabledAndDisabledHops ) );
trans.addTransHop( new TransHopMeta( withEnabledHop, withEnabledAndDisabledHops, false ) );
trans.addTransHop( new TransHopMeta( withEnabledAndDisabledHops, afterEnabledDisabled ) );
Transformation transformation = TransMetaConverter.convert( trans );
List<String>
steps =
transformation.getOperations().stream().map( op -> op.getId() ).collect( Collectors.toList() );
assertThat( "Only 5 ops should exist", steps.size(), is( 5 ) );
assertThat( steps, hasItems( "Start", "WithEnabledHop", "ShouldStay", "WithEnabledAndDisabledHops",
"AfterEnabledDisabled" ) );
List<String> hops = transformation.getHops().stream().map( hop -> hop.getId() ).collect( Collectors.toList() );
assertThat( "Only 4 hops should exist", hops.size(), is( 4 ) );
assertThat( hops, hasItems( "Start -> WithEnabledHop", "WithEnabledHop -> ShouldStay",
"Start -> WithEnabledAndDisabledHops", "WithEnabledAndDisabledHops -> AfterEnabledDisabled" ) );
}
@Test
public void testRemovingDisabledInputSteps() {
TransMeta trans = new TransMeta();
StepMeta inputToBeRemoved = new StepMeta( "InputToBeRemoved", stepMetaInterface );
trans.addStep( inputToBeRemoved );
StepMeta inputToStay = new StepMeta( "InputToStay", stepMetaInterface );
trans.addStep( inputToStay );
StepMeta inputReceiver1 = new StepMeta( "InputReceiver1", stepMetaInterface );
trans.addStep( inputReceiver1 );
StepMeta inputReceiver2 = new StepMeta( "InputReceiver2", stepMetaInterface );
trans.addStep( inputReceiver2 );
TransHopMeta hop1 = new TransHopMeta( inputToBeRemoved, inputReceiver1, false );
TransHopMeta hop2 = new TransHopMeta( inputToStay, inputReceiver1 );
TransHopMeta hop3 = new TransHopMeta( inputToBeRemoved, inputReceiver2, false );
trans.addTransHop( hop1 );
trans.addTransHop( hop2 );
trans.addTransHop( hop3 );
Transformation transformation = TransMetaConverter.convert( trans );
List<String>
steps =
transformation.getOperations().stream().map( op -> op.getId() ).collect( Collectors.toList() );
assertThat( "Only 2 ops should exist", steps.size(), is( 2 ) );
assertThat( steps, hasItems( "InputToStay", "InputReceiver1" ) );
List<String> hops = transformation.getHops().stream().map( hop -> hop.getId() ).collect( Collectors.toList() );
assertThat( "Only 1 hop should exist", hops.size(), is( 1 ) );
assertThat( hops, hasItems( "InputToStay -> InputReceiver1" ) );
}
@Test
public void testMultipleDisabledHops() {
TransMeta trans = new TransMeta();
StepMeta input = new StepMeta( "Input", stepMetaInterface );
trans.addStep( input );
StepMeta step1 = new StepMeta( "Step1", stepMetaInterface );
trans.addStep( step1 );
StepMeta step2 = new StepMeta( "Step2", stepMetaInterface );
trans.addStep( step2 );
StepMeta step3 = new StepMeta( "Step3", stepMetaInterface );
trans.addStep( step3 );
TransHopMeta hop1 = new TransHopMeta( input, step1, false );
TransHopMeta hop2 = new TransHopMeta( step1, step2, false );
TransHopMeta hop3 = new TransHopMeta( step2, step3, false );
trans.addTransHop( hop1 );
trans.addTransHop( hop2 );
trans.addTransHop( hop3 );
Transformation transformation = TransMetaConverter.convert( trans );
assertThat( "Trans has steps though all of them should be removed", transformation.getOperations().size(),
is( 0 ) );
assertThat( "Trans has hops though all of them should be removed", transformation.getHops().size(), is( 0 ) );
}
@Test
public void errorHops() throws Exception {
TransMeta meta = new TransMeta();
meta.setFilename( "fileName" );
StepMeta from = new StepMeta( "step1", stepMetaInterface );
meta.addStep( from );
StepMeta to = new StepMeta( "step2", stepMetaInterface );
meta.addStep( to );
meta.addTransHop( new TransHopMeta( from, to ) );
StepMeta error = new StepMeta( "errorHandler", stepMetaInterface );
meta.addStep( error );
TransHopMeta errorHop = new TransHopMeta( from, error );
errorHop.setErrorHop( true );
meta.addTransHop( errorHop );
Transformation trans = TransMetaConverter.convert( meta );
Map<String, List<Hop>> hops = trans.getHops().stream().collect( Collectors.groupingBy( Hop::getType ) );
List<Hop> normalHops = hops.get( Hop.TYPE_NORMAL );
assertThat( normalHops.size(), is( 1 ) );
assertThat( normalHops.get( 0 ).getTo().getId(), is( "step2" ) );
List<Hop> errorHops = hops.get( Hop.TYPE_ERROR );
assertThat( errorHops.size(), is( 1 ) );
assertThat( errorHops.get( 0 ).getTo().getId(), is( "errorHandler" ) );
assertThat(
hops.values().stream()
.flatMap( List::stream )
.map( Hop::getFrom ).map( Operation::getId )
.collect( Collectors.toList() ),
everyItem( equalTo( "step1" ) )
);
}
@Test
public void lazyConversionTurnedOff() throws KettleException {
KettleEnvironment.init();
TransMeta transMeta = new TransMeta();
CsvInputMeta csvInputMeta = new CsvInputMeta();
csvInputMeta.setLazyConversionActive( true );
StepMeta csvInput = new StepMeta( "Csv", csvInputMeta );
transMeta.addStep( csvInput );
TableInputMeta tableInputMeta = new TableInputMeta();
tableInputMeta.setLazyConversionActive( true );
StepMeta tableInput = new StepMeta( "Table", tableInputMeta );
transMeta.addStep( tableInput );
Transformation trans = TransMetaConverter.convert( transMeta );
TransMeta cloneMeta;
String transMetaXml = (String) trans.getConfig().get( TransMetaConverter.TRANS_META_CONF_KEY );
Document doc;
try {
doc = XMLHandler.loadXMLString( transMetaXml );
Node stepNode = XMLHandler.getSubNode( doc, "transformation" );
cloneMeta = new TransMeta( stepNode, null );
} catch ( KettleXMLException | KettleMissingPluginsException e ) {
throw new RuntimeException( e );
}
assertThat( ( (CsvInputMeta) cloneMeta.findStep( "Csv" ).getStepMetaInterface() ).isLazyConversionActive(),
is( false ) );
assertThat( ( (TableInputMeta) cloneMeta.findStep( "Table" ).getStepMetaInterface() ).isLazyConversionActive(),
is( false ) );
}
@Test
public void testIncludesSubTransformations() throws Exception {
TransMeta parentTransMeta = new TransMeta( getClass().getResource( "trans-meta-converter-parent.ktr" ).getPath() );
Transformation transformation = TransMetaConverter.convert( parentTransMeta );
@SuppressWarnings( { "unchecked", "ConstantConditions" } )
HashMap<String, Transformation> config =
(HashMap<String, Transformation>) transformation.getConfig( TransMetaConverter.SUB_TRANSFORMATIONS_KEY ).get();
assertEquals( 1, config.size() );
assertNotNull( config.get( "file://" + getClass().getResource( "trans-meta-converter-sub.ktr" ).getPath() ) );
}
@Test
public void testIncludesSubTransformationsFromRepository() throws Exception {
TransMeta parentTransMeta = new TransMeta( getClass().getResource( "trans-meta-converter-parent.ktr" ).getPath() );
Repository repository = mock( Repository.class );
TransMeta transMeta = new TransMeta( );
RepositoryDirectoryInterface repositoryDirectory = new RepositoryDirectory( null, "public");
String directory = getClass().getResource( "" ).toString().replace( File.separator, "/" );
when( repository.findDirectory( "public" ) ).thenReturn( repositoryDirectory );
when( repository.loadTransformation( "trans-meta-converter-sub.ktr", repositoryDirectory, null, true, null ) ).thenReturn( transMeta );
parentTransMeta.setRepository( repository );
parentTransMeta.setRepositoryDirectory( repositoryDirectory );
parentTransMeta.setVariable( "Internal.Entry.Current.Directory", "public" );
Transformation transformation = TransMetaConverter.convert( parentTransMeta );
@SuppressWarnings( { "unchecked", "ConstantConditions" } )
HashMap<String, Transformation> config =
(HashMap<String, Transformation>) transformation.getConfig( TransMetaConverter.SUB_TRANSFORMATIONS_KEY ).get();
assertEquals( 1, config.size() );
assertNotNull( config.get( "public/trans-meta-converter-sub.ktr" ) );
}
@Test
public void testClonesTransMeta() throws KettleException {
class ResultCaptor implements Answer<Object> {
private Object result;
public Object getResult() {
return result;
}
@Override public java.lang.Object answer( InvocationOnMock invocationOnMock ) throws Throwable {
result = invocationOnMock.callRealMethod();
return result;
}
}
TransMeta originalTransMeta = spy( new TransMeta() );
ResultCaptor cloneTransMetaCaptor = new ResultCaptor();
doAnswer( cloneTransMetaCaptor ).when( originalTransMeta ).realClone( eq( false ) );
originalTransMeta.setName( "TransName" );
TransMetaConverter.convert( originalTransMeta );
TransMeta cloneTransMeta = (TransMeta) cloneTransMetaCaptor.getResult();
verify( originalTransMeta ).realClone( eq( false ) );
assertThat( cloneTransMeta.getName(), is( originalTransMeta.getName() ) );
verify( originalTransMeta, never() ).getXML();
verify( cloneTransMeta ).getXML();
}
@Test
public void testResolveStepMetaResources() throws KettleException, MetaStoreException {
Variables variables = new Variables();
TransMeta transMeta = spy( new TransMeta() );
transMeta.setParentVariableSpace( variables );
doReturn( transMeta ).when( transMeta ).realClone( false );
TestMetaResolvableResource testMetaResolvableResource = spy( new TestMetaResolvableResource() );
TestMetaResolvableResource testMetaResolvableResourceTwo = spy( new TestMetaResolvableResource() );
StepMeta testMeta = new StepMeta( "TestMeta", testMetaResolvableResource );
StepMeta testMetaTwo = new StepMeta( "TestMeta2", testMetaResolvableResourceTwo );
transMeta.addStep( testMeta );
transMeta.addStep( testMetaTwo );
transMeta.addTransHop( new TransHopMeta( testMeta, testMetaTwo ) );
TransMetaConverter.convert( transMeta );
verify( testMetaResolvableResource ).resolve();
verify( testMetaResolvableResourceTwo ).resolve();
}
private static class TestMetaResolvableResource extends BaseStepMeta
implements StepMetaInterface, ResolvableResource {
@Override public void resolve() {
}
@Override public void setDefault() {
}
@Override
public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
TransMeta transMeta,
Trans trans ) {
return null;
}
@Override public StepDataInterface getStepData() {
return null;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.jini.id;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
/**
* A 128-bit value to serve as a universally unique identifier. Two
* <code>Uuid</code>s are equal if they have the same 128-bit value.
* <code>Uuid</code> instances can be created using the static methods
* of the {@link UuidFactory} class.
*
* <p>The design of this class is intended to support the use of
* universally unique identifiers that
*
* <ol>
* <li>have a high likelihood of uniqueness over space and time and
* <li>are computationally difficult to guess.
* </ol>
*
* The second goal is intended to support the treatment of data
* containing a <code>Uuid</code> as a capability. Note that not all
* defined <code>Uuid</code> values imply a generation algorithm that
* supports this goal.
*
* <p>The most significant 64 bits of the value can be decomposed into
* unsigned integer fields according to the following bit masks:
*
* <pre>
* 0xFFFFFFFF00000000 time_low
* 0x00000000FFFF0000 time_mid
* 0x000000000000F000 version
* 0x0000000000000FFF time_hi
* </pre>
*
* <p>The least significant 64 bits of the value can be decomposed
* into unsigned integer fields according to the following bit masks:
*
* <pre>
* 0xC000000000000000 variant
* 0x3FFF000000000000 clock_seq
* 0x0000FFFFFFFFFFFF node
* </pre>
*
* <p>This specification defines the meaning (and implies aspects of
* the generation algorithm) of <code>Uuid</code> values if the
* variant field is <code>0x2</code> and the <code>version</code>
* field is either <code>0x1</code> or <code>0x4</code>.
*
* <p>If the <code>version</code> field is <code>0x1</code>, then
*
* <ul>
*
* <li>the <code>time_low</code>, <code>time_mid</code>, and
* <code>time_hi</code> fields are the least, middle, and most
* significant bits (respectively) of a 60-bit timestamp of
* 100-nanosecond intervals since midnight, October 15, 1582 UTC,
*
* <li>the <code>clock_seq</code> field is a 14-bit number chosen to
* help avoid duplicate <code>Uuid</code> values in the event of a
* changed node address or a backward system clock adjustment (such as
* a random number when in doubt, or the previously used number
* incremented by one if just a backward clock adjustment is
* detected), and
*
* <li>the <code>node</code> field is an IEEE 802 address (a 48-bit
* value).
*
* <p>As an alternative to an IEEE 802 address (such as if one is not
* available to the generation algorithm), the <code>node</code> field
* may also be a 48-bit number for which the most significant bit is
* set to <code>1</code> and the remaining bits were produced from a
* cryptographically strong random sequence.
*
* </ul>
*
* <p>If the <code>version</code> field is <code>0x4</code>, then the
* <code>time_low</code>, <code>time_mid</code>, <code>time_hi</code>,
* <code>clock_seq</code>, and <code>node</code> fields are values
* that were produced from a cryptographically strong random sequence.
*
* <p>Only <code>Uuid</code> values with a <code>version</code> field
* of <code>0x4</code> are considered computationally difficult to
* guess. A <code>Uuid</code> value with a <code>version</code> field
* of <code>0x1</code> should not be treated as a capability.
*
* <p>A subclass of <code>Uuid</code> must not implement {@link
* Externalizable}; this restriction is enforced by this class's
* constructor and <code>readObject</code> methods.
*
*
* @since 2.0
**/
public class Uuid implements Serializable {
private static final long serialVersionUID = -106268922535833151L;
/**
* The most significant 64 bits of the 128-bit value.
*
* @serial
**/
private final long bits0;
/**
* The least significant 64 bits of the 128-bit value.
*
* @serial
**/
private final long bits1;
/**
* Creates a new <code>Uuid</code> with the specified 128-bit
* value.
*
* @param bits0 the most significant 64 bits of the 128-bit value
*
* @param bits1 the least significant 64 bits of the 128-bit value
*
* @throws SecurityException if the class of this object
* implements <code>Externalizable</code>
**/
protected Uuid(long bits0, long bits1) {
if (!isValid()) {
throw new SecurityException("invalid class: " +
this.getClass().getName());
}
this.bits0 = bits0;
this.bits1 = bits1;
}
/**
* Returns the most significant 64 bits of this
* <code>Uuid</code>'s 128-bit value.
*
* @return the most significant 64 bits of the 128-bit value
**/
public final long getMostSignificantBits() {
return bits0;
}
/**
* Returns the least significant 64 bits of this
* <code>Uuid</code>'s 128-bit value.
*
* @return the least significant 64 bits of the 128-bit value
**/
public final long getLeastSignificantBits() {
return bits1;
}
/**
* Returns the hash code value for this <code>Uuid</code>.
*
* @return the hash code value for this <code>Uuid</code>
**/
public final int hashCode() {
return (int) ((bits0 >>> 32) ^ bits0 ^ (bits1 >>> 32) ^ bits1);
}
/**
* Compares the specified object with this <code>Uuid</code> for
* equality.
*
* This method returns <code>true</code> if and only if the
* specified object is a <code>Uuid</code> instance with the same
* 128-bit value as this one.
*
* @param obj the object to compare this <code>Uuid</code> to
*
* @return <code>true</code> if the given object is equivalent to
* this one, and <code>false</code> otherwise
**/
public final boolean equals(Object obj) {
if (obj instanceof Uuid) {
Uuid other = (Uuid) obj;
return bits0 == other.bits0 && bits1 == other.bits1;
} else {
return false;
}
}
/**
* Returns a string representation of this <code>Uuid</code>.
*
* <p>The string representation is 36 characters long, with five
* fields of zero-filled, lowercase hexadecimal numbers separated
* by hyphens. The fields of the string representation are
* derived from the components of the 128-bit value in the
* following order:
*
* <ul>
*
* <li><code>time_low</code> (8 hexadecimal digits)
*
* <li><code>time_mid</code> (4 hexadecimal digits)
*
* <li><code>version</code> and <code>time_hi</code> treated as a
* single field (4 hexadecimal digits)
*
* <li><code>variant</code> and <code>clock_seq</code> treated as
* a single field (4 hexadecimal digits)
*
* <li><code>node</code> (12 hexadecimal digits)
*
* </ul>
*
* <p>As an example, a <code>Uuid</code> with the 128-bit value
*
* <pre>0x0123456789ABCDEF0123456789ABCDEF</pre>
*
* would have the following string representation:
*
* <pre>01234567-89ab-cdef-0123-456789abcdef</pre>
*
* @return a string representation of this <code>Uuid</code>
**/
public final String toString() {
return
toHexString(bits0 >>> 32, 8) + "-" +
toHexString(bits0 >>> 16, 4) + "-" +
toHexString(bits0 >>> 0, 4) + "-" +
toHexString(bits1 >>> 48, 4) + "-" +
toHexString(bits1 >>> 0, 12);
}
/**
* Returns the specified number of the least significant digits of
* the hexadecimal representation of the given value, discarding
* more significant digits or padding with zeros as necessary.
* Only lowercase letters are used in the returned hexadecimal
* representation.
**/
private String toHexString(long value, int digits) {
long cutoff = 1L << (digits * 4);
return Long.toHexString(cutoff | (value & (cutoff - 1))).substring(1);
}
/**
* Marshals a binary representation of this <code>Uuid</code> to
* an <code>OutputStream</code>.
*
* <p>Specifically, this method writes the 128-bit value to the
* stream as 16 bytes in network (big-endian) byte order.
*
* @param out the <code>OutputStream</code> to write this
* <code>Uuid</code> to
*
* @throws IOException if an I/O exception occurs while performing
* this operation
*
* @throws NullPointerException if <code>out</code> is
* <code>null</code>
**/
public final void write(OutputStream out) throws IOException {
writeLong(bits0, out);
writeLong(bits1, out);
}
/**
* Write a long value to an OutputStream in big-endian byte order.
**/
private static void writeLong(long value, OutputStream out)
throws IOException
{
out.write((int) (value >>> 56) & 0xFF);
out.write((int) (value >>> 48) & 0xFF);
out.write((int) (value >>> 40) & 0xFF);
out.write((int) (value >>> 32) & 0xFF);
out.write((int) (value >>> 24) & 0xFF);
out.write((int) (value >>> 16) & 0xFF);
out.write((int) (value >>> 8) & 0xFF);
out.write((int) (value >>> 0) & 0xFF);
}
/**
* Delegates to the superclass's {@link Object#finalize finalize}
* method. This method prevents a subclass from declaring an
* overriding <code>finalize</code> method.
*
* @throws Throwable if the superclass's <code>finalize</code>
* method throws a <code>Throwable</code>
**/
protected final void finalize() throws Throwable { }
/**
* Returns this object. This method prevents a subclass from
* declaring a <code>writeReplace</code> method with an alternate
* implementation.
*
* @return this object
**/
protected final Object writeReplace() {
return this;
}
/**
* Returns this object. This method prevents a subclass from
* declaring a <code>readResolve</code> method with an alternate
* implementation.
*
* @return this object
**/
protected final Object readResolve() {
return this;
}
/**
* @throws InvalidObjectException if the class of this object
* implements <code>Externalizable</code>
**/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
if (!isValid()) {
throw new InvalidObjectException("invalid class: " +
this.getClass().getName());
}
in.defaultReadObject();
}
/**
* @throws InvalidObjectException unconditionally
**/
private void readObjectNoData() throws InvalidObjectException {
throw new InvalidObjectException("no data in stream; class: " +
this.getClass().getName());
}
private boolean isValid() {
return !(this instanceof Externalizable);
}
}
| |
package postprocessing;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import fluentSolver.Fluent;
import fluentSolver.FluentNetworkSolver;
import htn.HTNMetaConstraint;
import htn.HTNOperator;
import htn.HTNPlanner;
import htn.PlanReportroryItem;
import org.metacsp.framework.Constraint;
import org.metacsp.framework.ConstraintNetwork;
import org.metacsp.framework.Variable;
import org.metacsp.multi.allenInterval.AllenIntervalNetworkSolver;
import org.metacsp.time.APSPSolver;
import org.metacsp.time.SimpleDistanceConstraint;
import org.metacsp.time.TimePoint;
import planner.CHIMP;
import postprocessing.estereltypes.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
public class EsterelGenerator {
public static void generateEsterelGraph(CHIMP chimp, Writer writer) {
FluentNetworkSolver fluentSolver = chimp.getFluentSolver();
List<SimpleDistanceConstraint> additionalConsList = calcAdditionalConstraints(fluentSolver);
// Add new constraints to apspSolver
APSPSolver apspSolver = getApspSolver(fluentSolver);
boolean success = apspSolver.addConstraints(
additionalConsList.toArray(new SimpleDistanceConstraint[additionalConsList.size()]));
// Create Esterel Graph:
Map<TimePoint, Fluent> timePointActivityMap = getTimePointActivityMap(fluentSolver);
// create ActionDispatch messages
Map<Fluent, ActionDispatch> fluentActionDispatchMap = getFluentActionDispatchMap(timePointActivityMap, chimp);
// Create and sort array of timepoints
TimePoint[] tps = createSortedActivityTimepoints(apspSolver, timePointActivityMap);
EsterelPlan esterelPlan = new EsterelPlan();
// add nodes to esterel plan
for (int i = 0; i < tps.length - 1; i++) {
TimePoint tp = tps[i];
if (tp.getID() == 0) {
EsterelPlanNode node = new EsterelPlanNode();
node.name = "plan_start";
node.node_id = 0;
node.node_type = 2;
node.action = new ActionDispatch(0, "");
esterelPlan.nodes.add(node);
} else {
Fluent fl = timePointActivityMap.get(tp);
EsterelPlanNode node = new EsterelPlanNode();
node.name = fl.getCompoundSymbolicVariable().getPredicateName();
if (isEndpoint(tp)) {
node.name += "_end";
} else {
node.name += "_start";
}
node.node_type = isEndpoint(tp) ? 1 : 0;
node.node_id = i;
node.action = fluentActionDispatchMap.get(fl);
esterelPlan.nodes.add(node);
}
}
// the index of nodes in the esterel plan is the same as that of the corresponding timepoint in tps
// Add edges: for two nodes check if an edge exist and add it to the plan
int edgeIdCnt = 0;
for (int i = 0; i < tps.length - 1; i++) {
for (int j = 0; j < tps.length - 1; j++) { // horizon tp is last in tps and can be ignored
SimpleDistanceConstraint sdc = apspSolver.getConstraint(tps[i], tps[j]);
if (sdc != null) {
// create edge
int edgeId = edgeIdCnt++;
EsterelPlanEdge edge = new EsterelPlanEdge(edgeId, "edge" + edgeId, i, j,
sdc.getMinimum() / 1000, sdc.getMaximum() / 1000);
esterelPlan.addEdge(edge);
}
}
}
// export esterel
ObjectMapper objectMapper = new ObjectMapper(
new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER));
try {
objectMapper.writeValue(writer, esterelPlan);
} catch (IOException e) {
e.printStackTrace();
}
}
public static TimePoint[] createSortedActivityTimepoints(APSPSolver apspSolver, Map<TimePoint, Fluent> timePointActivityMap) {
TimePoint[] tps = new TimePoint[timePointActivityMap.keySet().size() + 2];
tps[0] = apspSolver.getSource();
tps[tps.length-1] = apspSolver.getSink();
int pos = 1;
for (TimePoint tp : timePointActivityMap.keySet()) {
tps[pos++] = tp;
}
Arrays.sort(tps, new Comparator<TimePoint>() {
@Override
public int compare(TimePoint t0, TimePoint t1) {
return Long.compare(t0.getLowerBound(), t1.getLowerBound());
}
});
return tps;
}
public static Map<Fluent, ActionDispatch> getFluentActionDispatchMap(Map<TimePoint, Fluent> timePointActivityMap,
CHIMP chimp) {
// we need the operators to get the names of the actions' arguments
List<PlanReportroryItem> operators = chimp.getPlanner().getHTNMetaConstraint().getOperators();
Map<String, PlanReportroryItem> nameOperatorMap = new HashMap<>();
for (PlanReportroryItem op : operators) {
nameOperatorMap.put(op.getName(), op);
}
Map<Fluent, ActionDispatch> fluentActionDispatchMap = new HashMap<>();
for (Fluent fl : timePointActivityMap.values()) {
String actionName= fl.getCompoundSymbolicVariable().getPredicateName();
ActionDispatch actionDispatch = new ActionDispatch(fl.getID(), actionName);
actionDispatch.duration = (fl.getAllenInterval().getEET() - fl.getAllenInterval().getEST()) / 1000;
String[] opArgNames = nameOperatorMap.get(actionName).getStringArgumentNames();
String[] flArgs = fl.getCompoundSymbolicVariable().getArgs();
for (int i = 0; i < flArgs.length; i++) {
String key = opArgNames[i];
// remove leading '?'
if (key.length() > 0 && key.charAt(0) == '?') {
key = key.substring(1);
}
actionDispatch.parameters.add(new KeyValue(key, flArgs[i]));
}
actionDispatch.dispatch_time = fl.getAllenInterval().getEST() / 1000;
fluentActionDispatchMap.put(fl, actionDispatch);
}
return fluentActionDispatchMap;
}
public static Map<TimePoint, Fluent> getTimePointActivityMap(FluentNetworkSolver fluentSolver) {
Map<TimePoint, Fluent> timePointActivityMap = new HashMap<>();
for (Variable activityVar : fluentSolver.getVariables(Fluent.ACTIVITY_TYPE_STR)) {
Fluent activity = (Fluent) activityVar;
timePointActivityMap.put(activity.getAllenInterval().getStart(), activity);
timePointActivityMap.put(activity.getAllenInterval().getEnd(), activity);
}
return timePointActivityMap;
}
public static APSPSolver getApspSolver(FluentNetworkSolver fluentSolver) {
AllenIntervalNetworkSolver aiSolver =
(AllenIntervalNetworkSolver) fluentSolver.getConstraintSolvers()[1];
APSPSolver apspSolver = (APSPSolver) aiSolver.getConstraintSolvers()[0];
return apspSolver;
}
/**
* Compute implicit constraints in between activities for between which a path exists.
* @param fluentSolver
* @return List of implicit constraints between activities.
*/
public static List<SimpleDistanceConstraint> calcAdditionalConstraints(FluentNetworkSolver fluentSolver) {
APSPSolver apspSolver = getApspSolver(fluentSolver);
// Copy temporal constraint network to dummy cn
ConstraintNetwork cn = (ConstraintNetwork) apspSolver.getConstraintNetwork().clone();
List<SimpleDistanceConstraint> additionalConsList = new ArrayList<>();
// [0,0]-constraints are relevant in both directions, therefore we also need edges in both directions
// Add reverse constraints for constraints [0,0]-constraints from end-timepoint to end-timepoint
for (Constraint con : cn.getConstraints()) {
SimpleDistanceConstraint dst = (SimpleDistanceConstraint) con;
if (isEndpoint(dst.getFrom()) && isEndpoint(dst.getTo()) &&
dst.getMinimum() == 0 && dst.getMaximum() == 0) {
additionalConsList.add(createReverseConstraint(dst));
}
}
cn.addConstraints(additionalConsList.toArray(new SimpleDistanceConstraint[additionalConsList.size()]));
// Replace fluents that are not activities
for (Variable v : fluentSolver.getVariables()) {
Fluent fl = (Fluent) v;
if (!fl.isActivity()) {
TimePoint start = fl.getAllenInterval().getStart();
additionalConsList.addAll(replaceNode(cn, start));
TimePoint end = fl.getAllenInterval().getEnd();
additionalConsList.addAll(replaceNode(cn, end));
}
}
return additionalConsList;
}
//
/**
* Check if the temporal variable represents a start or end point.
*
* Assumes that ids of endpoints are odd.
* @return true if the temporal variable is a endpoint, false if it as startpoint
*/
private static boolean isEndpoint(Variable var) {
return (var.getID() % 2) == 1;
}
private static SimpleDistanceConstraint createReverseConstraint(SimpleDistanceConstraint con) {
SimpleDistanceConstraint reverseCon = new SimpleDistanceConstraint();
reverseCon.setMinimum(con.getMinimum());
reverseCon.setMaximum(con.getMaximum());
reverseCon.setFrom(con.getTo());
reverseCon.setTo(con.getFrom());
return reverseCon;
}
public static List<SimpleDistanceConstraint> replaceNode(ConstraintNetwork cn, TimePoint tp) {
List<SimpleDistanceConstraint> newConstraints = new ArrayList<>();
for (Constraint inConstraint : cn.getIngoingEdges(tp)) {
SimpleDistanceConstraint inDistCon = (SimpleDistanceConstraint) inConstraint;
if (inDistCon.getFrom().getID() < tp.getID())
continue; // skip node that has already been processed
for (Constraint outConstraint : cn.getOutgoingEdges(tp)) {
SimpleDistanceConstraint outDistCon = (SimpleDistanceConstraint) outConstraint;
if (outDistCon.getTo().getID() < tp.getID())
continue; // skip node that has already been processed
SimpleDistanceConstraint sumDistCon = new SimpleDistanceConstraint();
if (inDistCon.getMinimum() == APSPSolver.INF || outDistCon.getMinimum() == APSPSolver.INF) {
sumDistCon.setMinimum(APSPSolver.INF);
} else {
sumDistCon.setMinimum(inDistCon.getMinimum() + outDistCon.getMinimum());
}
if (inDistCon.getMaximum() == APSPSolver.INF || outDistCon.getMaximum() == APSPSolver.INF) {
sumDistCon.setMaximum(APSPSolver.INF);
} else {
sumDistCon.setMaximum(inDistCon.getMaximum() + outDistCon.getMaximum());
}
sumDistCon.setFrom(inDistCon.getFrom());
sumDistCon.setTo(outDistCon.getTo());
if(sumDistCon.getFrom().getID() == sumDistCon.getTo().getID()) {
// System.out.println("Found self-constraint: " + sumDistCon.toString());
} else {
newConstraints.add(sumDistCon);
cn.addConstraint(sumDistCon);
}
// System.out.println("Replacement for " + inDistCon.toString() + " and " + outDistCon.toString() + ":");
// System.out.println(" -> " + sumDistCon.toString());
}
}
return newConstraints;
}
}
| |
package net.vrallev.android.task.demo;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Toast;
import net.vrallev.android.task.Task;
import net.vrallev.android.task.TaskExecutor;
import net.vrallev.android.task.TaskResult;
import java.util.Iterator;
import java.util.List;
/**
* @author rwondratschek
*/
@SuppressWarnings("UnusedDeclaration")
public class MainActivity extends Activity {
private static final String ANNOTATION_ID = "annotationId";
private static final String TASK_ID_KEY = "TASK_ID_KEY";
private static final String TASK_ID_PERMISSION_KEY = "TASK_ID_PERMISSION_KEY";
private int mTaskId;
private int mTaskIdPermission;
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
mTaskId = savedInstanceState.getInt(TASK_ID_KEY, -1);
mTaskIdPermission = savedInstanceState.getInt(TASK_ID_PERMISSION_KEY, -1);
} else {
mTaskId = -1;
mTaskIdPermission = -1;
}
}
@Override
protected void onStart() {
super.onStart();
if (mTaskId != -1) {
showDialog();
}
}
@Override
protected void onStop() {
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
super.onStop();
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(TASK_ID_KEY, mTaskId);
outState.putInt(TASK_ID_PERMISSION_KEY, mTaskIdPermission);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (mTaskIdPermission > 0) {
PermissionTask task = (PermissionTask) TaskExecutor.getInstance().getTask(mTaskIdPermission);
if (task != null) {
task.onRequestPermissionResult(requestCode, permissions, grantResults);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_default_activity:
testDefaultActivity();
break;
case R.id.button_support_fragment:
testSupportFragment();
break;
case R.id.button_integer:
testIntegerTask();
break;
case R.id.button_annotation_with_id:
testAnnotationWithId();
break;
case R.id.button_get_all_tasks:
testGetAllTasks();
break;
case R.id.button_shutdown_executor:
testShutdownExecutor();
break;
case R.id.button_list:
testArrayListTask();
break;
case R.id.button_double_fragment:
testDoubleFragment();
break;
case R.id.button_no_callback:
testNoCallback();
break;
case R.id.button_crash:
testCrashingTask();
break;
case R.id.button_open_transparent_activity:
testIntegerTask();
startActivity(new Intent(this, TransparentActivity.class));
break;
case R.id.button_open_view_pager_activity:
startActivity(new Intent(this, ViewPagerActivity.class));
break;
case R.id.button_permission:
testPermissionTask();
break;
case R.id.button_explain:
testExplain();
break;
case R.id.button_replace_callback:
testReplaceCallback();
break;
}
}
@TaskResult
public void onResult(Boolean result) {
Toast.makeText(this, "Result " + result, Toast.LENGTH_SHORT).show();
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
mTaskId = -1;
}
@TaskResult
public void onResult(Integer integer, IntegerTask task) {
Toast.makeText(this, "Result " + integer, Toast.LENGTH_SHORT).show();
}
@TaskResult(id = ANNOTATION_ID)
public void onResultWithId(Integer integer, Task<?> task) {
Toast.makeText(this, "Result with ID " + integer + ", finished = " + task.isFinished(), Toast.LENGTH_SHORT).show();
}
@TaskResult
public void onListResult(List<String> list) {
Toast.makeText(this, "List length " + (list == null ? null : list.size()), Toast.LENGTH_SHORT).show();
}
@TaskResult(id = "crash")
public void onCrashResult(Boolean result) {
}
@TaskResult(id = "permission")
public void onPermissionResult(Boolean result) {
Toast.makeText(this, "Permission " + result, Toast.LENGTH_SHORT).show();
}
@TaskResult(id = "explain")
public void onExplainResult(Boolean result) {
Toast.makeText(this, "Explain " + result, Toast.LENGTH_SHORT).show();
}
private void testDefaultActivity() {
mTaskId = TaskExecutor.getInstance().execute(new SimpleTask(), this);
showDialog();
}
private void testSupportFragment() {
startActivity(new Intent(this, FragmentTestActivity.class));
}
private void testIntegerTask() {
TaskExecutor.getInstance().execute(new IntegerTask(), this);
}
private void testAnnotationWithId() {
TaskExecutor.getInstance().execute(new IntegerTask(), this, ANNOTATION_ID);
}
private void testGetAllTasks() {
List<IntegerTask> allTasks = TaskExecutor.getInstance().getAllTasks(IntegerTask.class);
Iterator<IntegerTask> iterator = allTasks.iterator();
StringBuilder stringBuilder = new StringBuilder();
while (iterator.hasNext()) {
stringBuilder.append(iterator.next());
if (iterator.hasNext()) {
stringBuilder.append("\n\n");
}
}
new AlertDialog.Builder(this)
.setTitle("Tasks")
.setMessage(stringBuilder)
.setPositiveButton(android.R.string.ok, null)
.show();
}
private void testShutdownExecutor() {
TaskExecutor.getInstance().shutdown();
}
private void testArrayListTask() {
TaskExecutor.getInstance().execute(new ListTask(), this);
}
private void testDoubleFragment() {
startActivity(new Intent(this, DoubleFragmentActivity.class));
}
private void testNoCallback() {
TaskExecutor.getInstance().execute(new SimpleNoCallbackTask(), this);
}
private void testCrashingTask() {
TaskExecutor.getInstance().execute(new CrashingTask(), this, "crash");
}
private void testPermissionTask() {
mTaskIdPermission = TaskExecutor.getInstance().execute(new PermissionTask(), this, "permission");
}
private void testExplain() {
TaskExecutor.getInstance().execute(new ExplainActivity.ExplainTask(), this, "explain");
}
private void testReplaceCallback() {
for (int i = 0; i < 3; i++) {
new IntegerTask().start(this);
}
startActivity(new Intent(this, ReplaceCallbackActivity.class));
}
private void showDialog() {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.rotate_the_device));
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mTaskId != -1) {
SimpleTask task = (SimpleTask) TaskExecutor.getInstance().getTask(mTaskId);
if (task != null) {
task.cancel();
}
}
}
});
mProgressDialog.show();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.